From 75aaff301065c5b64f07cc38d90c2a2fe37e73db Mon Sep 17 00:00:00 2001 From: jakcron Date: Thu, 31 Jan 2019 17:10:19 +0800 Subject: [PATCH] Make source code about nstool only. --- .gitignore | 351 ++- .vscode/c_cpp_properties.json | 97 - .vscode/settings.json | 40 - .vscode/tasks.json | 21 - BUILDING.md | 19 + LICENSE | 48 +- NNTools.sln | 124 - NNTools.vcxproj | 119 - NNTools.vcxproj.filters | 17 - README.md | 93 +- build/visualstudio/nstool.sln | 129 + build/visualstudio/nstool/nstool.vcxproj | 194 ++ .../nstool/nstool.vcxproj.filters | 302 ++- lib/libes/include/nn/es/SectionHeader_V2.h | 58 - lib/libes/include/nn/es/TicketBody_V2.h | 103 - lib/libes/include/nn/es/ticket.h | 111 - lib/libes/libes.vcxproj | 134 - lib/libes/libes.vcxproj.filters | 39 - lib/libes/libes.vcxproj.user | 4 - lib/libes/makefile | 46 - lib/libes/source/SectionHeader_V2.cpp | 139 - lib/libes/source/TicketBody_V2.cpp | 326 --- lib/libfnd/include/fnd/AesCtrWrappedIFile.h | 32 - lib/libfnd/include/fnd/BitMath.h | 14 - lib/libfnd/include/fnd/Endian.h | 118 - lib/libfnd/include/fnd/Exception.h | 24 - lib/libfnd/include/fnd/IByteModel.h | 23 - lib/libfnd/include/fnd/IFile.h | 18 - .../include/fnd/LayeredIntegrityMetadata.h | 59 - .../fnd/LayeredIntegrityWrappedIFile.h | 47 - lib/libfnd/include/fnd/List.h | 167 -- lib/libfnd/include/fnd/OffsetAdjustedIFile.h | 23 - lib/libfnd/include/fnd/ResourceFileReader.h | 22 - lib/libfnd/include/fnd/SharedPtr.h | 141 -- lib/libfnd/include/fnd/SimpleFile.h | 54 - lib/libfnd/include/fnd/SimpleTextOutput.h | 23 - lib/libfnd/include/fnd/StringConv.h | 50 - lib/libfnd/include/fnd/Vec.h | 207 -- lib/libfnd/include/fnd/aes.h | 117 - lib/libfnd/include/fnd/base64.h | 14 - lib/libfnd/include/fnd/ecdsa.h | 83 - lib/libfnd/include/fnd/elf.h | 458 ---- lib/libfnd/include/fnd/io.h | 19 - lib/libfnd/include/fnd/lz4.h | 11 - lib/libfnd/include/fnd/rsa.h | 124 - lib/libfnd/include/fnd/sha.h | 89 - lib/libfnd/include/fnd/types.h | 16 - lib/libfnd/libfnd.vcxproj | 170 -- lib/libfnd/libfnd.vcxproj.filters | 144 -- lib/libfnd/libfnd.vcxproj.user | 4 - lib/libfnd/makefile | 46 - lib/libfnd/source/AesCtrWrappedIFile.cpp | 80 - lib/libfnd/source/Exception.cpp | 48 - .../source/LayeredIntegrityMetadata.cpp | 71 - .../source/LayeredIntegrityWrappedIFile.cpp | 191 -- lib/libfnd/source/OffsetAdjustedIFile.cpp | 47 - lib/libfnd/source/ResourceFileReader.cpp | 64 - lib/libfnd/source/SimpleFile.cpp | 331 --- lib/libfnd/source/SimpleTextOutput.cpp | 117 - lib/libfnd/source/StringConv.cpp | 147 -- lib/libfnd/source/aes_wrapper.cpp | 159 -- lib/libfnd/source/base64_wrapper.cpp | 30 - lib/libfnd/source/io.cpp | 74 - lib/libfnd/source/lz4_wrapper.cpp | 14 - lib/libfnd/source/rsa_wrapper.cpp | 214 -- lib/libfnd/source/sha_wrapper.cpp | 15 - lib/libhac-hb/include/nn/hac/AssetHeader.h | 72 - lib/libhac-hb/include/nn/hac/define/aset.h | 33 - lib/libhac-hb/include/nn/hac/define/nro-hb.h | 14 - lib/libhac-hb/libhac-hb.vcxproj | 134 - lib/libhac-hb/libhac-hb.vcxproj.filters | 39 - lib/libhac-hb/libhac-hb.vcxproj.user | 4 - lib/libhac-hb/makefile | 46 - lib/libhac-hb/source/AssetHeader.cpp | 135 - lib/libhac/include/nn/hac/AccessControlInfo.h | 57 - .../include/nn/hac/AccessControlInfoDesc.h | 92 - .../nn/hac/AddOnContentMetaExtendedHeader.h | 46 - lib/libhac/include/nn/hac/AesKeygen.h | 22 - .../nn/hac/ApplicationControlProperty.h | 272 -- .../nn/hac/ApplicationControlPropertyUtils.h | 15 - .../nn/hac/ApplicationMetaExtendedHeader.h | 46 - .../include/nn/hac/ContentArchiveHeader.h | 121 - .../include/nn/hac/ContentArchiveUtils.h | 17 - lib/libhac/include/nn/hac/ContentInfo.h | 59 - lib/libhac/include/nn/hac/ContentMeta.h | 113 - lib/libhac/include/nn/hac/ContentMetaInfo.h | 55 - .../include/nn/hac/DeltaMetaExtendedHeader.h | 47 - .../include/nn/hac/FileSystemAccessControl.h | 78 - lib/libhac/include/nn/hac/GameCardHeader.h | 127 - lib/libhac/include/nn/hac/GameCardUtils.h | 16 - .../include/nn/hac/HandleTableSizeEntry.h | 50 - .../include/nn/hac/HandleTableSizeHandler.h | 37 - .../nn/hac/HierarchicalIntegrityHeader.h | 70 - .../include/nn/hac/HierarchicalSha256Header.h | 71 - .../include/nn/hac/IKernelCapabilityHandler.h | 19 - lib/libhac/include/nn/hac/IdConverter.h | 21 - lib/libhac/include/nn/hac/IniHeader.h | 46 - lib/libhac/include/nn/hac/InteruptEntry.h | 58 - lib/libhac/include/nn/hac/InteruptHandler.h | 36 - .../include/nn/hac/KernelCapabilityControl.h | 78 - .../include/nn/hac/KernelCapabilityEntry.h | 57 - .../nn/hac/KernelInitialProcessHeader.h | 137 - .../include/nn/hac/KernelVersionEntry.h | 58 - .../include/nn/hac/KernelVersionHandler.h | 39 - .../include/nn/hac/MemoryMappingHandler.h | 80 - lib/libhac/include/nn/hac/MemoryPageEntry.h | 62 - lib/libhac/include/nn/hac/Meta.h | 80 - lib/libhac/include/nn/hac/MiscFlagsEntry.h | 50 - lib/libhac/include/nn/hac/MiscFlagsHandler.h | 57 - lib/libhac/include/nn/hac/MiscParamsEntry.h | 50 - lib/libhac/include/nn/hac/MiscParamsHandler.h | 37 - lib/libhac/include/nn/hac/NroHeader.h | 141 -- lib/libhac/include/nn/hac/NsoHeader.h | 149 -- lib/libhac/include/nn/hac/PartitionFsHeader.h | 100 - .../include/nn/hac/PatchMetaExtendedHeader.h | 51 - lib/libhac/include/nn/hac/Result.h | 39 - .../include/nn/hac/ServiceAccessControl.h | 42 - .../nn/hac/ServiceAccessControlEntry.h | 51 - lib/libhac/include/nn/hac/SystemCallEntry.h | 59 - lib/libhac/include/nn/hac/SystemCallHandler.h | 38 - lib/libhac/include/nn/hac/ThreadInfoEntry.h | 69 - lib/libhac/include/nn/hac/ThreadInfoHandler.h | 43 - lib/libhac/include/nn/hac/define/aci.h | 56 - lib/libhac/include/nn/hac/define/cnmt.h | 181 -- lib/libhac/include/nn/hac/define/delta.h | 26 - lib/libhac/include/nn/hac/define/fac.h | 60 - lib/libhac/include/nn/hac/define/gc.h | 133 - .../nn/hac/define/hierarchicalintegrity.h | 35 - .../nn/hac/define/hierarchicalsha256.h | 29 - lib/libhac/include/nn/hac/define/ini.h | 26 - lib/libhac/include/nn/hac/define/kc.h | 28 - lib/libhac/include/nn/hac/define/kip.h | 65 - lib/libhac/include/nn/hac/define/macro.h | 5 - lib/libhac/include/nn/hac/define/meta.h | 58 - lib/libhac/include/nn/hac/define/nacp.h | 289 --- lib/libhac/include/nn/hac/define/nca.h | 144 -- lib/libhac/include/nn/hac/define/nro.h | 45 - lib/libhac/include/nn/hac/define/nrr.h | 39 - lib/libhac/include/nn/hac/define/nso.h | 68 - lib/libhac/include/nn/hac/define/pfs.h | 45 - lib/libhac/include/nn/hac/define/romfs.h | 60 - lib/libhac/libhac.vcxproj | 246 -- lib/libhac/libhac.vcxproj.filters | 363 --- lib/libhac/libhac.vcxproj.user | 4 - lib/libhac/makefile | 46 - lib/libhac/source/AccessControlInfo.cpp | 173 -- lib/libhac/source/AccessControlInfoDesc.cpp | 251 -- .../source/AddOnContentMetaExtendedHeader.cpp | 84 - lib/libhac/source/AesKeygen.cpp | 19 - .../source/ApplicationControlProperty.cpp | 731 ------ .../ApplicationControlPropertyUtils.cpp | 11 - .../source/ApplicationMetaExtendedHeader.cpp | 84 - lib/libhac/source/ContentArchiveHeader.cpp | 334 --- lib/libhac/source/ContentArchiveUtils.cpp | 58 - lib/libhac/source/ContentInfo.cpp | 123 - lib/libhac/source/ContentMeta.cpp | 368 --- lib/libhac/source/ContentMetaInfo.cpp | 114 - lib/libhac/source/DeltaMetaExtendedHeader.cpp | 84 - lib/libhac/source/FileSystemAccessControl.cpp | 219 -- lib/libhac/source/GameCardHeader.cpp | 480 ---- lib/libhac/source/GameCardUtils.cpp | 22 - lib/libhac/source/HandleTableSizeEntry.cpp | 69 - lib/libhac/source/HandleTableSizeHandler.cpp | 67 - .../source/HierarchicalIntegrityHeader.cpp | 137 - .../source/HierarchicalSha256Header.cpp | 112 - lib/libhac/source/IdConverter.cpp | 16 - lib/libhac/source/IniHeader.cpp | 114 - lib/libhac/source/InteruptEntry.cpp | 78 - lib/libhac/source/InteruptHandler.cpp | 111 - lib/libhac/source/KernelCapabilityControl.cpp | 234 -- lib/libhac/source/KernelCapabilityEntry.cpp | 63 - .../source/KernelInitialProcessHeader.cpp | 346 --- lib/libhac/source/KernelVersionEntry.cpp | 90 - lib/libhac/source/KernelVersionHandler.cpp | 80 - lib/libhac/source/MemoryMappingHandler.cpp | 139 - lib/libhac/source/MemoryPageEntry.cpp | 109 - lib/libhac/source/Meta.cpp | 295 --- lib/libhac/source/MiscFlagsEntry.cpp | 68 - lib/libhac/source/MiscFlagsHandler.cpp | 89 - lib/libhac/source/MiscParamsEntry.cpp | 68 - lib/libhac/source/MiscParamsHandler.cpp | 68 - lib/libhac/source/NroHeader.cpp | 270 -- lib/libhac/source/NsoHeader.cpp | 306 --- lib/libhac/source/PartitionFsHeader.cpp | 253 -- lib/libhac/source/PatchMetaExtendedHeader.cpp | 99 - lib/libhac/source/Result.cpp | 62 - lib/libhac/source/ServiceAccessControl.cpp | 79 - .../source/ServiceAccessControlEntry.cpp | 132 - lib/libhac/source/SystemCallEntry.cpp | 92 - lib/libhac/source/SystemCallHandler.cpp | 113 - lib/libhac/source/ThreadInfoEntry.cpp | 134 - lib/libhac/source/ThreadInfoHandler.cpp | 103 - lib/liblz4/include/lz4.h | 607 ----- lib/liblz4/liblz4.vcxproj | 132 - lib/liblz4/liblz4.vcxproj.filters | 30 - lib/liblz4/liblz4.vcxproj.user | 4 - lib/liblz4/makefile | 45 - lib/liblz4/source/lz4.c | 1930 -------------- lib/libpki/include/nn/pki/CertificateBody.h | 67 - lib/libpki/include/nn/pki/SignUtils.h | 17 - lib/libpki/include/nn/pki/SignatureBlock.h | 51 - lib/libpki/include/nn/pki/SignedData.h | 139 - lib/libpki/include/nn/pki/cert.h | 54 - lib/libpki/include/nn/pki/sign.h | 65 - lib/libpki/libpki.vcxproj | 143 -- lib/libpki/libpki.vcxproj.filters | 51 - lib/libpki/libpki.vcxproj.user | 4 - lib/libpki/makefile | 45 - lib/libpki/source/CertificateBody.cpp | 254 -- lib/libpki/source/SignUtils.cpp | 45 - lib/libpki/source/SignatureBlock.cpp | 182 -- lib/libpolarssl/include/polarssl/aes.h | 203 -- lib/libpolarssl/include/polarssl/base64.h | 88 - lib/libpolarssl/include/polarssl/bignum.h | 685 ----- lib/libpolarssl/include/polarssl/bn_mul.h | 864 ------- lib/libpolarssl/include/polarssl/config.h | 1013 -------- lib/libpolarssl/include/polarssl/ctr_drbg.h | 234 -- lib/libpolarssl/include/polarssl/entropy.h | 180 -- .../include/polarssl/entropy_poll.h | 72 - lib/libpolarssl/include/polarssl/md.h | 357 --- lib/libpolarssl/include/polarssl/md_wrap.h | 61 - lib/libpolarssl/include/polarssl/rsa.h | 597 ----- lib/libpolarssl/include/polarssl/sha1.h | 180 -- lib/libpolarssl/include/polarssl/sha2.h | 183 -- lib/libpolarssl/include/polarssl/sha4.h | 183 -- lib/libpolarssl/libpolarssl.vcxproj | 156 -- lib/libpolarssl/libpolarssl.vcxproj.filters | 102 - lib/libpolarssl/libpolarssl.vcxproj.user | 4 - lib/libpolarssl/makefile | 45 - lib/libpolarssl/source/aes.c | 1352 ---------- lib/libpolarssl/source/base64.c | 269 -- lib/libpolarssl/source/bignum.c | 2135 ---------------- lib/libpolarssl/source/ctr_drbg.c | 582 ----- lib/libpolarssl/source/entropy.c | 261 -- lib/libpolarssl/source/entropy_poll.c | 133 - lib/libpolarssl/source/md.c | 300 --- lib/libpolarssl/source/md_wrap.c | 743 ------ lib/libpolarssl/source/rsa.c | 1466 ----------- lib/libpolarssl/source/sha1.c | 624 ----- lib/libpolarssl/source/sha2.c | 705 ------ lib/libpolarssl/source/sha4.c | 762 ------ makefile | 152 +- programs/nstool/README.md | 80 - programs/nstool/makefile | 48 - programs/nstool/nstool.vcxproj | 230 -- programs/nstool/nstool.vcxproj.user | 23 - .../nstool/source => src}/AssetProcess.cpp | 0 .../nstool/source => src}/AssetProcess.h | 0 .../nstool/source => src}/CnmtProcess.cpp | 498 ++-- {programs/nstool/source => src}/CnmtProcess.h | 78 +- .../nstool/source => src}/ElfSymbolParser.cpp | 0 .../nstool/source => src}/ElfSymbolParser.h | 0 .../nstool/source => src}/EsTikProcess.cpp | 0 .../nstool/source => src}/EsTikProcess.h | 0 .../nstool/source => src}/GameCardProcess.cpp | 0 .../nstool/source => src}/GameCardProcess.h | 0 .../nstool/source => src}/IniProcess.cpp | 0 {programs/nstool/source => src}/IniProcess.h | 0 .../source => src}/KeyConfiguration.cpp | 750 +++--- .../nstool/source => src}/KeyConfiguration.h | 416 +-- .../nstool/source => src}/KipProcess.cpp | 0 {programs/nstool/source => src}/KipProcess.h | 0 .../nstool/source => src}/MetaProcess.cpp | 2234 ++++++++--------- {programs/nstool/source => src}/MetaProcess.h | 110 +- .../nstool/source => src}/NacpProcess.cpp | 1336 +++++----- {programs/nstool/source => src}/NacpProcess.h | 108 +- .../nstool/source => src}/NcaProcess.cpp | 1666 ++++++------ {programs/nstool/source => src}/NcaProcess.h | 244 +- .../nstool/source => src}/NroProcess.cpp | 342 +-- {programs/nstool/source => src}/NroProcess.h | 104 +- .../nstool/source => src}/NsoProcess.cpp | 472 ++-- {programs/nstool/source => src}/NsoProcess.h | 92 +- .../nstool/source => src}/PfsProcess.cpp | 0 {programs/nstool/source => src}/PfsProcess.h | 0 .../nstool/source => src}/PkiCertProcess.cpp | 0 .../nstool/source => src}/PkiCertProcess.h | 0 .../nstool/source => src}/PkiValidator.cpp | 0 .../nstool/source => src}/PkiValidator.h | 0 .../source => src}/RoMetadataProcess.cpp | 564 ++--- .../nstool/source => src}/RoMetadataProcess.h | 134 +- .../nstool/source => src}/RomfsProcess.cpp | 0 .../nstool/source => src}/RomfsProcess.h | 266 +- .../nstool/source => src}/SdkApiString.cpp | 0 .../nstool/source => src}/SdkApiString.h | 0 .../nstool/source => src}/UserSettings.cpp | 2118 ++++++++-------- .../nstool/source => src}/UserSettings.h | 274 +- {programs/nstool/source => src}/common.h | 122 +- {programs/nstool/source => src}/main.cpp | 512 ++-- {programs/nstool/source => src}/version.h | 0 289 files changed, 7258 insertions(+), 43389 deletions(-) delete mode 100644 .vscode/c_cpp_properties.json delete mode 100644 .vscode/settings.json delete mode 100644 .vscode/tasks.json create mode 100644 BUILDING.md delete mode 100644 NNTools.sln delete mode 100644 NNTools.vcxproj delete mode 100644 NNTools.vcxproj.filters create mode 100644 build/visualstudio/nstool.sln create mode 100644 build/visualstudio/nstool/nstool.vcxproj rename {programs => build/visualstudio}/nstool/nstool.vcxproj.filters (57%) delete mode 100644 lib/libes/include/nn/es/SectionHeader_V2.h delete mode 100644 lib/libes/include/nn/es/TicketBody_V2.h delete mode 100644 lib/libes/include/nn/es/ticket.h delete mode 100644 lib/libes/libes.vcxproj delete mode 100644 lib/libes/libes.vcxproj.filters delete mode 100644 lib/libes/libes.vcxproj.user delete mode 100644 lib/libes/makefile delete mode 100644 lib/libes/source/SectionHeader_V2.cpp delete mode 100644 lib/libes/source/TicketBody_V2.cpp delete mode 100644 lib/libfnd/include/fnd/AesCtrWrappedIFile.h delete mode 100644 lib/libfnd/include/fnd/BitMath.h delete mode 100644 lib/libfnd/include/fnd/Endian.h delete mode 100644 lib/libfnd/include/fnd/Exception.h delete mode 100644 lib/libfnd/include/fnd/IByteModel.h delete mode 100644 lib/libfnd/include/fnd/IFile.h delete mode 100644 lib/libfnd/include/fnd/LayeredIntegrityMetadata.h delete mode 100644 lib/libfnd/include/fnd/LayeredIntegrityWrappedIFile.h delete mode 100644 lib/libfnd/include/fnd/List.h delete mode 100644 lib/libfnd/include/fnd/OffsetAdjustedIFile.h delete mode 100644 lib/libfnd/include/fnd/ResourceFileReader.h delete mode 100644 lib/libfnd/include/fnd/SharedPtr.h delete mode 100644 lib/libfnd/include/fnd/SimpleFile.h delete mode 100644 lib/libfnd/include/fnd/SimpleTextOutput.h delete mode 100644 lib/libfnd/include/fnd/StringConv.h delete mode 100644 lib/libfnd/include/fnd/Vec.h delete mode 100644 lib/libfnd/include/fnd/aes.h delete mode 100644 lib/libfnd/include/fnd/base64.h delete mode 100644 lib/libfnd/include/fnd/ecdsa.h delete mode 100644 lib/libfnd/include/fnd/elf.h delete mode 100644 lib/libfnd/include/fnd/io.h delete mode 100644 lib/libfnd/include/fnd/lz4.h delete mode 100644 lib/libfnd/include/fnd/rsa.h delete mode 100644 lib/libfnd/include/fnd/sha.h delete mode 100644 lib/libfnd/include/fnd/types.h delete mode 100644 lib/libfnd/libfnd.vcxproj delete mode 100644 lib/libfnd/libfnd.vcxproj.filters delete mode 100644 lib/libfnd/libfnd.vcxproj.user delete mode 100644 lib/libfnd/makefile delete mode 100644 lib/libfnd/source/AesCtrWrappedIFile.cpp delete mode 100644 lib/libfnd/source/Exception.cpp delete mode 100644 lib/libfnd/source/LayeredIntegrityMetadata.cpp delete mode 100644 lib/libfnd/source/LayeredIntegrityWrappedIFile.cpp delete mode 100644 lib/libfnd/source/OffsetAdjustedIFile.cpp delete mode 100644 lib/libfnd/source/ResourceFileReader.cpp delete mode 100644 lib/libfnd/source/SimpleFile.cpp delete mode 100644 lib/libfnd/source/SimpleTextOutput.cpp delete mode 100644 lib/libfnd/source/StringConv.cpp delete mode 100644 lib/libfnd/source/aes_wrapper.cpp delete mode 100644 lib/libfnd/source/base64_wrapper.cpp delete mode 100644 lib/libfnd/source/io.cpp delete mode 100644 lib/libfnd/source/lz4_wrapper.cpp delete mode 100644 lib/libfnd/source/rsa_wrapper.cpp delete mode 100644 lib/libfnd/source/sha_wrapper.cpp delete mode 100644 lib/libhac-hb/include/nn/hac/AssetHeader.h delete mode 100644 lib/libhac-hb/include/nn/hac/define/aset.h delete mode 100644 lib/libhac-hb/include/nn/hac/define/nro-hb.h delete mode 100644 lib/libhac-hb/libhac-hb.vcxproj delete mode 100644 lib/libhac-hb/libhac-hb.vcxproj.filters delete mode 100644 lib/libhac-hb/libhac-hb.vcxproj.user delete mode 100644 lib/libhac-hb/makefile delete mode 100644 lib/libhac-hb/source/AssetHeader.cpp delete mode 100644 lib/libhac/include/nn/hac/AccessControlInfo.h delete mode 100644 lib/libhac/include/nn/hac/AccessControlInfoDesc.h delete mode 100644 lib/libhac/include/nn/hac/AddOnContentMetaExtendedHeader.h delete mode 100644 lib/libhac/include/nn/hac/AesKeygen.h delete mode 100644 lib/libhac/include/nn/hac/ApplicationControlProperty.h delete mode 100644 lib/libhac/include/nn/hac/ApplicationControlPropertyUtils.h delete mode 100644 lib/libhac/include/nn/hac/ApplicationMetaExtendedHeader.h delete mode 100644 lib/libhac/include/nn/hac/ContentArchiveHeader.h delete mode 100644 lib/libhac/include/nn/hac/ContentArchiveUtils.h delete mode 100644 lib/libhac/include/nn/hac/ContentInfo.h delete mode 100644 lib/libhac/include/nn/hac/ContentMeta.h delete mode 100644 lib/libhac/include/nn/hac/ContentMetaInfo.h delete mode 100644 lib/libhac/include/nn/hac/DeltaMetaExtendedHeader.h delete mode 100644 lib/libhac/include/nn/hac/FileSystemAccessControl.h delete mode 100644 lib/libhac/include/nn/hac/GameCardHeader.h delete mode 100644 lib/libhac/include/nn/hac/GameCardUtils.h delete mode 100644 lib/libhac/include/nn/hac/HandleTableSizeEntry.h delete mode 100644 lib/libhac/include/nn/hac/HandleTableSizeHandler.h delete mode 100644 lib/libhac/include/nn/hac/HierarchicalIntegrityHeader.h delete mode 100644 lib/libhac/include/nn/hac/HierarchicalSha256Header.h delete mode 100644 lib/libhac/include/nn/hac/IKernelCapabilityHandler.h delete mode 100644 lib/libhac/include/nn/hac/IdConverter.h delete mode 100644 lib/libhac/include/nn/hac/IniHeader.h delete mode 100644 lib/libhac/include/nn/hac/InteruptEntry.h delete mode 100644 lib/libhac/include/nn/hac/InteruptHandler.h delete mode 100644 lib/libhac/include/nn/hac/KernelCapabilityControl.h delete mode 100644 lib/libhac/include/nn/hac/KernelCapabilityEntry.h delete mode 100644 lib/libhac/include/nn/hac/KernelInitialProcessHeader.h delete mode 100644 lib/libhac/include/nn/hac/KernelVersionEntry.h delete mode 100644 lib/libhac/include/nn/hac/KernelVersionHandler.h delete mode 100644 lib/libhac/include/nn/hac/MemoryMappingHandler.h delete mode 100644 lib/libhac/include/nn/hac/MemoryPageEntry.h delete mode 100644 lib/libhac/include/nn/hac/Meta.h delete mode 100644 lib/libhac/include/nn/hac/MiscFlagsEntry.h delete mode 100644 lib/libhac/include/nn/hac/MiscFlagsHandler.h delete mode 100644 lib/libhac/include/nn/hac/MiscParamsEntry.h delete mode 100644 lib/libhac/include/nn/hac/MiscParamsHandler.h delete mode 100644 lib/libhac/include/nn/hac/NroHeader.h delete mode 100644 lib/libhac/include/nn/hac/NsoHeader.h delete mode 100644 lib/libhac/include/nn/hac/PartitionFsHeader.h delete mode 100644 lib/libhac/include/nn/hac/PatchMetaExtendedHeader.h delete mode 100644 lib/libhac/include/nn/hac/Result.h delete mode 100644 lib/libhac/include/nn/hac/ServiceAccessControl.h delete mode 100644 lib/libhac/include/nn/hac/ServiceAccessControlEntry.h delete mode 100644 lib/libhac/include/nn/hac/SystemCallEntry.h delete mode 100644 lib/libhac/include/nn/hac/SystemCallHandler.h delete mode 100644 lib/libhac/include/nn/hac/ThreadInfoEntry.h delete mode 100644 lib/libhac/include/nn/hac/ThreadInfoHandler.h delete mode 100644 lib/libhac/include/nn/hac/define/aci.h delete mode 100644 lib/libhac/include/nn/hac/define/cnmt.h delete mode 100644 lib/libhac/include/nn/hac/define/delta.h delete mode 100644 lib/libhac/include/nn/hac/define/fac.h delete mode 100644 lib/libhac/include/nn/hac/define/gc.h delete mode 100644 lib/libhac/include/nn/hac/define/hierarchicalintegrity.h delete mode 100644 lib/libhac/include/nn/hac/define/hierarchicalsha256.h delete mode 100644 lib/libhac/include/nn/hac/define/ini.h delete mode 100644 lib/libhac/include/nn/hac/define/kc.h delete mode 100644 lib/libhac/include/nn/hac/define/kip.h delete mode 100644 lib/libhac/include/nn/hac/define/macro.h delete mode 100644 lib/libhac/include/nn/hac/define/meta.h delete mode 100644 lib/libhac/include/nn/hac/define/nacp.h delete mode 100644 lib/libhac/include/nn/hac/define/nca.h delete mode 100644 lib/libhac/include/nn/hac/define/nro.h delete mode 100644 lib/libhac/include/nn/hac/define/nrr.h delete mode 100644 lib/libhac/include/nn/hac/define/nso.h delete mode 100644 lib/libhac/include/nn/hac/define/pfs.h delete mode 100644 lib/libhac/include/nn/hac/define/romfs.h delete mode 100644 lib/libhac/libhac.vcxproj delete mode 100644 lib/libhac/libhac.vcxproj.filters delete mode 100644 lib/libhac/libhac.vcxproj.user delete mode 100644 lib/libhac/makefile delete mode 100644 lib/libhac/source/AccessControlInfo.cpp delete mode 100644 lib/libhac/source/AccessControlInfoDesc.cpp delete mode 100644 lib/libhac/source/AddOnContentMetaExtendedHeader.cpp delete mode 100644 lib/libhac/source/AesKeygen.cpp delete mode 100644 lib/libhac/source/ApplicationControlProperty.cpp delete mode 100644 lib/libhac/source/ApplicationControlPropertyUtils.cpp delete mode 100644 lib/libhac/source/ApplicationMetaExtendedHeader.cpp delete mode 100644 lib/libhac/source/ContentArchiveHeader.cpp delete mode 100644 lib/libhac/source/ContentArchiveUtils.cpp delete mode 100644 lib/libhac/source/ContentInfo.cpp delete mode 100644 lib/libhac/source/ContentMeta.cpp delete mode 100644 lib/libhac/source/ContentMetaInfo.cpp delete mode 100644 lib/libhac/source/DeltaMetaExtendedHeader.cpp delete mode 100644 lib/libhac/source/FileSystemAccessControl.cpp delete mode 100644 lib/libhac/source/GameCardHeader.cpp delete mode 100644 lib/libhac/source/GameCardUtils.cpp delete mode 100644 lib/libhac/source/HandleTableSizeEntry.cpp delete mode 100644 lib/libhac/source/HandleTableSizeHandler.cpp delete mode 100644 lib/libhac/source/HierarchicalIntegrityHeader.cpp delete mode 100644 lib/libhac/source/HierarchicalSha256Header.cpp delete mode 100644 lib/libhac/source/IdConverter.cpp delete mode 100644 lib/libhac/source/IniHeader.cpp delete mode 100644 lib/libhac/source/InteruptEntry.cpp delete mode 100644 lib/libhac/source/InteruptHandler.cpp delete mode 100644 lib/libhac/source/KernelCapabilityControl.cpp delete mode 100644 lib/libhac/source/KernelCapabilityEntry.cpp delete mode 100644 lib/libhac/source/KernelInitialProcessHeader.cpp delete mode 100644 lib/libhac/source/KernelVersionEntry.cpp delete mode 100644 lib/libhac/source/KernelVersionHandler.cpp delete mode 100644 lib/libhac/source/MemoryMappingHandler.cpp delete mode 100644 lib/libhac/source/MemoryPageEntry.cpp delete mode 100644 lib/libhac/source/Meta.cpp delete mode 100644 lib/libhac/source/MiscFlagsEntry.cpp delete mode 100644 lib/libhac/source/MiscFlagsHandler.cpp delete mode 100644 lib/libhac/source/MiscParamsEntry.cpp delete mode 100644 lib/libhac/source/MiscParamsHandler.cpp delete mode 100644 lib/libhac/source/NroHeader.cpp delete mode 100644 lib/libhac/source/NsoHeader.cpp delete mode 100644 lib/libhac/source/PartitionFsHeader.cpp delete mode 100644 lib/libhac/source/PatchMetaExtendedHeader.cpp delete mode 100644 lib/libhac/source/Result.cpp delete mode 100644 lib/libhac/source/ServiceAccessControl.cpp delete mode 100644 lib/libhac/source/ServiceAccessControlEntry.cpp delete mode 100644 lib/libhac/source/SystemCallEntry.cpp delete mode 100644 lib/libhac/source/SystemCallHandler.cpp delete mode 100644 lib/libhac/source/ThreadInfoEntry.cpp delete mode 100644 lib/libhac/source/ThreadInfoHandler.cpp delete mode 100644 lib/liblz4/include/lz4.h delete mode 100644 lib/liblz4/liblz4.vcxproj delete mode 100644 lib/liblz4/liblz4.vcxproj.filters delete mode 100644 lib/liblz4/liblz4.vcxproj.user delete mode 100644 lib/liblz4/makefile delete mode 100644 lib/liblz4/source/lz4.c delete mode 100644 lib/libpki/include/nn/pki/CertificateBody.h delete mode 100644 lib/libpki/include/nn/pki/SignUtils.h delete mode 100644 lib/libpki/include/nn/pki/SignatureBlock.h delete mode 100644 lib/libpki/include/nn/pki/SignedData.h delete mode 100644 lib/libpki/include/nn/pki/cert.h delete mode 100644 lib/libpki/include/nn/pki/sign.h delete mode 100644 lib/libpki/libpki.vcxproj delete mode 100644 lib/libpki/libpki.vcxproj.filters delete mode 100644 lib/libpki/libpki.vcxproj.user delete mode 100644 lib/libpki/makefile delete mode 100644 lib/libpki/source/CertificateBody.cpp delete mode 100644 lib/libpki/source/SignUtils.cpp delete mode 100644 lib/libpki/source/SignatureBlock.cpp delete mode 100644 lib/libpolarssl/include/polarssl/aes.h delete mode 100644 lib/libpolarssl/include/polarssl/base64.h delete mode 100644 lib/libpolarssl/include/polarssl/bignum.h delete mode 100644 lib/libpolarssl/include/polarssl/bn_mul.h delete mode 100644 lib/libpolarssl/include/polarssl/config.h delete mode 100644 lib/libpolarssl/include/polarssl/ctr_drbg.h delete mode 100644 lib/libpolarssl/include/polarssl/entropy.h delete mode 100644 lib/libpolarssl/include/polarssl/entropy_poll.h delete mode 100644 lib/libpolarssl/include/polarssl/md.h delete mode 100644 lib/libpolarssl/include/polarssl/md_wrap.h delete mode 100644 lib/libpolarssl/include/polarssl/rsa.h delete mode 100644 lib/libpolarssl/include/polarssl/sha1.h delete mode 100644 lib/libpolarssl/include/polarssl/sha2.h delete mode 100644 lib/libpolarssl/include/polarssl/sha4.h delete mode 100644 lib/libpolarssl/libpolarssl.vcxproj delete mode 100644 lib/libpolarssl/libpolarssl.vcxproj.filters delete mode 100644 lib/libpolarssl/libpolarssl.vcxproj.user delete mode 100644 lib/libpolarssl/makefile delete mode 100644 lib/libpolarssl/source/aes.c delete mode 100644 lib/libpolarssl/source/base64.c delete mode 100644 lib/libpolarssl/source/bignum.c delete mode 100644 lib/libpolarssl/source/ctr_drbg.c delete mode 100644 lib/libpolarssl/source/entropy.c delete mode 100644 lib/libpolarssl/source/entropy_poll.c delete mode 100644 lib/libpolarssl/source/md.c delete mode 100644 lib/libpolarssl/source/md_wrap.c delete mode 100644 lib/libpolarssl/source/rsa.c delete mode 100644 lib/libpolarssl/source/sha1.c delete mode 100644 lib/libpolarssl/source/sha2.c delete mode 100644 lib/libpolarssl/source/sha4.c delete mode 100644 programs/nstool/README.md delete mode 100644 programs/nstool/makefile delete mode 100644 programs/nstool/nstool.vcxproj delete mode 100644 programs/nstool/nstool.vcxproj.user rename {programs/nstool/source => src}/AssetProcess.cpp (100%) rename {programs/nstool/source => src}/AssetProcess.h (100%) rename {programs/nstool/source => src}/CnmtProcess.cpp (97%) rename {programs/nstool/source => src}/CnmtProcess.h (96%) rename {programs/nstool/source => src}/ElfSymbolParser.cpp (100%) rename {programs/nstool/source => src}/ElfSymbolParser.h (100%) rename {programs/nstool/source => src}/EsTikProcess.cpp (100%) rename {programs/nstool/source => src}/EsTikProcess.h (100%) rename {programs/nstool/source => src}/GameCardProcess.cpp (100%) rename {programs/nstool/source => src}/GameCardProcess.h (100%) rename {programs/nstool/source => src}/IniProcess.cpp (100%) rename {programs/nstool/source => src}/IniProcess.h (100%) rename {programs/nstool/source => src}/KeyConfiguration.cpp (97%) rename {programs/nstool/source => src}/KeyConfiguration.h (97%) rename {programs/nstool/source => src}/KipProcess.cpp (100%) rename {programs/nstool/source => src}/KipProcess.h (100%) rename {programs/nstool/source => src}/MetaProcess.cpp (96%) rename {programs/nstool/source => src}/MetaProcess.h (97%) rename {programs/nstool/source => src}/NacpProcess.cpp (96%) rename {programs/nstool/source => src}/NacpProcess.h (97%) rename {programs/nstool/source => src}/NcaProcess.cpp (96%) rename {programs/nstool/source => src}/NcaProcess.h (96%) rename {programs/nstool/source => src}/NroProcess.cpp (96%) rename {programs/nstool/source => src}/NroProcess.h (96%) rename {programs/nstool/source => src}/NsoProcess.cpp (97%) rename {programs/nstool/source => src}/NsoProcess.h (95%) rename {programs/nstool/source => src}/PfsProcess.cpp (100%) rename {programs/nstool/source => src}/PfsProcess.h (100%) rename {programs/nstool/source => src}/PkiCertProcess.cpp (100%) rename {programs/nstool/source => src}/PkiCertProcess.h (100%) rename {programs/nstool/source => src}/PkiValidator.cpp (100%) rename {programs/nstool/source => src}/PkiValidator.h (100%) rename {programs/nstool/source => src}/RoMetadataProcess.cpp (95%) rename {programs/nstool/source => src}/RoMetadataProcess.h (96%) rename {programs/nstool/source => src}/RomfsProcess.cpp (100%) rename {programs/nstool/source => src}/RomfsProcess.h (95%) rename {programs/nstool/source => src}/SdkApiString.cpp (100%) rename {programs/nstool/source => src}/SdkApiString.h (100%) rename {programs/nstool/source => src}/UserSettings.cpp (96%) rename {programs/nstool/source => src}/UserSettings.h (97%) rename {programs/nstool/source => src}/common.h (96%) rename {programs/nstool/source => src}/main.cpp (96%) rename {programs/nstool/source => src}/version.h (100%) diff --git a/.gitignore b/.gitignore index 6013d18..acccb6a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,20 +1,335 @@ -################################################################################ -# This .gitignore file was automatically created by Microsoft(R) Visual Studio. -################################################################################ - -/.vs -*.a +bin/* *.o -*.exe -*.db -*.opendb +*.a +*.so.* + +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ +**/Properties/launchSettings.json + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj *.log -/bin/* -/*/*/Debug -/*/*/x64 -/*/*/bin -/x64 -/Debug -/test -/sample -.DS_Store +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json deleted file mode 100644 index d7e3785..0000000 --- a/.vscode/c_cpp_properties.json +++ /dev/null @@ -1,97 +0,0 @@ -{ - "configurations": [ - { - "name": "Mac", - "includePath": [ - "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1", - "/usr/local/include", - "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/9.0.0/include", - "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include", - "/usr/include", - "${workspaceRoot}", - "${workspaceRoot}/lib/libfnd/include", - "${workspaceRoot}/lib/libpolarssl/include", - "${workspaceRoot}/lib/liblz4/include", - "${workspaceRoot}/lib/libes/include", - "${workspaceRoot}/lib/libpki/include", - "${workspaceRoot}/lib/libhac/include", - "${workspaceRoot}/lib/libhac-hb/include" - ], - "defines": [], - "intelliSenseMode": "clang-x64", - "browse": { - "path": [ - "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1", - "/usr/local/include", - "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/9.0.0/include", - "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include", - "/usr/include", - "${workspaceRoot}" - ], - "limitSymbolsToIncludedHeaders": true, - "databaseFilename": "" - }, - "macFrameworkPath": [ - "/System/Library/Frameworks", - "/Library/Frameworks" - ], - "compilerPath": "/usr/bin/clang", - "cStandard": "c11", - "cppStandard": "c++17" - }, - { - "name": "Linux", - "includePath": [ - "/usr/include", - "/usr/local/include", - "${workspaceRoot}" - ], - "defines": [], - "intelliSenseMode": "clang-x64", - "browse": { - "path": [ - "/usr/include", - "/usr/local/include", - "${workspaceRoot}" - ], - "limitSymbolsToIncludedHeaders": true, - "databaseFilename": "" - }, - "compilerPath": "/usr/bin/clang", - "cStandard": "c11", - "cppStandard": "c++17" - }, - { - "name": "Win32", - "includePath": [ - "C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/include", - "${workspaceRoot}", - "${workspaceRoot}/lib/libfnd/include", - "${workspaceRoot}/lib/libpolarssl/include", - "${workspaceRoot}/lib/liblz4/include", - "${workspaceRoot}/lib/libes/include", - "${workspaceRoot}/lib/libpki/include", - "${workspaceRoot}/lib/libhac/include", - "${workspaceRoot}/lib/libhac-hb/include" - ], - "defines": [ - "_DEBUG", - "UNICODE", - "_UNICODE" - ], - "intelliSenseMode": "msvc-x64", - "browse": { - "path": [ - "C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/include/*", - "${workspaceRoot}" - ], - "limitSymbolsToIncludedHeaders": true, - "databaseFilename": "" - }, - "compilerPath": "/usr/bin/clang", - "cStandard": "c11", - "cppStandard": "c++17" - } - ], - "version": 4 -} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index 768b573..0000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "files.associations": { - "__config": "cpp", - "__nullptr": "cpp", - "cstddef": "cpp", - "exception": "cpp", - "initializer_list": "cpp", - "new": "cpp", - "stdexcept": "cpp", - "type_traits": "cpp", - "typeinfo": "cpp", - "__split_buffer": "cpp", - "__tree": "cpp", - "bitset": "cpp", - "iterator": "cpp", - "map": "cpp", - "string": "cpp", - "string_view": "cpp", - "utility": "cpp", - "vector": "cpp", - "istream": "cpp", - "atomic": "cpp", - "ios": "cpp", - "system_error": "cpp", - "__functional_base": "cpp", - "locale": "cpp", - "memory": "cpp", - "tuple": "cpp", - "__locale": "cpp", - "cinttypes": "cpp", - "__bit_reference": "cpp", - "algorithm": "cpp", - "__functional_base_03": "cpp", - "__tuple": "cpp", - "chrono": "cpp", - "functional": "cpp", - "limits": "cpp", - "ratio": "cpp" - } -} \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json deleted file mode 100644 index 0325034..0000000 --- a/.vscode/tasks.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - // See https://go.microsoft.com/fwlink/?LinkId=733558 - // for the documentation about the tasks.json format - "version": "2.0.0", - "tasks": [ - { - "label": "build", - "type": "shell", - "command": "make", - "group": { - "kind": "build", - "isDefault": true - } - }, - { - "label": "rebuild", - "type": "shell", - "command": "make rebuild" - } - ] -} \ No newline at end of file diff --git a/BUILDING.md b/BUILDING.md new file mode 100644 index 0000000..2d94e78 --- /dev/null +++ b/BUILDING.md @@ -0,0 +1,19 @@ +# Building +## Linux (incl. Windows Subsystem for Linux) & MacOS - Makefile +### Requirements +* `make` +* Terminal access +* Typical GNU compatible development tools (e.g. `clang`, `g++`, `c++`, `ar` etc) with __C++11__ support + +### Using Makefile +* `make` (default) - Compile program +* `make clean` - Remove executable and object files + +## Native Win32 - Visual Studio +### Requirements +* [Visual Studio Community](https://visualstudio.microsoft.com/vs/community/) 2015 or 2017 + +### Compiling NSTool +* Open `build/visualstudio/nstool.sln` in Visual Studio +* Select Target (e.g `Debug`|`Release` & `x64`) +* Navigate to `Build`->`Build Solution` \ No newline at end of file diff --git a/LICENSE b/LICENSE index 24d91e4..edbe185 100644 --- a/LICENSE +++ b/LICENSE @@ -1,5 +1,6 @@ -NNTools -Copyright (c) 2017-2018 Jack +MIT License + +Copyright (c) 2019 Jack Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -18,46 +19,3 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -PolarSSL -Copyright (C) 2006-2013, Brainspark B.V. -All rights reserved. - -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 2 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, write to the Free Software Foundation, Inc., -51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -LZ4 Library -Copyright (c) 2011-2016, Yann Collet -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/NNTools.sln b/NNTools.sln deleted file mode 100644 index 249f281..0000000 --- a/NNTools.sln +++ /dev/null @@ -1,124 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27428.2015 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Libraries", "Libraries", "{170B4A09-1B67-4A62-93AB-116EBCFF4A8C}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Programs", "Programs", "{E0863FCC-8E72-490D-BE1B-458F12CA8298}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{8F6C846D-35E2-47FD-AF42-7A3FD036346E}" - ProjectSection(SolutionItems) = preProject - .gitignore = .gitignore - LICENSE = LICENSE - makefile = makefile - README.md = README.md - SWITCH_KEYS.md = SWITCH_KEYS.md - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "nstool", "programs\nstool\nstool.vcxproj", "{AF09FA96-4463-417D-8FE6-526063F41349}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libfnd", "lib\libfnd\libfnd.vcxproj", "{4D27EDB9-5110-44FE-8CE2-D46C5AD3C55B}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libpolarssl", "lib\libpolarssl\libpolarssl.vcxproj", "{394EFC16-BD3A-4538-B33D-7BA1EDB8DAC1}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblz4", "lib\liblz4\liblz4.vcxproj", "{AB0C3362-63AB-480A-ADBC-2EF7D859778B}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libpki", "lib\libpki\libpki.vcxproj", "{B9113734-6E84-44FF-8CF7-58199AA815C5}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libes", "lib\libes\libes.vcxproj", "{7BE99936-0D40-410D-944B-4513C2EFF8DC}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libhac", "lib\libhac\libhac.vcxproj", "{91BA9E79-8242-4F7D-B997-0DFEC95EA22B}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libhac-hb", "lib\libhac-hb\libhac-hb.vcxproj", "{738CB4FC-CD9E-4B81-A04B-DEADBFA71C63}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {AF09FA96-4463-417D-8FE6-526063F41349}.Debug|x64.ActiveCfg = Debug|x64 - {AF09FA96-4463-417D-8FE6-526063F41349}.Debug|x64.Build.0 = Debug|x64 - {AF09FA96-4463-417D-8FE6-526063F41349}.Debug|x86.ActiveCfg = Debug|Win32 - {AF09FA96-4463-417D-8FE6-526063F41349}.Debug|x86.Build.0 = Debug|Win32 - {AF09FA96-4463-417D-8FE6-526063F41349}.Release|x64.ActiveCfg = Release|x64 - {AF09FA96-4463-417D-8FE6-526063F41349}.Release|x64.Build.0 = Release|x64 - {AF09FA96-4463-417D-8FE6-526063F41349}.Release|x86.ActiveCfg = Release|Win32 - {AF09FA96-4463-417D-8FE6-526063F41349}.Release|x86.Build.0 = Release|Win32 - {4D27EDB9-5110-44FE-8CE2-D46C5AD3C55B}.Debug|x64.ActiveCfg = Debug|x64 - {4D27EDB9-5110-44FE-8CE2-D46C5AD3C55B}.Debug|x64.Build.0 = Debug|x64 - {4D27EDB9-5110-44FE-8CE2-D46C5AD3C55B}.Debug|x86.ActiveCfg = Debug|Win32 - {4D27EDB9-5110-44FE-8CE2-D46C5AD3C55B}.Debug|x86.Build.0 = Debug|Win32 - {4D27EDB9-5110-44FE-8CE2-D46C5AD3C55B}.Release|x64.ActiveCfg = Release|x64 - {4D27EDB9-5110-44FE-8CE2-D46C5AD3C55B}.Release|x64.Build.0 = Release|x64 - {4D27EDB9-5110-44FE-8CE2-D46C5AD3C55B}.Release|x86.ActiveCfg = Release|Win32 - {4D27EDB9-5110-44FE-8CE2-D46C5AD3C55B}.Release|x86.Build.0 = Release|Win32 - {394EFC16-BD3A-4538-B33D-7BA1EDB8DAC1}.Debug|x64.ActiveCfg = Debug|x64 - {394EFC16-BD3A-4538-B33D-7BA1EDB8DAC1}.Debug|x64.Build.0 = Debug|x64 - {394EFC16-BD3A-4538-B33D-7BA1EDB8DAC1}.Debug|x86.ActiveCfg = Debug|Win32 - {394EFC16-BD3A-4538-B33D-7BA1EDB8DAC1}.Debug|x86.Build.0 = Debug|Win32 - {394EFC16-BD3A-4538-B33D-7BA1EDB8DAC1}.Release|x64.ActiveCfg = Release|x64 - {394EFC16-BD3A-4538-B33D-7BA1EDB8DAC1}.Release|x64.Build.0 = Release|x64 - {394EFC16-BD3A-4538-B33D-7BA1EDB8DAC1}.Release|x86.ActiveCfg = Release|Win32 - {394EFC16-BD3A-4538-B33D-7BA1EDB8DAC1}.Release|x86.Build.0 = Release|Win32 - {AB0C3362-63AB-480A-ADBC-2EF7D859778B}.Debug|x64.ActiveCfg = Debug|x64 - {AB0C3362-63AB-480A-ADBC-2EF7D859778B}.Debug|x64.Build.0 = Debug|x64 - {AB0C3362-63AB-480A-ADBC-2EF7D859778B}.Debug|x86.ActiveCfg = Debug|Win32 - {AB0C3362-63AB-480A-ADBC-2EF7D859778B}.Debug|x86.Build.0 = Debug|Win32 - {AB0C3362-63AB-480A-ADBC-2EF7D859778B}.Release|x64.ActiveCfg = Release|x64 - {AB0C3362-63AB-480A-ADBC-2EF7D859778B}.Release|x64.Build.0 = Release|x64 - {AB0C3362-63AB-480A-ADBC-2EF7D859778B}.Release|x86.ActiveCfg = Release|Win32 - {AB0C3362-63AB-480A-ADBC-2EF7D859778B}.Release|x86.Build.0 = Release|Win32 - {B9113734-6E84-44FF-8CF7-58199AA815C5}.Debug|x64.ActiveCfg = Debug|x64 - {B9113734-6E84-44FF-8CF7-58199AA815C5}.Debug|x64.Build.0 = Debug|x64 - {B9113734-6E84-44FF-8CF7-58199AA815C5}.Debug|x86.ActiveCfg = Debug|Win32 - {B9113734-6E84-44FF-8CF7-58199AA815C5}.Debug|x86.Build.0 = Debug|Win32 - {B9113734-6E84-44FF-8CF7-58199AA815C5}.Release|x64.ActiveCfg = Release|x64 - {B9113734-6E84-44FF-8CF7-58199AA815C5}.Release|x64.Build.0 = Release|x64 - {B9113734-6E84-44FF-8CF7-58199AA815C5}.Release|x86.ActiveCfg = Release|Win32 - {B9113734-6E84-44FF-8CF7-58199AA815C5}.Release|x86.Build.0 = Release|Win32 - {7BE99936-0D40-410D-944B-4513C2EFF8DC}.Debug|x64.ActiveCfg = Debug|x64 - {7BE99936-0D40-410D-944B-4513C2EFF8DC}.Debug|x64.Build.0 = Debug|x64 - {7BE99936-0D40-410D-944B-4513C2EFF8DC}.Debug|x86.ActiveCfg = Debug|Win32 - {7BE99936-0D40-410D-944B-4513C2EFF8DC}.Debug|x86.Build.0 = Debug|Win32 - {7BE99936-0D40-410D-944B-4513C2EFF8DC}.Release|x64.ActiveCfg = Release|x64 - {7BE99936-0D40-410D-944B-4513C2EFF8DC}.Release|x64.Build.0 = Release|x64 - {7BE99936-0D40-410D-944B-4513C2EFF8DC}.Release|x86.ActiveCfg = Release|Win32 - {7BE99936-0D40-410D-944B-4513C2EFF8DC}.Release|x86.Build.0 = Release|Win32 - {91BA9E79-8242-4F7D-B997-0DFEC95EA22B}.Debug|x64.ActiveCfg = Debug|x64 - {91BA9E79-8242-4F7D-B997-0DFEC95EA22B}.Debug|x64.Build.0 = Debug|x64 - {91BA9E79-8242-4F7D-B997-0DFEC95EA22B}.Debug|x86.ActiveCfg = Debug|Win32 - {91BA9E79-8242-4F7D-B997-0DFEC95EA22B}.Debug|x86.Build.0 = Debug|Win32 - {91BA9E79-8242-4F7D-B997-0DFEC95EA22B}.Release|x64.ActiveCfg = Release|x64 - {91BA9E79-8242-4F7D-B997-0DFEC95EA22B}.Release|x64.Build.0 = Release|x64 - {91BA9E79-8242-4F7D-B997-0DFEC95EA22B}.Release|x86.ActiveCfg = Release|Win32 - {91BA9E79-8242-4F7D-B997-0DFEC95EA22B}.Release|x86.Build.0 = Release|Win32 - {738CB4FC-CD9E-4B81-A04B-DEADBFA71C63}.Debug|x64.ActiveCfg = Debug|x64 - {738CB4FC-CD9E-4B81-A04B-DEADBFA71C63}.Debug|x64.Build.0 = Debug|x64 - {738CB4FC-CD9E-4B81-A04B-DEADBFA71C63}.Debug|x86.ActiveCfg = Debug|Win32 - {738CB4FC-CD9E-4B81-A04B-DEADBFA71C63}.Debug|x86.Build.0 = Debug|Win32 - {738CB4FC-CD9E-4B81-A04B-DEADBFA71C63}.Release|x64.ActiveCfg = Release|x64 - {738CB4FC-CD9E-4B81-A04B-DEADBFA71C63}.Release|x64.Build.0 = Release|x64 - {738CB4FC-CD9E-4B81-A04B-DEADBFA71C63}.Release|x86.ActiveCfg = Release|Win32 - {738CB4FC-CD9E-4B81-A04B-DEADBFA71C63}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {AF09FA96-4463-417D-8FE6-526063F41349} = {E0863FCC-8E72-490D-BE1B-458F12CA8298} - {4D27EDB9-5110-44FE-8CE2-D46C5AD3C55B} = {170B4A09-1B67-4A62-93AB-116EBCFF4A8C} - {394EFC16-BD3A-4538-B33D-7BA1EDB8DAC1} = {170B4A09-1B67-4A62-93AB-116EBCFF4A8C} - {AB0C3362-63AB-480A-ADBC-2EF7D859778B} = {170B4A09-1B67-4A62-93AB-116EBCFF4A8C} - {B9113734-6E84-44FF-8CF7-58199AA815C5} = {170B4A09-1B67-4A62-93AB-116EBCFF4A8C} - {7BE99936-0D40-410D-944B-4513C2EFF8DC} = {170B4A09-1B67-4A62-93AB-116EBCFF4A8C} - {91BA9E79-8242-4F7D-B997-0DFEC95EA22B} = {170B4A09-1B67-4A62-93AB-116EBCFF4A8C} - {738CB4FC-CD9E-4B81-A04B-DEADBFA71C63} = {170B4A09-1B67-4A62-93AB-116EBCFF4A8C} - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {07DCCACC-D10D-47C9-85AE-FB9C54DB7D62} - EndGlobalSection -EndGlobal diff --git a/NNTools.vcxproj b/NNTools.vcxproj deleted file mode 100644 index d764e1b..0000000 --- a/NNTools.vcxproj +++ /dev/null @@ -1,119 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 15.0 - {0A4197A1-76AD-4BF7-A29D-5CED369B72FD} - NNTools - 10.0.15063.0 - NNTools - - - - Application - true - v141 - MultiByte - - - Application - false - v141 - true - MultiByte - - - Application - true - v141 - MultiByte - - - Application - false - v141 - true - MultiByte - - - - - - - - - - - - - - - - - - - - - - - Level3 - Disabled - true - - - - - Level3 - Disabled - true - - - - - Level3 - MaxSpeed - true - true - true - - - true - true - - - - - Level3 - MaxSpeed - true - true - true - - - true - true - - - - - - - - \ No newline at end of file diff --git a/NNTools.vcxproj.filters b/NNTools.vcxproj.filters deleted file mode 100644 index 6a1782f..0000000 --- a/NNTools.vcxproj.filters +++ /dev/null @@ -1,17 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - \ No newline at end of file diff --git a/README.md b/README.md index 48824a1..26112c8 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,83 @@ -# NNTools +# Nintendo Switch Tool (NSTool) ![DeviceTag](https://img.shields.io/badge/Device-SWITCH-e60012.svg) +General purpose reading/extraction tool for Nintendo Switch file formats. -Tools & Libraries for Nintendo devices. +## Supported File Formats +* Meta (.npdm) +* PartitionFS (and HashedPartitionFS) (includes raw .nsp) +* RomFS +* GameCard Image (.xci) +* Nintendo Content Archive (.nca) +* Content Metadata (.cnmt) +* Nintendo Software Object (.nso) +* Nintendo Relocatable Software Object (.nro) +* Kernel Initial Process List (.ini) +* Kernel Initial Process (.kip) +* Nintendo Application Control Property (.nacp) +* ES Ticket (v2 only) (.tik) +* PKI Certificate (.cert) -[![License](https://img.shields.io/badge/license-MIT-blue.svg)](/LICENSE) +# Usage +``` +Usage: nstool [options... ] -# Tools -* [__nstool__](/programs/nstool/README.md) - General purpose read/extract tool for Nintendo Switch file formats. + General Options: + -d, --dev Use devkit keyset. + -k, --keyset Specify keyset file. + -t, --type Specify input file type. [xci, pfs, romfs, nca, meta, cnmt, nso, nro, ini, kip, nacp, aset, cert, tik] + -y, --verify Verify file. -# Libraries -* __libfnd__ - Foundation library. Provides file IO, crypto, CLI utils, string conversion, etc. -* __libpki__ - Processes Nintendo's proprietary PKI. -* __libes__ - Processes Nintendo's eShop file formats. -* __libhac__ - Processes Nintendo Switch file formats. -* __libhac-hb__ - Processes Nintendo Switch file formats (homebrew extensions). + Output Options: + --showkeys Show keys generated. + --showlayout Show layout metadata. + -v, --verbose Verbose output. -# Dependencies -* __libpolarssl__ - Cryptographic functions (AES,SHA,RSA). Clone of [polarssl](https://github.com/ARMmbed/mbedtls) (now mbedTLS). -* __liblz4__ - Compression algorithms (LZ4). Clone of [lz4](https://github.com/lz4/lz4). + XCI (GameCard Image) + nstool [--listfs] [--update --logo --normal --secure ] <.xci file> + --listfs Print file system in embedded partitions. + --update Extract "update" partition to directory. + --logo Extract "logo" partition to directory. + --normal Extract "normal" partition to directory. + --secure Extract "secure" partition to directory. -(Copies of these are included locally and are statically linked libraries) + PFS0/HFS0 (PartitionFs), RomFs, NSP (Ninendo Submission Package) + nstool [--listfs] [--fsdir ] + --listfs Print file system. + --fsdir Extract file system to directory. + + NCA (Nintendo Content Archive) + nstool [--listfs] [--bodykey --titlekey ] [--part0 ...] <.nca file> + --listfs Print file system in embedded partitions. + --titlekey Specify title key extracted from ticket. + --bodykey Specify body encryption key. + --tik Specify ticket to source title key. + --cert Specify certificate chain to verify ticket. + --part0 Extract "partition 0" to directory. + --part1 Extract "partition 1" to directory. + --part2 Extract "partition 2" to directory. + --part3 Extract "partition 3" to directory. + + NSO (Nintendo Software Object), NRO (Nintendo Relocatable Object) + nstool [--listapi --listsym] [--insttype ] + --listapi Print SDK API List. + --listsym Print Code Symbols. + --insttype Specify instruction type [64bit|32bit] (64bit is assumed). + + INI (Initial Process List Blob) + nstool [--kipdir ] + --kipdir Extract embedded KIPs to directory. + + ASET (Homebrew Asset Blob) + nstool [--listfs] [--icon --nacp --fsdir ] + --listfs Print filesystem in embedded RomFS partition. + --icon Extract icon partition to file. + --nacp Extract NACP partition to file. + --fsdir Extract RomFS partition to directory. +``` + +# External Keys +NSTool doesn't embed any keys that are copyright protected. However keys can be imported via various keyset files. + +See [SWITCH_KEYS.md](/SWITCH_KEYS.md) for more info. # Building -On MacOS/Linux/WSL run `make`. - -For Windows, Visual Studio 2017 is supported. \ No newline at end of file +See [BUILDING.md](/BUILDING.md). \ No newline at end of file diff --git a/build/visualstudio/nstool.sln b/build/visualstudio/nstool.sln new file mode 100644 index 0000000..8958846 --- /dev/null +++ b/build/visualstudio/nstool.sln @@ -0,0 +1,129 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.28010.2036 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "nstool", "nstool\nstool.vcxproj", "{775EF5EB-CA49-4994-8AC4-47B4A5385266}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "deps", "deps", "{05929EAE-4471-4E8E-A6F3-793A81623D7F}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libfnd", "..\..\deps\libfnd\build\visualstudio\libfnd\libfnd.vcxproj", "{4E578016-34BA-4A1E-B8EC-37A48780B6CA}" + ProjectSection(ProjectDependencies) = postProject + {E741ADED-7900-4E07-8DB0-D008C336C3FB} = {E741ADED-7900-4E07-8DB0-D008C336C3FB} + {7A7C66F3-2B5B-4E23-85D8-2A74FEDAD92C} = {7A7C66F3-2B5B-4E23-85D8-2A74FEDAD92C} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblz4", "..\..\deps\liblz4\build\visualstudio\liblz4\liblz4.vcxproj", "{E741ADED-7900-4E07-8DB0-D008C336C3FB}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libnintendo-es", "..\..\deps\libnintendo-es\build\visualstudio\libnintendo-es\libnintendo-es.vcxproj", "{8616D6C9-C8DE-4C3F-AFC2-625636664C2B}" + ProjectSection(ProjectDependencies) = postProject + {4E578016-34BA-4A1E-B8EC-37A48780B6CA} = {4E578016-34BA-4A1E-B8EC-37A48780B6CA} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libnintendo-hac", "..\..\deps\libnintendo-hac\build\visualstudio\libnintendo-hac\libnintendo-hac.vcxproj", "{8885C125-83FB-4F73-A93A-C712B1434D54}" + ProjectSection(ProjectDependencies) = postProject + {4E578016-34BA-4A1E-B8EC-37A48780B6CA} = {4E578016-34BA-4A1E-B8EC-37A48780B6CA} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libnintendo-hac-hb", "..\..\deps\libnintendo-hac-hb\build\visualstudio\libnintendo-hac-hb\libnintendo-hac-hb.vcxproj", "{24D001B4-D439-4967-9371-DC3E0523EB19}" + ProjectSection(ProjectDependencies) = postProject + {4E578016-34BA-4A1E-B8EC-37A48780B6CA} = {4E578016-34BA-4A1E-B8EC-37A48780B6CA} + {8885C125-83FB-4F73-A93A-C712B1434D54} = {8885C125-83FB-4F73-A93A-C712B1434D54} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libnintendo-pki", "..\..\deps\libnintendo-pki\build\visualstudio\libnintendo-pki\libnintendo-pki.vcxproj", "{0BEF63A0-2801-4563-AB65-1E2FD881C3AF}" + ProjectSection(ProjectDependencies) = postProject + {4E578016-34BA-4A1E-B8EC-37A48780B6CA} = {4E578016-34BA-4A1E-B8EC-37A48780B6CA} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libpolarssl", "..\..\deps\libpolarssl\build\visualstudio\libpolarssl\libpolarssl.vcxproj", "{7A7C66F3-2B5B-4E23-85D8-2A74FEDAD92C}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {775EF5EB-CA49-4994-8AC4-47B4A5385266}.Debug|x64.ActiveCfg = Debug|x64 + {775EF5EB-CA49-4994-8AC4-47B4A5385266}.Debug|x64.Build.0 = Debug|x64 + {775EF5EB-CA49-4994-8AC4-47B4A5385266}.Debug|x86.ActiveCfg = Debug|Win32 + {775EF5EB-CA49-4994-8AC4-47B4A5385266}.Debug|x86.Build.0 = Debug|Win32 + {775EF5EB-CA49-4994-8AC4-47B4A5385266}.Release|x64.ActiveCfg = Release|x64 + {775EF5EB-CA49-4994-8AC4-47B4A5385266}.Release|x64.Build.0 = Release|x64 + {775EF5EB-CA49-4994-8AC4-47B4A5385266}.Release|x86.ActiveCfg = Release|Win32 + {775EF5EB-CA49-4994-8AC4-47B4A5385266}.Release|x86.Build.0 = Release|Win32 + {4E578016-34BA-4A1E-B8EC-37A48780B6CA}.Debug|x64.ActiveCfg = Debug|x64 + {4E578016-34BA-4A1E-B8EC-37A48780B6CA}.Debug|x64.Build.0 = Debug|x64 + {4E578016-34BA-4A1E-B8EC-37A48780B6CA}.Debug|x86.ActiveCfg = Debug|Win32 + {4E578016-34BA-4A1E-B8EC-37A48780B6CA}.Debug|x86.Build.0 = Debug|Win32 + {4E578016-34BA-4A1E-B8EC-37A48780B6CA}.Release|x64.ActiveCfg = Release|x64 + {4E578016-34BA-4A1E-B8EC-37A48780B6CA}.Release|x64.Build.0 = Release|x64 + {4E578016-34BA-4A1E-B8EC-37A48780B6CA}.Release|x86.ActiveCfg = Release|Win32 + {4E578016-34BA-4A1E-B8EC-37A48780B6CA}.Release|x86.Build.0 = Release|Win32 + {E741ADED-7900-4E07-8DB0-D008C336C3FB}.Debug|x64.ActiveCfg = Debug|x64 + {E741ADED-7900-4E07-8DB0-D008C336C3FB}.Debug|x64.Build.0 = Debug|x64 + {E741ADED-7900-4E07-8DB0-D008C336C3FB}.Debug|x86.ActiveCfg = Debug|Win32 + {E741ADED-7900-4E07-8DB0-D008C336C3FB}.Debug|x86.Build.0 = Debug|Win32 + {E741ADED-7900-4E07-8DB0-D008C336C3FB}.Release|x64.ActiveCfg = Release|x64 + {E741ADED-7900-4E07-8DB0-D008C336C3FB}.Release|x64.Build.0 = Release|x64 + {E741ADED-7900-4E07-8DB0-D008C336C3FB}.Release|x86.ActiveCfg = Release|Win32 + {E741ADED-7900-4E07-8DB0-D008C336C3FB}.Release|x86.Build.0 = Release|Win32 + {8616D6C9-C8DE-4C3F-AFC2-625636664C2B}.Debug|x64.ActiveCfg = Debug|x64 + {8616D6C9-C8DE-4C3F-AFC2-625636664C2B}.Debug|x64.Build.0 = Debug|x64 + {8616D6C9-C8DE-4C3F-AFC2-625636664C2B}.Debug|x86.ActiveCfg = Debug|Win32 + {8616D6C9-C8DE-4C3F-AFC2-625636664C2B}.Debug|x86.Build.0 = Debug|Win32 + {8616D6C9-C8DE-4C3F-AFC2-625636664C2B}.Release|x64.ActiveCfg = Release|x64 + {8616D6C9-C8DE-4C3F-AFC2-625636664C2B}.Release|x64.Build.0 = Release|x64 + {8616D6C9-C8DE-4C3F-AFC2-625636664C2B}.Release|x86.ActiveCfg = Release|Win32 + {8616D6C9-C8DE-4C3F-AFC2-625636664C2B}.Release|x86.Build.0 = Release|Win32 + {8885C125-83FB-4F73-A93A-C712B1434D54}.Debug|x64.ActiveCfg = Debug|x64 + {8885C125-83FB-4F73-A93A-C712B1434D54}.Debug|x64.Build.0 = Debug|x64 + {8885C125-83FB-4F73-A93A-C712B1434D54}.Debug|x86.ActiveCfg = Debug|Win32 + {8885C125-83FB-4F73-A93A-C712B1434D54}.Debug|x86.Build.0 = Debug|Win32 + {8885C125-83FB-4F73-A93A-C712B1434D54}.Release|x64.ActiveCfg = Release|x64 + {8885C125-83FB-4F73-A93A-C712B1434D54}.Release|x64.Build.0 = Release|x64 + {8885C125-83FB-4F73-A93A-C712B1434D54}.Release|x86.ActiveCfg = Release|Win32 + {8885C125-83FB-4F73-A93A-C712B1434D54}.Release|x86.Build.0 = Release|Win32 + {24D001B4-D439-4967-9371-DC3E0523EB19}.Debug|x64.ActiveCfg = Debug|x64 + {24D001B4-D439-4967-9371-DC3E0523EB19}.Debug|x64.Build.0 = Debug|x64 + {24D001B4-D439-4967-9371-DC3E0523EB19}.Debug|x86.ActiveCfg = Debug|Win32 + {24D001B4-D439-4967-9371-DC3E0523EB19}.Debug|x86.Build.0 = Debug|Win32 + {24D001B4-D439-4967-9371-DC3E0523EB19}.Release|x64.ActiveCfg = Release|x64 + {24D001B4-D439-4967-9371-DC3E0523EB19}.Release|x64.Build.0 = Release|x64 + {24D001B4-D439-4967-9371-DC3E0523EB19}.Release|x86.ActiveCfg = Release|Win32 + {24D001B4-D439-4967-9371-DC3E0523EB19}.Release|x86.Build.0 = Release|Win32 + {0BEF63A0-2801-4563-AB65-1E2FD881C3AF}.Debug|x64.ActiveCfg = Debug|x64 + {0BEF63A0-2801-4563-AB65-1E2FD881C3AF}.Debug|x64.Build.0 = Debug|x64 + {0BEF63A0-2801-4563-AB65-1E2FD881C3AF}.Debug|x86.ActiveCfg = Debug|Win32 + {0BEF63A0-2801-4563-AB65-1E2FD881C3AF}.Debug|x86.Build.0 = Debug|Win32 + {0BEF63A0-2801-4563-AB65-1E2FD881C3AF}.Release|x64.ActiveCfg = Release|x64 + {0BEF63A0-2801-4563-AB65-1E2FD881C3AF}.Release|x64.Build.0 = Release|x64 + {0BEF63A0-2801-4563-AB65-1E2FD881C3AF}.Release|x86.ActiveCfg = Release|Win32 + {0BEF63A0-2801-4563-AB65-1E2FD881C3AF}.Release|x86.Build.0 = Release|Win32 + {7A7C66F3-2B5B-4E23-85D8-2A74FEDAD92C}.Debug|x64.ActiveCfg = Debug|x64 + {7A7C66F3-2B5B-4E23-85D8-2A74FEDAD92C}.Debug|x64.Build.0 = Debug|x64 + {7A7C66F3-2B5B-4E23-85D8-2A74FEDAD92C}.Debug|x86.ActiveCfg = Debug|Win32 + {7A7C66F3-2B5B-4E23-85D8-2A74FEDAD92C}.Debug|x86.Build.0 = Debug|Win32 + {7A7C66F3-2B5B-4E23-85D8-2A74FEDAD92C}.Release|x64.ActiveCfg = Release|x64 + {7A7C66F3-2B5B-4E23-85D8-2A74FEDAD92C}.Release|x64.Build.0 = Release|x64 + {7A7C66F3-2B5B-4E23-85D8-2A74FEDAD92C}.Release|x86.ActiveCfg = Release|Win32 + {7A7C66F3-2B5B-4E23-85D8-2A74FEDAD92C}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {4E578016-34BA-4A1E-B8EC-37A48780B6CA} = {05929EAE-4471-4E8E-A6F3-793A81623D7F} + {E741ADED-7900-4E07-8DB0-D008C336C3FB} = {05929EAE-4471-4E8E-A6F3-793A81623D7F} + {8616D6C9-C8DE-4C3F-AFC2-625636664C2B} = {05929EAE-4471-4E8E-A6F3-793A81623D7F} + {8885C125-83FB-4F73-A93A-C712B1434D54} = {05929EAE-4471-4E8E-A6F3-793A81623D7F} + {24D001B4-D439-4967-9371-DC3E0523EB19} = {05929EAE-4471-4E8E-A6F3-793A81623D7F} + {0BEF63A0-2801-4563-AB65-1E2FD881C3AF} = {05929EAE-4471-4E8E-A6F3-793A81623D7F} + {7A7C66F3-2B5B-4E23-85D8-2A74FEDAD92C} = {05929EAE-4471-4E8E-A6F3-793A81623D7F} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {ABDCFB40-D6B3-44A9-92B5-0D7AB38D9FB8} + EndGlobalSection +EndGlobal diff --git a/build/visualstudio/nstool/nstool.vcxproj b/build/visualstudio/nstool/nstool.vcxproj new file mode 100644 index 0000000..8d79358 --- /dev/null +++ b/build/visualstudio/nstool/nstool.vcxproj @@ -0,0 +1,194 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 15.0 + {775EF5EB-CA49-4994-8AC4-47B4A5385266} + nstool + 10.0.17134.0 + + + + Application + true + v141 + MultiByte + + + Application + false + v141 + true + MultiByte + + + Application + true + v141 + MultiByte + + + Application + false + v141 + true + MultiByte + + + + + + + + + + + + + + + + + + + + + + + Level3 + Disabled + true + true + $(ProjectDir)..\..\..\include;$(SolutionDir)..\..\deps\libfnd\include;$(SolutionDir)..\..\deps\libnintendo-es\include;$(SolutionDir)..\..\deps\libnintendo-pki\include;$(SolutionDir)..\..\deps\libnintendo-hac\include;$(SolutionDir)..\..\deps\libnintendo-hac-hb\include + + + + + Level3 + Disabled + true + true + $(ProjectDir)..\..\..\include;$(SolutionDir)..\..\deps\libfnd\include;$(SolutionDir)..\..\deps\libnintendo-es\include;$(SolutionDir)..\..\deps\libnintendo-pki\include;$(SolutionDir)..\..\deps\libnintendo-hac\include;$(SolutionDir)..\..\deps\libnintendo-hac-hb\include + + + + + Level3 + MaxSpeed + true + true + true + true + $(ProjectDir)..\..\..\include;$(SolutionDir)..\..\deps\libfnd\include;$(SolutionDir)..\..\deps\libnintendo-es\include;$(SolutionDir)..\..\deps\libnintendo-pki\include;$(SolutionDir)..\..\deps\libnintendo-hac\include;$(SolutionDir)..\..\deps\libnintendo-hac-hb\include + + + true + true + + + + + Level3 + MaxSpeed + true + true + true + true + $(ProjectDir)..\..\..\include;$(SolutionDir)..\..\deps\libfnd\include;$(SolutionDir)..\..\deps\libnintendo-es\include;$(SolutionDir)..\..\deps\libnintendo-pki\include;$(SolutionDir)..\..\deps\libnintendo-hac\include;$(SolutionDir)..\..\deps\libnintendo-hac-hb\include + + + true + true + + + + + {4e578016-34ba-4a1e-b8ec-37a48780b6ca} + + + {e741aded-7900-4e07-8db0-d008c336c3fb} + + + {8616d6c9-c8de-4c3f-afc2-625636664c2b} + + + {24d001b4-d439-4967-9371-dc3e0523eb19} + + + {8885c125-83fb-4f73-a93a-c712b1434d54} + + + {0bef63a0-2801-4563-ab65-1e2fd881c3af} + + + {7a7c66f3-2b5b-4e23-85d8-2a74fedad92c} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/programs/nstool/nstool.vcxproj.filters b/build/visualstudio/nstool/nstool.vcxproj.filters similarity index 57% rename from programs/nstool/nstool.vcxproj.filters rename to build/visualstudio/nstool/nstool.vcxproj.filters index 243a78b..4ae16db 100644 --- a/programs/nstool/nstool.vcxproj.filters +++ b/build/visualstudio/nstool/nstool.vcxproj.filters @@ -1,154 +1,150 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + \ No newline at end of file diff --git a/lib/libes/include/nn/es/SectionHeader_V2.h b/lib/libes/include/nn/es/SectionHeader_V2.h deleted file mode 100644 index f472b6f..0000000 --- a/lib/libes/include/nn/es/SectionHeader_V2.h +++ /dev/null @@ -1,58 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace es -{ - class SectionHeader_V2 : - public fnd::IByteModel - { - public: - SectionHeader_V2(); - SectionHeader_V2(const SectionHeader_V2& other); - - void operator=(const SectionHeader_V2& other); - bool operator==(const SectionHeader_V2& other) const; - bool operator!=(const SectionHeader_V2& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* data, size_t len); - const fnd::Vec& getBytes() const; - - // variables - virtual void clear(); - - uint32_t getSectionOffset() const; - void setSectionOffset(uint32_t offset); - - uint32_t getRecordSize() const; - void setRecordSize(uint32_t size); - - uint32_t getSectionSize() const; - void getSectionSize(uint32_t size); - - uint16_t getRecordNum() const; - void setRecordNum(uint16_t record_num); - - ticket::SectionType getSectionType() const; - void setSectionType(ticket::SectionType type); - - private: - const std::string kModuleName = "SECTION_HEADER_V2"; - - // raw binary - fnd::Vec mRawBinary; - - // variables - uint32_t mSectionOffset; - uint32_t mRecordSize; - uint32_t mSectionSize; - uint16_t mRecordNum; - ticket::SectionType mSectionType; - }; -} -} \ No newline at end of file diff --git a/lib/libes/include/nn/es/TicketBody_V2.h b/lib/libes/include/nn/es/TicketBody_V2.h deleted file mode 100644 index 2a068b4..0000000 --- a/lib/libes/include/nn/es/TicketBody_V2.h +++ /dev/null @@ -1,103 +0,0 @@ -#pragma once -#include -#include -#include -#include - -namespace nn -{ -namespace es -{ - class TicketBody_V2 : - public fnd::IByteModel - { - public: - TicketBody_V2(); - TicketBody_V2(const TicketBody_V2& other); - - void operator=(const TicketBody_V2& other); - bool operator==(const TicketBody_V2& other) const; - bool operator!=(const TicketBody_V2& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* bytes, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - const std::string& getIssuer() const; - void setIssuer(const std::string& issuer); - - const byte_t* getEncTitleKey() const; - void setEncTitleKey(const byte_t* data, size_t len); - - ticket::TitleKeyEncType getTitleKeyEncType() const; - void setTitleKeyEncType(ticket::TitleKeyEncType type); - - uint16_t getTicketVersion() const; - void setTicketVersion(uint16_t version); - - ticket::LicenseType getLicenseType() const; - void setLicenseType(ticket::LicenseType type); - - byte_t getCommonKeyId() const; - void setCommonKeyId(byte_t id); - - const fnd::List& getPropertyFlags() const; - void setPropertyFlags(const fnd::List& flags); - - const byte_t* getReservedRegion() const; - void setReservedRegion(const byte_t* data, size_t len); - - uint64_t getTicketId() const; - void setTicketId(uint64_t id); - - uint64_t getDeviceId() const; - void setDeviceId(uint64_t id); - - const byte_t* getRightsId() const; - void setRightsId(const byte_t* id); - - uint32_t getAccountId() const; - void setAccountId(uint32_t id); - - uint32_t getSectionTotalSize() const; - void setSectionTotalSize(uint32_t size); - - uint32_t getSectionHeaderOffset() const; - void setSectionHeaderOffset(uint32_t offset); - - uint16_t getSectionNum() const; - void setSectionNum(uint16_t num); - - uint16_t getSectionEntrySize() const; - void setSectionEntrySize(uint16_t size); - - private: - const std::string kModuleName = "TICKET_BODY_V2"; - - // raw binary - fnd::Vec mRawBinary; - - // variables - std::string mIssuer; - byte_t mEncTitleKey[ticket::kEncTitleKeySize]; - ticket::TitleKeyEncType mEncType; - uint16_t mTicketVersion; - ticket::LicenseType mLicenseType; - byte_t mCommonKeyId; - fnd::List mPropertyFlags; - byte_t mReservedRegion[ticket::kReservedRegionSize]; // explicitly reserved - uint64_t mTicketId; - uint64_t mDeviceId; - byte_t mRightsId[ticket::kRightsIdSize]; - uint32_t mAccountId; - uint32_t mSectTotalSize; - uint32_t mSectHeaderOffset; - uint16_t mSectNum; - uint16_t mSectEntrySize; - }; -} -} \ No newline at end of file diff --git a/lib/libes/include/nn/es/ticket.h b/lib/libes/include/nn/es/ticket.h deleted file mode 100644 index d2e953d..0000000 --- a/lib/libes/include/nn/es/ticket.h +++ /dev/null @@ -1,111 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace es -{ - namespace ticket - { - enum TitleKeyEncType - { - AES128_CBC, - RSA2048 - }; - - enum LicenseType - { - LICENSE_PERMANENT = 0, - LICENSE_DEMO = 1, - LICENSE_TRIAL = 2, - LICENSE_RENTAL = 3, - LICENSE_SUBSCRIPTION = 4, - LICENSE_SERVICE = 5, - }; - - enum PropertyMaskFlags - { - FLAG_PRE_INSTALL, - FLAG_SHARED_TITLE, - FLAG_ALLOW_ALL_CONTENT - }; - - enum SectionType - { - SECTION_PERMANENT = 1, - SECTION_SUBSCRIPTION = 2, - SECTION_CONTENT = 3, - SECTION_CONTENT_CONSUMPTION = 4, - SECTION_ACCESS_TITLE = 5, - SECTION_LIMITED_RESOURCE = 6, - }; - - static const size_t kIssuerSize = 0x40; - static const byte_t kFormatVersion = 2; - static const size_t kEncTitleKeySize = fnd::rsa::kRsa2048Size; - static const size_t kReservedRegionSize = 8; - static const size_t kRightsIdSize = 16; - } -#pragma pack(push,1) - struct sTicketBody_v2 - { - char issuer[ticket::kIssuerSize]; - byte_t enc_title_key[ticket::kEncTitleKeySize]; - byte_t format_version; - byte_t title_key_enc_type; - le_uint16_t ticket_version; - byte_t license_type; - byte_t common_key_id; - byte_t property_mask; - byte_t reserved_0; - byte_t reserved_region[ticket::kReservedRegionSize]; // explicitly reserved - le_uint64_t ticket_id; - le_uint64_t device_id; - byte_t rights_id[ticket::kRightsIdSize]; - le_uint32_t account_id; - le_uint32_t sect_total_size; - le_uint32_t sect_header_offset; - le_uint16_t sect_num; - le_uint16_t sect_entry_size; - }; - - struct sSectionHeader_v2 - { - le_uint32_t section_offset; - le_uint32_t record_size; - le_uint32_t section_size; - le_uint16_t record_num; - le_uint16_t section_type; - }; - - struct sContentRecord_v1 - { - private: - static const size_t kAccessMaskSize = 0x80; - static const uint16_t kGroupMask = 0xFC00; - static const uint16_t kAccessMaskMask = 0x3FF; - - be_uint32_t group; - byte_t access_mask[kAccessMaskSize]; - public: - uint32_t index_group() const { return group.get(); } - bool is_index_enabled(uint16_t index) const - { - return (index_group() == get_group(index)) \ - && ((access_mask[get_access_mask(index) / 8] & BIT(get_access_mask(index) % 8)) != 0); - } - - void clear() { memset(this, 0, sizeof(sContentRecord_v1)); } - - void set_index_group(uint16_t index) { group = get_group(index); } - void enable_index(uint16_t index) { access_mask[get_access_mask(index) / 8] |= BIT(get_access_mask(index) % 8); } - void disable_index(uint16_t index) { access_mask[get_access_mask(index) / 8] &= ~BIT(get_access_mask(index) % 8); } - - inline uint16_t get_access_mask(uint16_t index) const { return index & kAccessMaskMask; } - inline uint16_t get_group(uint16_t index) const { return index & kGroupMask; } - }; -#pragma pack(pop) -} -} \ No newline at end of file diff --git a/lib/libes/libes.vcxproj b/lib/libes/libes.vcxproj deleted file mode 100644 index b1fe783..0000000 --- a/lib/libes/libes.vcxproj +++ /dev/null @@ -1,134 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - {7BE99936-0D40-410D-944B-4513C2EFF8DC} - 10.0.16299.0 - - - - StaticLibrary - true - v141 - MultiByte - - - StaticLibrary - false - v141 - true - MultiByte - - - StaticLibrary - true - v141 - MultiByte - - - StaticLibrary - false - v141 - true - MultiByte - - - - - - - - - - - - - - - - - - - - - - - Level3 - Disabled - true - ..\libfnd\include;..\libes\include; - _MBCS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - - - Level3 - Disabled - true - ..\libfnd\include;..\libes\include; - _MBCS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - - - Level3 - MaxSpeed - true - true - true - ..\libfnd\include;..\libes\include; - _MBCS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - true - true - - - - - Level3 - MaxSpeed - true - true - true - ..\libfnd\include;..\libes\include; - _MBCS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - true - true - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/lib/libes/libes.vcxproj.filters b/lib/libes/libes.vcxproj.filters deleted file mode 100644 index d55625c..0000000 --- a/lib/libes/libes.vcxproj.filters +++ /dev/null @@ -1,39 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - - - - Header Files - - - Header Files - - - Header Files - - - - - Source Files - - - Source Files - - - \ No newline at end of file diff --git a/lib/libes/libes.vcxproj.user b/lib/libes/libes.vcxproj.user deleted file mode 100644 index be25078..0000000 --- a/lib/libes/libes.vcxproj.user +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/lib/libes/makefile b/lib/libes/makefile deleted file mode 100644 index d8a204a..0000000 --- a/lib/libes/makefile +++ /dev/null @@ -1,46 +0,0 @@ -# Sources -SRC_DIR = source -OBJS = $(foreach dir,$(SRC_DIR),$(subst .cpp,.o,$(wildcard $(dir)/*.cpp))) $(foreach dir,$(SRC_DIR),$(subst .c,.o,$(wildcard $(dir)/*.c))) - -# External dependencies -DEPENDS = fnd crypto -LIB_DIR = .. -INCS = -I"include" $(foreach dep,$(DEPENDS), -I"$(LIB_DIR)/lib$(dep)/include") - -# Compiler Settings -CXXFLAGS = -std=c++11 $(INCS) -D__STDC_FORMAT_MACROS -Wall -Wno-unused-value -CFLAGS = -std=c11 $(INCS) -Wall -Wno-unused-value -ARFLAGS = cr -o -ifeq ($(OS),Windows_NT) - # Windows Only Flags/Libs - CC = x86_64-w64-mingw32-gcc - CXX = x86_64-w64-mingw32-g++ - CFLAGS += -Wno-unused-but-set-variable - CXXFLAGS += -Wno-unused-but-set-variable -else - UNAME = $(shell uname -s) - ifeq ($(UNAME), Darwin) - # MacOS Only Flags/Libs - CFLAGS += -Wno-unused-private-field - CXXFLAGS += -Wno-unused-private-field - ARFLAGS = rc - else - # *nix Only Flags/Libs - CFLAGS += -Wno-unused-but-set-variable - CXXFLAGS += -Wno-unused-but-set-variable - endif - -endif - -# Output -OUTPUT = $(shell basename "$(CURDIR)").a - -main: build - -rebuild: clean build - -build: $(OBJS) - ar $(ARFLAGS) $(OUTPUT) $(OBJS) - -clean: - rm -rf $(OUTPUT) $(OBJS) \ No newline at end of file diff --git a/lib/libes/source/SectionHeader_V2.cpp b/lib/libes/source/SectionHeader_V2.cpp deleted file mode 100644 index ae5ad04..0000000 --- a/lib/libes/source/SectionHeader_V2.cpp +++ /dev/null @@ -1,139 +0,0 @@ -#include - -nn::es::SectionHeader_V2::SectionHeader_V2() -{} - -nn::es::SectionHeader_V2::SectionHeader_V2(const SectionHeader_V2 & other) -{ - *this = other; -} - -void nn::es::SectionHeader_V2::operator=(const SectionHeader_V2 & other) -{ - if (other.getBytes().size()) - { - fromBytes(other.getBytes().data(), other.getBytes().size()); - } - else - { - mRawBinary.clear(); - mSectionOffset = other.mSectionOffset; - mRecordSize = other.mRecordSize; - mSectionSize = other.mSectionSize; - mRecordNum = other.mRecordNum; - mSectionType = other.mSectionType; - } -} - -bool nn::es::SectionHeader_V2::operator==(const SectionHeader_V2 & other) const -{ - return (mSectionOffset == other.mSectionOffset) \ - && (mRecordSize == other.mRecordSize) \ - && (mSectionSize == other.mSectionSize) \ - && (mRecordNum == other.mRecordNum) \ - && (mSectionType == other.mSectionType); -} - -bool nn::es::SectionHeader_V2::operator!=(const SectionHeader_V2 & other) const -{ - return !(*this ==other); -} - -void nn::es::SectionHeader_V2::toBytes() -{ - mRawBinary.alloc(sizeof(sSectionHeader_v2)); - sSectionHeader_v2* hdr = (sSectionHeader_v2*)mRawBinary.data(); - - hdr->section_offset = (mSectionOffset); - hdr->record_size = (mRecordSize); - hdr->section_size = (mSectionSize); - hdr->record_num = (mRecordNum); - hdr->section_type = (mSectionType); -} - -void nn::es::SectionHeader_V2::fromBytes(const byte_t * bytes, size_t len) -{ - if (len < sizeof(sSectionHeader_v2)) - { - throw fnd::Exception(kModuleName, "Binary too small"); - } - - clear(); - - mRawBinary.alloc(sizeof(sSectionHeader_v2)); - memcpy(mRawBinary.data(), bytes, mRawBinary.size()); - sSectionHeader_v2* hdr = (sSectionHeader_v2*)mRawBinary.data(); - - mSectionOffset = hdr->section_offset.get(); - mRecordSize = hdr->record_size.get(); - mSectionSize = hdr->section_size.get(); - mRecordNum = hdr->record_num.get(); - mSectionType = (ticket::SectionType)hdr->section_type.get(); -} - -const fnd::Vec& nn::es::SectionHeader_V2::getBytes() const -{ - return mRawBinary; -} - -void nn::es::SectionHeader_V2::clear() -{ - mRawBinary.clear(); - mSectionOffset = 0; - mRecordSize = 0; - mSectionSize = 0; - mRecordNum = 0; - mSectionType = ticket::SECTION_PERMANENT; -} - -uint32_t nn::es::SectionHeader_V2::getSectionOffset() const -{ - return mSectionOffset; -} - -void nn::es::SectionHeader_V2::setSectionOffset(uint32_t offset) -{ - mSectionOffset = offset; -} - -uint32_t nn::es::SectionHeader_V2::getRecordSize() const -{ - return mRecordSize; -} - -void nn::es::SectionHeader_V2::setRecordSize(uint32_t size) -{ - mRecordSize = size; -} - -uint32_t nn::es::SectionHeader_V2::getSectionSize() const -{ - return mSectionSize; -} - -void nn::es::SectionHeader_V2::getSectionSize(uint32_t size) -{ - mSectionSize = size; -} - -uint16_t nn::es::SectionHeader_V2::getRecordNum() const -{ - return mRecordNum; -} - -void nn::es::SectionHeader_V2::setRecordNum(uint16_t record_num) -{ - mRecordNum = record_num; -} - -nn::es::ticket::SectionType nn::es::SectionHeader_V2::getSectionType() const -{ - return mSectionType; -} - -void nn::es::SectionHeader_V2::setSectionType(ticket::SectionType type) -{ - mSectionType = type; -} - - diff --git a/lib/libes/source/TicketBody_V2.cpp b/lib/libes/source/TicketBody_V2.cpp deleted file mode 100644 index 1a5302d..0000000 --- a/lib/libes/source/TicketBody_V2.cpp +++ /dev/null @@ -1,326 +0,0 @@ -#include - -nn::es::TicketBody_V2::TicketBody_V2() -{ - clear(); -} - -nn::es::TicketBody_V2::TicketBody_V2(const TicketBody_V2 & other) -{ - *this = other; -} - -void nn::es::TicketBody_V2::operator=(const TicketBody_V2 & other) -{ - if (other.getBytes().size()) - { - fromBytes(other.getBytes().data(), other.getBytes().size()); - } - else - { - clear(); - mIssuer = other.mIssuer; - memcpy(mEncTitleKey, other.mEncTitleKey, ticket::kEncTitleKeySize); - mEncType = other.mEncType; - mTicketVersion = other.mTicketVersion; - mLicenseType = other.mLicenseType; - mCommonKeyId = other.mCommonKeyId; - mPropertyFlags = other.mPropertyFlags; - memcpy(mReservedRegion, other.mReservedRegion, ticket::kReservedRegionSize); - mTicketId = other.mTicketId; - mDeviceId = other.mDeviceId; - memcpy(mRightsId, other.mRightsId, ticket::kRightsIdSize); - mAccountId = other.mAccountId; - mSectTotalSize = other.mSectTotalSize; - mSectHeaderOffset = other.mSectHeaderOffset; - mSectNum = other.mSectNum; - mSectEntrySize = other.mSectEntrySize; - } -} - -bool nn::es::TicketBody_V2::operator==(const TicketBody_V2 & other) const -{ - return (mIssuer == other.mIssuer) \ - && (memcmp(mEncTitleKey, other.mEncTitleKey, ticket::kEncTitleKeySize) == 0) \ - && (mEncType == other.mEncType) \ - && (mTicketVersion == other.mTicketVersion) \ - && (mLicenseType == other.mLicenseType) \ - && (mPropertyFlags == other.mPropertyFlags) \ - && (memcmp(mReservedRegion, other.mReservedRegion, ticket::kReservedRegionSize) == 0) \ - && (mTicketId == other.mTicketId) \ - && (mDeviceId == other.mDeviceId) \ - && (memcmp(mRightsId, other.mRightsId, ticket::kRightsIdSize) == 0) \ - && (mAccountId == other.mAccountId) \ - && (mSectTotalSize == other.mSectTotalSize) \ - && (mSectHeaderOffset == other.mSectHeaderOffset) \ - && (mSectNum == other.mSectNum) \ - && (mSectEntrySize == other.mSectEntrySize); -} - -bool nn::es::TicketBody_V2::operator!=(const TicketBody_V2 & other) const -{ - return !(*this == other); -} - -void nn::es::TicketBody_V2::toBytes() -{ - mRawBinary.alloc(sizeof(sTicketBody_v2)); - sTicketBody_v2* body = (sTicketBody_v2*)mRawBinary.data(); - - body->format_version = (ticket::kFormatVersion); - - strncpy(body->issuer, mIssuer.c_str(), ticket::kIssuerSize); - memcpy(body->enc_title_key, mEncTitleKey, ticket::kEncTitleKeySize); - body->title_key_enc_type = (mEncType); - body->ticket_version = (mTicketVersion); - body->license_type = mLicenseType; - body->common_key_id = mCommonKeyId; - byte_t property_mask = 0; - for (size_t i = 0; i < mPropertyFlags.size(); i++) - { - property_mask |= _BIT(mPropertyFlags[i]); - } - body->property_mask = (property_mask); - memcpy(body->reserved_region, mReservedRegion, ticket::kReservedRegionSize); - body->ticket_id = (mTicketId); - body->device_id = (mDeviceId); - memcpy(body->rights_id, mRightsId, ticket::kRightsIdSize); - body->account_id = (mAccountId); - body->sect_total_size = (mSectTotalSize); - body->sect_header_offset = (mSectHeaderOffset); - body->sect_num = (mSectNum); - body->sect_entry_size = (mSectEntrySize); -} - -void nn::es::TicketBody_V2::fromBytes(const byte_t * bytes, size_t len) -{ - if (len < sizeof(sTicketBody_v2)) - { - throw fnd::Exception(kModuleName, "Header size too small"); - } - - clear(); - - mRawBinary.alloc(sizeof(sTicketBody_v2)); - memcpy(mRawBinary.data(), bytes, mRawBinary.size()); - sTicketBody_v2* body = (sTicketBody_v2*)mRawBinary.data(); - - if (body->format_version != ticket::kFormatVersion) - { - throw fnd::Exception(kModuleName, "Unsupported format version"); - } - - mIssuer = std::string(body->issuer, _MIN(strlen(body->issuer), ticket::kIssuerSize)); - memcpy(mEncTitleKey, body->enc_title_key, ticket::kEncTitleKeySize); - mEncType = (ticket::TitleKeyEncType)body->title_key_enc_type; - mTicketVersion = body->ticket_version.get(); - mLicenseType = (ticket::LicenseType)body->license_type; - mCommonKeyId = body->common_key_id; - for (size_t i = 0; i < mPropertyFlags.size(); i++) - { - if (_HAS_BIT(body->property_mask, i)) - mPropertyFlags.addElement((ticket::PropertyMaskFlags)i); - } - memcpy(mReservedRegion, body->reserved_region, ticket::kReservedRegionSize); - mTicketId = body->ticket_id.get(); - mDeviceId = body->device_id.get(); - memcpy(mRightsId, body->rights_id, ticket::kRightsIdSize); - mAccountId = body->account_id.get(); - mSectTotalSize = body->sect_total_size.get(); - mSectHeaderOffset = body->sect_header_offset.get(); - mSectNum = body->sect_num.get(); - mSectEntrySize = body->sect_entry_size.get(); -} - -const fnd::Vec& nn::es::TicketBody_V2::getBytes() const -{ - return mRawBinary; -} - -void nn::es::TicketBody_V2::clear() -{ - mRawBinary.clear(); - mIssuer.clear(); - memset(mEncTitleKey, 0, ticket::kEncTitleKeySize); - mEncType = ticket::AES128_CBC; - mTicketVersion = 0; - mLicenseType = ticket::LICENSE_PERMANENT; - mCommonKeyId = 0; - mPropertyFlags.clear(); - memset(mReservedRegion, 0, ticket::kReservedRegionSize); - mTicketId = 0; - mDeviceId = 0; - memset(mRightsId, 0, ticket::kRightsIdSize); - mAccountId = 0; - mSectTotalSize = 0; - mSectHeaderOffset = 0; - mSectNum = 0; - mSectEntrySize = 0; -} - -const std::string & nn::es::TicketBody_V2::getIssuer() const -{ - return mIssuer; -} - -void nn::es::TicketBody_V2::setIssuer(const std::string & issuer) -{ - if (issuer.length() > ticket::kIssuerSize) - { - throw fnd::Exception(kModuleName, "Issuer is too long"); - } - - mIssuer = issuer; -} - -const byte_t * nn::es::TicketBody_V2::getEncTitleKey() const -{ - return mEncTitleKey; -} - -void nn::es::TicketBody_V2::setEncTitleKey(const byte_t * data, size_t len) -{ - memset(mEncTitleKey, 0, ticket::kEncTitleKeySize); - memcpy(mEncTitleKey, data, _MIN(len, ticket::kEncTitleKeySize)); -} - -nn::es::ticket::TitleKeyEncType nn::es::TicketBody_V2::getTitleKeyEncType() const -{ - return mEncType; -} - -void nn::es::TicketBody_V2::setTitleKeyEncType(ticket::TitleKeyEncType type) -{ - mEncType = type; -} - -uint16_t nn::es::TicketBody_V2::getTicketVersion() const -{ - return mTicketVersion; -} - -void nn::es::TicketBody_V2::setTicketVersion(uint16_t version) -{ - mTicketVersion = version; -} - -nn::es::ticket::LicenseType nn::es::TicketBody_V2::getLicenseType() const -{ - return mLicenseType; -} - -void nn::es::TicketBody_V2::setLicenseType(ticket::LicenseType type) -{ - mLicenseType = type; -} - -byte_t nn::es::TicketBody_V2::getCommonKeyId() const -{ - return mCommonKeyId; -} - -void nn::es::TicketBody_V2::setCommonKeyId(byte_t id) -{ - mCommonKeyId = id; -} - -const fnd::List& nn::es::TicketBody_V2::getPropertyFlags() const -{ - return mPropertyFlags; -} - -void nn::es::TicketBody_V2::setPropertyFlags(const fnd::List& flags) -{ - mPropertyFlags = flags; -} - -const byte_t * nn::es::TicketBody_V2::getReservedRegion() const -{ - return mReservedRegion; -} - -void nn::es::TicketBody_V2::setReservedRegion(const byte_t * data, size_t len) -{ - memset(mReservedRegion, 0, ticket::kReservedRegionSize); - memcpy(mReservedRegion, data, _MIN(len, ticket::kReservedRegionSize)); -} - -uint64_t nn::es::TicketBody_V2::getTicketId() const -{ - return mTicketId; -} - -void nn::es::TicketBody_V2::setTicketId(uint64_t id) -{ - mTicketId = id; -} - -uint64_t nn::es::TicketBody_V2::getDeviceId() const -{ - return mDeviceId; -} - -void nn::es::TicketBody_V2::setDeviceId(uint64_t id) -{ - mDeviceId = id; -} - -const byte_t * nn::es::TicketBody_V2::getRightsId() const -{ - return mRightsId; -} - -void nn::es::TicketBody_V2::setRightsId(const byte_t * id) -{ - memcpy(mRightsId, id, ticket::kRightsIdSize); -} - -uint32_t nn::es::TicketBody_V2::getAccountId() const -{ - return mAccountId; -} - -void nn::es::TicketBody_V2::setAccountId(uint32_t id) -{ - mAccountId = id; -} - -uint32_t nn::es::TicketBody_V2::getSectionTotalSize() const -{ - return mSectTotalSize; -} - -void nn::es::TicketBody_V2::setSectionTotalSize(uint32_t size) -{ - mSectTotalSize = size; -} - -uint32_t nn::es::TicketBody_V2::getSectionHeaderOffset() const -{ - return mSectHeaderOffset; -} - -void nn::es::TicketBody_V2::setSectionHeaderOffset(uint32_t offset) -{ - mSectHeaderOffset = offset; -} - -uint16_t nn::es::TicketBody_V2::getSectionNum() const -{ - return mSectNum; -} - -void nn::es::TicketBody_V2::setSectionNum(uint16_t num) -{ - mSectNum = num; -} - -uint16_t nn::es::TicketBody_V2::getSectionEntrySize() const -{ - return mSectEntrySize; -} - -void nn::es::TicketBody_V2::setSectionEntrySize(uint16_t size) -{ - mSectEntrySize = size; -} \ No newline at end of file diff --git a/lib/libfnd/include/fnd/AesCtrWrappedIFile.h b/lib/libfnd/include/fnd/AesCtrWrappedIFile.h deleted file mode 100644 index 88b2df6..0000000 --- a/lib/libfnd/include/fnd/AesCtrWrappedIFile.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once -#include -#include -#include -#include - -namespace fnd -{ - class AesCtrWrappedIFile : public fnd::IFile - { - public: - AesCtrWrappedIFile(const fnd::SharedPtr& file, const fnd::aes::sAes128Key& key, const fnd::aes::sAesIvCtr& ctr); - - size_t size(); - void seek(size_t offset); - void read(byte_t* out, size_t len); - void read(byte_t* out, size_t offset, size_t len); - void write(const byte_t* out, size_t len); - void write(const byte_t* out, size_t offset, size_t len); - private: - const std::string kModuleName = "AesCtrWrappedIFile"; - static const size_t kCacheSize = 0x10000; - static const size_t kCacheSizeAllocSize = kCacheSize + fnd::aes::kAesBlockSize; - - fnd::SharedPtr mFile; - fnd::aes::sAes128Key mKey; - fnd::aes::sAesIvCtr mBaseCtr, mCurrentCtr; - size_t mFileOffset; - - fnd::Vec mCache; - }; -} \ No newline at end of file diff --git a/lib/libfnd/include/fnd/BitMath.h b/lib/libfnd/include/fnd/BitMath.h deleted file mode 100644 index 722036a..0000000 --- a/lib/libfnd/include/fnd/BitMath.h +++ /dev/null @@ -1,14 +0,0 @@ -/* -BitMath.h -(c) 2018 Jakcron -*/ -#pragma once - -// to be deprecated -#define BIT(n) (1ULL << (n)) - -// Bit math macros -#define _BIT(n) BIT(n) -#define _HAS_BIT(val, bit) (((val) & _BIT(bit)) != 0) -#define _SET_BIT(val, bit) ((val) |= _BIT(bit)) -#define _BITMASK(width) (_BIT(width)-1) \ No newline at end of file diff --git a/lib/libfnd/include/fnd/Endian.h b/lib/libfnd/include/fnd/Endian.h deleted file mode 100644 index db793f8..0000000 --- a/lib/libfnd/include/fnd/Endian.h +++ /dev/null @@ -1,118 +0,0 @@ -#pragma once -#include - -static inline uint16_t __local_bswap16(uint16_t x) { - return ((x << 8) & 0xff00) | ((x >> 8) & 0x00ff); -} - - -static inline uint32_t __local_bswap32(uint32_t x) { - return ((x << 24) & 0xff000000 ) | - ((x << 8) & 0x00ff0000 ) | - ((x >> 8) & 0x0000ff00 ) | - ((x >> 24) & 0x000000ff ); -} - -static inline uint64_t __local_bswap64(uint64_t x) -{ - return (uint64_t)__local_bswap32(x>>32) | - ((uint64_t)__local_bswap32(x&0xFFFFFFFF) << 32); -} - -#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ -static inline uint64_t be_dword(uint64_t a) { return __local_bswap64(a); } -static inline uint32_t be_word(uint32_t a) { return __local_bswap32(a); } -static inline uint16_t be_hword(uint16_t a) { return __local_bswap16(a); } -static inline uint64_t le_dword(uint64_t a) { return a; } -static inline uint32_t le_word(uint32_t a) { return a; } -static inline uint16_t le_hword(uint16_t a) { return a; } -#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ -static inline uint64_t be_dword(uint64_t a) { return a; } -static inline uint32_t be_word(uint32_t a) { return a; } -static inline uint16_t be_hword(uint16_t a) { return a; } -static inline uint64_t le_dword(uint64_t a) { return __local_bswap64(a); } -static inline uint32_t le_word(uint32_t a) { return __local_bswap32(a); } -static inline uint16_t le_hword(uint16_t a) { return __local_bswap16(a); } -#else -#error "What's the endianness of the platform you're targeting?" -#endif - -/* -template -class ISerialiseablePrimative { -public: - inline T get() const { return F(mVar);} - inline void set(T var) { mVar = F(var); } - inline T operator=(T var) { set(var); return get();} - inline T operator*() const { return get(); } -private: - T mVar; -}; - -typedef ISerialiseablePrimative le_uint16_t; -typedef ISerialiseablePrimative be_uint16_t; -typedef ISerialiseablePrimative le_uint32_t; -typedef ISerialiseablePrimative be_uint32_t; -typedef ISerialiseablePrimative le_uint64_t; -typedef ISerialiseablePrimative be_uint64_t; -*/ - -class le_uint16_t { -public: - inline uint16_t get() const { return le_hword(mVar);} - inline void set(uint16_t var) { mVar = le_hword(var); } - inline uint16_t operator=(uint16_t var) { set(var); return get();} - inline uint16_t operator*() const { return get(); } -private: - uint16_t mVar; -}; - -class be_uint16_t { -public: - inline uint16_t get() const { return be_hword(mVar);} - inline void set(uint16_t var) { mVar = be_hword(var); } - inline uint16_t operator=(uint16_t var) { set(var); return get();} - inline uint16_t operator*() const { return get(); } -private: - uint16_t mVar; -}; - -class le_uint32_t { -public: - inline uint32_t get() const { return le_word(mVar);} - inline void set(uint32_t var) { mVar = le_word(var); } - inline uint32_t operator=(uint32_t var) { set(var); return get();} - inline uint32_t operator*() const { return get(); } -private: - uint32_t mVar; -}; - -class be_uint32_t { -public: - inline uint32_t get() const { return be_word(mVar);} - inline void set(uint32_t var) { mVar = be_word(var); } - inline uint32_t operator=(uint32_t var) { set(var); return get();} - inline uint32_t operator*() const { return get(); } -private: - uint32_t mVar; -}; - -class le_uint64_t { -public: - inline uint64_t get() const { return le_dword(mVar);} - inline void set(uint64_t var) { mVar = le_dword(var); } - inline uint64_t operator=(uint64_t var) { set(var); return get();} - inline uint64_t operator*() const { return get(); } -private: - uint64_t mVar; -}; - -class be_uint64_t { -public: - inline uint64_t get() const { return be_dword(mVar);} - inline void set(uint64_t var) { mVar = be_dword(var); } - inline uint64_t operator=(uint64_t var) { set(var); return get();} - inline uint64_t operator*() const { return get(); } -private: - uint64_t mVar; -}; \ No newline at end of file diff --git a/lib/libfnd/include/fnd/Exception.h b/lib/libfnd/include/fnd/Exception.h deleted file mode 100644 index e26c45e..0000000 --- a/lib/libfnd/include/fnd/Exception.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once -#include -#include - -namespace fnd -{ - class Exception : public std::exception - { - public: - Exception() noexcept; - Exception(const std::string& what) noexcept; - Exception(const std::string& module, const std::string& what) noexcept; - - const char* what() const noexcept; - const char* module() const noexcept; - const char* error() const noexcept; - private: - std::string what_; - std::string module_; - std::string error_; - }; -} - - diff --git a/lib/libfnd/include/fnd/IByteModel.h b/lib/libfnd/include/fnd/IByteModel.h deleted file mode 100644 index 6f92187..0000000 --- a/lib/libfnd/include/fnd/IByteModel.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once -#include -#include - -namespace fnd -{ - class IByteModel - { - public: - virtual ~IByteModel() = default; - - // serialise - virtual void toBytes() = 0; - // deserialise - virtual void fromBytes(const byte_t* data, size_t len) = 0; - - // get byte vector - virtual const fnd::Vec& getBytes() const = 0; - - // clear data - virtual void clear() = 0; - }; -} \ No newline at end of file diff --git a/lib/libfnd/include/fnd/IFile.h b/lib/libfnd/include/fnd/IFile.h deleted file mode 100644 index e93bbf0..0000000 --- a/lib/libfnd/include/fnd/IFile.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once -#include - -namespace fnd -{ - class IFile - { - public: - virtual ~IFile() = default; - - virtual size_t size() = 0; - virtual void seek(size_t offset) = 0; - virtual void read(byte_t* out, size_t len) = 0; - virtual void read(byte_t* out, size_t offset, size_t len) = 0; - virtual void write(const byte_t* out, size_t len) = 0; - virtual void write(const byte_t* out, size_t offset, size_t len) = 0; - }; -} diff --git a/lib/libfnd/include/fnd/LayeredIntegrityMetadata.h b/lib/libfnd/include/fnd/LayeredIntegrityMetadata.h deleted file mode 100644 index 7d1e3ac..0000000 --- a/lib/libfnd/include/fnd/LayeredIntegrityMetadata.h +++ /dev/null @@ -1,59 +0,0 @@ -#pragma once -#include -#include -#include - -namespace fnd -{ - class LayeredIntegrityMetadata - { - public: - struct sLayer - { - size_t offset; - size_t size; - size_t block_size; - - void operator=(const sLayer& other) - { - offset = other.offset; - size = other.size; - block_size = other.block_size; - } - - bool operator==(const sLayer& other) const - { - return (offset == other.offset && size == other.size && block_size == other.block_size); - } - - bool operator!=(const sLayer& other) const - { - return !(*this == other); - } - }; - - LayeredIntegrityMetadata(); - - void operator=(const LayeredIntegrityMetadata& other); - bool operator==(const LayeredIntegrityMetadata& other) const; - bool operator!=(const LayeredIntegrityMetadata& other) const; - - const fnd::List& getHashLayerInfo() const; - void setHashLayerInfo(const fnd::List& layer_info); - - const sLayer& getDataLayer() const; - void setDataLayerInfo(const sLayer& data_info); - - const fnd::List& getMasterHashList() const; - void setMasterHashList(const fnd::List& master_hash_list); - - bool getAlignHashToBlock() const; - void setAlignHashToBlock(bool doAlign); - private: - // data - fnd::List mLayerInfo; - sLayer mDataLayer; - fnd::List mMasterHashList; - bool mDoAlignHashToBlock; - }; -} \ No newline at end of file diff --git a/lib/libfnd/include/fnd/LayeredIntegrityWrappedIFile.h b/lib/libfnd/include/fnd/LayeredIntegrityWrappedIFile.h deleted file mode 100644 index 2bc2a4d..0000000 --- a/lib/libfnd/include/fnd/LayeredIntegrityWrappedIFile.h +++ /dev/null @@ -1,47 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include -#include - -namespace fnd -{ - class LayeredIntegrityWrappedIFile : public fnd::IFile - { - public: - LayeredIntegrityWrappedIFile(const fnd::SharedPtr& file, const LayeredIntegrityMetadata& hdr); - - size_t size(); - void seek(size_t offset); - void read(byte_t* out, size_t len); - void read(byte_t* out, size_t offset, size_t len); - void write(const byte_t* out, size_t len); - void write(const byte_t* out, size_t offset, size_t len); - private: - const std::string kModuleName = "LayeredIntegrityWrappedIFile"; - static const size_t kDefaultCacheSize = 0x10000; - std::stringstream mErrorSs; - - fnd::SharedPtr mFile; - - // data file - fnd::SharedPtr mData; - size_t mDataOffset; - size_t mDataBlockSize; - fnd::List mDataHashLayer; - bool mAlignHashCalcToBlock; - - fnd::Vec mCache; - size_t mCacheBlockNum; - - inline size_t getOffsetBlock(size_t offset) const { return offset / mDataBlockSize; } - inline size_t getOffsetInBlock(size_t offset) const { return offset % mDataBlockSize; } - inline size_t getRemanderBlockReadSize(size_t total_size) const { return total_size % mDataBlockSize; } - inline size_t getBlockNum(size_t total_size) const { return (total_size / mDataBlockSize) + (getRemanderBlockReadSize(total_size) > 0); } - - void initialiseDataLayer(const LayeredIntegrityMetadata& hdr); - void readData(size_t block_offset, size_t block_num); - }; -} \ No newline at end of file diff --git a/lib/libfnd/include/fnd/List.h b/lib/libfnd/include/fnd/List.h deleted file mode 100644 index d15d8ba..0000000 --- a/lib/libfnd/include/fnd/List.h +++ /dev/null @@ -1,167 +0,0 @@ -#pragma once -#include -#include -//#include - -namespace fnd -{ - template - class List - { - public: - // constructors - List(); - List(const List& other); - - // copy operator - void operator=(const List& other); - - // equivalence operators - bool operator==(const List& other) const; - bool operator!=(const List& other) const; - - // back relative insertion - void addElement(const T& element); - - // element access - const T& operator[](size_t index) const; - T& operator[](size_t index); - const T& atBack() const; - T& atBack(); - - // element num - size_t size() const; - - // clear List - void clear(); - - // element access by key - template - bool hasElement(const K& key) const; - template - const T& getElement(const K& key) const; - template - T& getElement(const K& key); - - private: - std::vector m_Vec; - }; - - template - inline List::List() : - m_Vec() - { - } - - template - inline List::List(const List& other) : - List() - { - *this = other; - } - - template - inline void List::operator=(const List& other) - { - m_Vec = other.m_Vec; - } - - template - inline bool List::operator==(const List& other) const - { - return m_Vec == other.m_Vec; - } - - template - inline bool List::operator!=(const List& other) const - { - return !(*this == other); - } - - template - inline void List::addElement(const T & element) - { - m_Vec.push_back(element); - } - - template - inline const T & List::operator[](size_t index) const - { - return m_Vec[index]; - } - - template - inline T & List::operator[](size_t index) - { - return m_Vec[index]; - } - - template - inline const T & List::atBack() const - { - return m_Vec.back(); - } - - template - inline T & List::atBack() - { - return m_Vec.back(); - } - - template - inline size_t List::size() const - { - return m_Vec.size(); - } - - template - inline void List::clear() - { - m_Vec.clear(); - } - - template - template - inline bool List::hasElement(const K & key) const - { - for (size_t i = 0; i < m_Vec.size(); i++) - { - if (m_Vec[i] == key) - { - return true; - } - } - - return false; - } - - template - template - inline const T & List::getElement(const K & key) const - { - for (size_t i = 0; i < m_Vec.size(); i++) - { - if (m_Vec[i] == key) - { - return m_Vec[i]; - } - } - - throw fnd::Exception("getElement(): element does not exist"); - } - - template - template - inline T & List::getElement(const K & key) - { - for (size_t i = 0; i < m_Vec.size(); i++) - { - if (m_Vec[i] == key) - { - return m_Vec[i]; - } - } - - throw fnd::Exception("getElement(): element does not exist"); - } -} diff --git a/lib/libfnd/include/fnd/OffsetAdjustedIFile.h b/lib/libfnd/include/fnd/OffsetAdjustedIFile.h deleted file mode 100644 index 706e63c..0000000 --- a/lib/libfnd/include/fnd/OffsetAdjustedIFile.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once -#include -#include - -namespace fnd -{ - class OffsetAdjustedIFile : public fnd::IFile - { - public: - OffsetAdjustedIFile(const fnd::SharedPtr& file, size_t offset, size_t size); - - size_t size(); - void seek(size_t offset); - void read(byte_t* out, size_t len); - void read(byte_t* out, size_t offset, size_t len); - void write(const byte_t* out, size_t len); - void write(const byte_t* out, size_t offset, size_t len); - private: - fnd::SharedPtr mFile; - size_t mBaseOffset, mCurrentOffset; - size_t mSize; - }; -} \ No newline at end of file diff --git a/lib/libfnd/include/fnd/ResourceFileReader.h b/lib/libfnd/include/fnd/ResourceFileReader.h deleted file mode 100644 index ed9eb05..0000000 --- a/lib/libfnd/include/fnd/ResourceFileReader.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once -#include -#include - -namespace fnd -{ - class ResourceFileReader - { - public: - ResourceFileReader(); - - void processFile(const std::string& path); - - bool doesExist(const std::string& key) const; - const std::string& operator[](const std::string& key); - - private: - const std::string kModuleName = "ResourceFileReader"; - - std::map mResources; - }; -} diff --git a/lib/libfnd/include/fnd/SharedPtr.h b/lib/libfnd/include/fnd/SharedPtr.h deleted file mode 100644 index e976d4e..0000000 --- a/lib/libfnd/include/fnd/SharedPtr.h +++ /dev/null @@ -1,141 +0,0 @@ -#pragma once -#include -#include - -namespace fnd -{ - template - class SharedPtr - { - public: - SharedPtr(); - - // constructor for creating owner object - SharedPtr(T* ptr); - - // copy constructor - SharedPtr(const SharedPtr& other); - - // destructor - ~SharedPtr(); - - // own operator - void operator=(T* ptr); - - // copy operator - void operator=(const SharedPtr& other); - - // access ptr - const T* operator*() const; - T* operator*(); - - private: - T* mPtr; - size_t* mRefCnt; - - void deletePtr(); - }; - - template - inline SharedPtr::SharedPtr() : - mPtr(nullptr), - mRefCnt(new size_t) - { - *mRefCnt = 0; - } - - template - inline SharedPtr::SharedPtr(T* ptr) : - SharedPtr() - { - *this = ptr; - } - - template - inline SharedPtr::SharedPtr(const SharedPtr& other) : - SharedPtr() - { - *this = other; - } - - template - inline SharedPtr::~SharedPtr() - { - deletePtr(); - } - - template - inline void SharedPtr::operator=(T* ptr) - { - deletePtr(); - if (ptr != nullptr) - { - mPtr = ptr; - mRefCnt = new size_t; - *mRefCnt = 1; - } - else - { - mPtr = nullptr; - mRefCnt = new size_t; - *mRefCnt = 0; - } - - } - - template - inline void SharedPtr::operator=(const SharedPtr& other) - { - deletePtr(); - - mPtr = other.mPtr; - mRefCnt = other.mRefCnt; - *mRefCnt += 1; - } - - template - inline const T* SharedPtr::operator*() const - { - return mPtr; - } - - template - inline T* SharedPtr::operator*() - { - return mPtr; - } - - template - inline void SharedPtr::deletePtr() - { - // if this is not the last reference - if (*mRefCnt > 1) - { - // decrement reference count - *mRefCnt -= 1; - - // make ptrs null - mPtr = nullptr; - mRefCnt = nullptr; - } - // if this is the last refeference - else if (*mRefCnt == 1) - { - // delete memory - delete mPtr; - delete mRefCnt; - - // make ptrs null - mPtr = nullptr; - mRefCnt = nullptr; - } - // else if this is an empty refernce - else if (*mRefCnt == 0) - { - delete mRefCnt; - - mPtr = nullptr; - mRefCnt = nullptr; - } - } -} \ No newline at end of file diff --git a/lib/libfnd/include/fnd/SimpleFile.h b/lib/libfnd/include/fnd/SimpleFile.h deleted file mode 100644 index 24d311a..0000000 --- a/lib/libfnd/include/fnd/SimpleFile.h +++ /dev/null @@ -1,54 +0,0 @@ -#pragma once -#include -#include -#ifdef _WIN32 -#include -#else -#include -#endif - -namespace fnd -{ - class SimpleFile : public IFile - { - public: - enum OpenMode - { - Read, - Edit, - Create - }; - - SimpleFile(); - SimpleFile(const std::string& path, OpenMode mode); - ~SimpleFile(); - - void open(const std::string& path, OpenMode mode); - bool isOpen() const; - void close(); - size_t size(); - void seek(size_t offset); - size_t pos(); - void read(byte_t* out, size_t len); - void read(byte_t* out, size_t offset, size_t len); - void write(const byte_t* out, size_t len); - void write(const byte_t* out, size_t offset, size_t len); - - private: - const std::string kModuleName = "SimpleFile"; - - bool mOpen; - OpenMode mMode; - -#ifdef _WIN32 - HANDLE mFileHandle; - DWORD getOpenModeFlag(OpenMode mode) const; - DWORD getShareModeFlag(OpenMode mode) const; - DWORD getCreationModeFlag(OpenMode mode) const; -#else - FILE* mFp; - const char* getOpenModeStr(OpenMode mode); -#endif - }; -} - diff --git a/lib/libfnd/include/fnd/SimpleTextOutput.h b/lib/libfnd/include/fnd/SimpleTextOutput.h deleted file mode 100644 index 15c3c8e..0000000 --- a/lib/libfnd/include/fnd/SimpleTextOutput.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once -#include -#include -#include - -namespace fnd -{ - class SimpleTextOutput - { - public: - static void hxdStyleDump(const byte_t* data, size_t len, size_t row_len, size_t byte_grouping_size); - static void hxdStyleDump(const byte_t* data, size_t len); - static void hexDump(const byte_t* data, size_t len, size_t row_len, size_t indent_len); - static void hexDump(const byte_t* data, size_t len); - static std::string arrayToString(const byte_t* data, size_t len, bool upper_case, const std::string& separator); - static void stringToArray(const std::string& str, fnd::Vec& array); - - private: - static const size_t kDefaultRowLen = 0x10; - static const size_t kDefaultByteGroupingSize = 1; - }; - -} \ No newline at end of file diff --git a/lib/libfnd/include/fnd/StringConv.h b/lib/libfnd/include/fnd/StringConv.h deleted file mode 100644 index 1b1c749..0000000 --- a/lib/libfnd/include/fnd/StringConv.h +++ /dev/null @@ -1,50 +0,0 @@ -#pragma once -#include -#include -#include - -namespace fnd -{ - class StringConv - { - public: - static std::u16string ConvertChar8ToChar16(const std::string& in); - static std::string ConvertChar16ToChar8(const std::u16string& in); - - private: - static const char32_t kUtf16EncodeMax = 0x10FFFF; - static const char32_t kUtf16NonNativeStart = 0x10000; - static const char16_t kUtf16SurrogateBits = 10; - static const char16_t kUtf16SurrogateMask = (1 << kUtf16SurrogateBits) - 1; - static const char16_t kUtf16HighSurrogateStart = 0xD800; - static const char16_t kUtf16HighSurrogateEnd = kUtf16HighSurrogateStart | kUtf16SurrogateMask; - static const char16_t kUtf16LowSurrogateStart = 0xDC00; - static const char16_t kUtf16LowSurrogateEnd = kUtf16LowSurrogateStart | kUtf16SurrogateMask; - - static const char32_t kUtf8AsciiStart = 0x00; - static const char32_t kUtf8AsciiEnd = 0x7F; - static const char32_t kUtf82ByteStart = 0x80; - static const char32_t kUtf82ByteEnd = 0x7FF; - static const char32_t kUtf83ByteStart = 0x800; - static const char32_t kUtf83ByteEnd = 0x7FFF; - static const char32_t kUtf84ByteStart = 0x8000; - static const char32_t kUtf84ByteEnd = 0x10FFFF; - - - static inline uint8_t make_utf8_prefix(uint8_t prefix_bits) { return ((uint8_t)(-1)) << (8 - prefix_bits); } - static inline uint8_t make_utf8_mask(uint8_t prefix_bits) { return ((uint8_t)(-1)) >> (prefix_bits + 1); } - static inline uint8_t make_utf8(uint8_t prefix_bits, uint8_t data) { return make_utf8_prefix(prefix_bits) | (data & make_utf8_mask(prefix_bits)); } - static inline uint8_t get_utf8_data(uint8_t prefix_bits, uint8_t utf8_chr) { return utf8_chr & make_utf8_mask(prefix_bits); } - static inline bool utf8_has_prefix(uint8_t prefix_bits, uint8_t utf8_chr) { return ((utf8_chr & make_utf8_prefix(prefix_bits)) == make_utf8_prefix(prefix_bits)) && ((utf8_chr & ~make_utf8_mask(prefix_bits)) == make_utf8_prefix(prefix_bits)); } - static inline uint8_t get_utf8_prefix(uint8_t utf8_chr) - { - uint8_t prefix = 0; - while ((utf8_chr & (1 << 7)) != 0) - { - utf8_chr <<= 1; - prefix++; - } - return prefix; - } - }; -} diff --git a/lib/libfnd/include/fnd/Vec.h b/lib/libfnd/include/fnd/Vec.h deleted file mode 100644 index 667027a..0000000 --- a/lib/libfnd/include/fnd/Vec.h +++ /dev/null @@ -1,207 +0,0 @@ -#pragma once -#include - -namespace fnd -{ - template - class Vec - { - public: - // constructors - Vec(); - Vec(const Vec& other); - Vec(const T* array, size_t num); - ~Vec(); - - // copy operator - void operator=(const Vec& other); - - // equivalence operators - bool operator==(const Vec& other) const; - bool operator!=(const Vec& other) const; - - // element access - const T& operator[](size_t index) const; - T& operator[](size_t index); - - // raw access - const T* data() const; - T* data(); - - // element num - size_t size() const; - - // allocate vector - void alloc(size_t new_size); - - // resize vector - void resize(size_t new_size); - - // clear vector - void clear(); - private: - T* m_Vec; - size_t m_Size; - - void copyFrom(const T * array, size_t num); - }; - - template - inline Vec::Vec() : - m_Vec(nullptr), - m_Size(0) - {} - - template - inline Vec::Vec(const Vec& other) : - Vec() - { - copyFrom(other.data(), other.size()); - } - - template - inline Vec::Vec(const T * array, size_t num) : - Vec() - { - copyFrom(array, num); - } - - template - inline Vec::~Vec() - { - clear(); - } - - template - inline void Vec::operator=(const Vec& other) - { - copyFrom(other.data(), other.size()); - } - - template - inline bool Vec::operator==(const Vec& other) const - { - bool isEqual = true; - - if (m_Size == other.m_Size) - { - for (size_t i = 0; i < m_Size && isEqual; i++) - { - if (m_Vec[i] != other.m_Vec[i]) - { - isEqual = false; - } - } - } - else - { - isEqual = false; - } - - return isEqual; - } - - template - inline bool Vec::operator!=(const Vec& other) const - { - return !(*this == other); - } - - template - inline const T & Vec::operator[](size_t index) const - { - return m_Vec[index]; - } - - template - inline T & Vec::operator[](size_t index) - { - return m_Vec[index]; - } - - template - inline const T * Vec::data() const - { - return m_Vec; - } - - template - inline T * Vec::data() - { - return m_Vec; - } - - template - inline size_t Vec::size() const - { - return m_Size; - } - - template - inline void Vec::alloc(size_t new_size) - { - clear(); - m_Vec = new T[new_size]; - if (m_Vec == nullptr) - { - fnd::Exception("Vec", "Failed to allocate memory for vector"); - } - for (size_t i = 0; i < new_size; i++) - { - m_Vec[i] = 0; - } - - m_Size = new_size; - } - - template - inline void Vec::resize(size_t new_size) - { - if (m_Vec != nullptr) - { - T* new_vec = new T[new_size]; - if (new_vec == nullptr) - { - fnd::Exception("Vec", "Failed to allocate memory for vector"); - } - for (size_t i = 0; i < new_size; i++) - { - new_vec[i] = 0; - } - - for (size_t i = 0; i < _MIN(m_Size, new_size); i++) - { - new_vec[i] = m_Vec[i]; - } - delete[] m_Vec; - m_Vec = new_vec; - m_Size = new_size; - } - else - { - alloc(new_size); - } - } - - template - inline void Vec::clear() - { - if (m_Vec != nullptr) - { - delete[] m_Vec; - } - m_Vec = nullptr; - m_Size = 0; - } - - template - inline void Vec::copyFrom(const T * array, size_t num) - { - clear(); - alloc(num); - for (size_t i = 0; i < m_Size; i++) - { - m_Vec[i] = array[i]; - } - } -} \ No newline at end of file diff --git a/lib/libfnd/include/fnd/aes.h b/lib/libfnd/include/fnd/aes.h deleted file mode 100644 index 2c3016f..0000000 --- a/lib/libfnd/include/fnd/aes.h +++ /dev/null @@ -1,117 +0,0 @@ -#pragma once -#include -#include - -namespace fnd -{ -namespace aes -{ - const size_t kAes128KeySize = 0x10; - const size_t kAesBlockSize = 0x10; - const size_t KAesCcmNonceSize = 0xc; - -#pragma pack (push, 1) - struct sAes128Key - { - uint8_t key[kAes128KeySize]; - - void set(const uint8_t key[kAes128KeySize]) - { - memcpy(this->key, key, kAes128KeySize); - } - - bool compare(const sAes128Key& other) const - { - return memcmp(this->key, other.key, kAes128KeySize) == 0; - } - - void operator=(const sAes128Key& other) - { - set(other.key); - } - bool operator==(const sAes128Key& other) const - { - return compare(other); - } - bool operator!=(const sAes128Key& other) const - { - return !compare(other); - } - - }; - - struct sAesXts128Key - { - uint8_t key[2][kAes128KeySize]; - - void set(const uint8_t key_0[kAes128KeySize], const uint8_t key_1[kAes128KeySize]) - { - memcpy(this->key[0], key_0, kAes128KeySize); - memcpy(this->key[1], key_1, kAes128KeySize); - } - - bool compare(const sAesXts128Key& other) const - { - return memcmp(this->key[0], other.key[0], kAes128KeySize) == 0 && memcmp(this->key[1], other.key[1], kAes128KeySize) == 0; - } - - void operator=(const sAesXts128Key& other) - { - set(other.key[0], other.key[1]); - } - bool operator==(const sAesXts128Key& other) const - { - return compare(other); - } - bool operator!=(const sAesXts128Key& other) const - { - return !compare(other); - } - }; - - struct sAesIvCtr - { - uint8_t iv[kAesBlockSize]; - - void set(const uint8_t iv[kAes128KeySize]) - { - memcpy(this->iv, iv, kAes128KeySize); - } - - bool compare(const sAesIvCtr& other) const - { - return memcmp(this->iv, other.iv, kAesBlockSize) == 0; - } - - void operator=(const sAesIvCtr& other) - { - set(other.iv); - } - bool operator==(const sAesIvCtr& other) const - { - return compare(other); - } - bool operator!=(const sAesIvCtr& other) const - { - return !compare(other); - } - }; -#pragma pack (pop) - - // aes-128 - void AesEcbDecrypt(const uint8_t* in, uint64_t size, const uint8_t key[kAes128KeySize], uint8_t* out); - void AesEcbEncrypt(const uint8_t* in, uint64_t size, const uint8_t key[kAes128KeySize], uint8_t* out); - - void AesCtr(const uint8_t* in, uint64_t size, const uint8_t key[kAes128KeySize], uint8_t ctr[kAesBlockSize], uint8_t* out); - void AesIncrementCounter(const uint8_t in[kAesBlockSize], size_t block_num, uint8_t out[kAesBlockSize]); - - void AesCbcDecrypt(const uint8_t* in, uint64_t size, const uint8_t key[kAes128KeySize], uint8_t iv[kAesBlockSize], uint8_t* out); - void AesCbcEncrypt(const uint8_t* in, uint64_t size, const uint8_t key[kAes128KeySize], uint8_t iv[kAesBlockSize], uint8_t* out); - - void AesXtsDecryptSector(const uint8_t* in, uint64_t sector_size, const uint8_t key1[kAes128KeySize], const uint8_t key2[kAes128KeySize], uint8_t tweak[kAesBlockSize], uint8_t* out); - void AesXtsEncryptSector(const uint8_t* in, uint64_t sector_size, const uint8_t key1[kAes128KeySize], const uint8_t key2[kAes128KeySize], uint8_t tweak[kAesBlockSize], uint8_t* out); - void AesXtsMakeTweak(uint8_t tweak[kAesBlockSize], size_t block_index); - - void GaloisFunc(uint8_t x[kAesBlockSize]); -} -} \ No newline at end of file diff --git a/lib/libfnd/include/fnd/base64.h b/lib/libfnd/include/fnd/base64.h deleted file mode 100644 index f9bbc08..0000000 --- a/lib/libfnd/include/fnd/base64.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once -#include -#include - -namespace fnd -{ -namespace base64 -{ - size_t B64_GetEncodeLen(const uint8_t* src, size_t slen); - void B64_Encode(const uint8_t* src, size_t slen, uint8_t* dst, size_t dlen); - size_t B64_GetDecodeLen(const uint8_t* src, size_t slen); - void B64_Decode(const uint8_t* src, size_t slen, uint8_t* dst, size_t dlen); -} -} \ No newline at end of file diff --git a/lib/libfnd/include/fnd/ecdsa.h b/lib/libfnd/include/fnd/ecdsa.h deleted file mode 100644 index aa9e48b..0000000 --- a/lib/libfnd/include/fnd/ecdsa.h +++ /dev/null @@ -1,83 +0,0 @@ -#pragma once -#include -#include - -namespace fnd -{ - namespace ecdsa - { - const size_t kEcdsa240Size = 0x1E; - - enum EcdsaType - { - ECDSA_240, - }; - -#pragma pack (push, 1) - struct sEcdsa240Point - { - uint8_t r[kEcdsa240Size]; - uint8_t s[kEcdsa240Size]; - - void operator=(const sEcdsa240Point& other) - { - memcpy(this->r, other.r, kEcdsa240Size); - memcpy(this->s, other.s, kEcdsa240Size); - } - - bool operator==(const sEcdsa240Point& other) const - { - return memcmp(this->r, other.r, kEcdsa240Size) == 0 \ - && memcmp(this->s, other.s, kEcdsa240Size) == 0; - } - - bool operator!=(const sEcdsa240Point& other) const - { - return !operator==(other); - } - }; - - struct sEcdsa240PrivateKey - { - uint8_t k[kEcdsa240Size]; - - void operator=(const sEcdsa240PrivateKey& other) - { - memcpy(this->k, other.k, kEcdsa240Size); - } - - bool operator==(const sEcdsa240PrivateKey& other) const - { - return memcmp(this->k, other.k, kEcdsa240Size) == 0; - } - - bool operator!=(const sEcdsa240PrivateKey& other) const - { - return !operator==(other); - } - }; - - struct sEcdsa240Key - { - sEcdsa240Point pub; - sEcdsa240PrivateKey pvt; - - void operator=(const sEcdsa240Key& other) - { - this->pub = other.pub; - this->pvt = other.pvt; - } - - bool operator==(const sEcdsa240Key& other) const - { - return this->pub == other.pub && this->pvt == other.pvt; - } - - bool operator!=(const sEcdsa240Key& other) const - { - return !operator==(other); - } - }; -#pragma pack (pop) - } -} diff --git a/lib/libfnd/include/fnd/elf.h b/lib/libfnd/include/fnd/elf.h deleted file mode 100644 index 0f32ccd..0000000 --- a/lib/libfnd/include/fnd/elf.h +++ /dev/null @@ -1,458 +0,0 @@ -#pragma once -#include "types.h" - -namespace fnd -{ - namespace elf - { - /* These constants are for the segment types stored in the image headers */ - enum SegmentType - { - PT_NULL = 0, - PT_LOAD = 1, - PT_DYNAMIC = 2, - PT_INTERP = 3, - PT_NOTE = 4, - PT_SHLIB = 5, - PT_PHDR = 6, - PT_TLS = 7, /* Thread local storage segment */ - PT_LOOS = 0x60000000, /* OS-specific */ - PT_HIOS = 0x6fffffff, /* OS-specific */ - PT_LOPROC = 0x70000000, - PT_HIPROC = 0x7fffffff - }; - - /* These constants define the different elf file types */ - enum ElfType - { - ET_NONE = 0, - ET_REL = 1, - ET_EXEC = 2, - ET_DYN = 3, - ET_CORE = 4, - ET_LOPROC = 0xff00, - ET_HIPROC = 0xffff - }; - - /* This is the info that is needed to parse the dynamic section of the file */ - enum DynamicSectionType - { - DT_NULL = 0, - DT_NEEDED = 1, - DT_PLTRELSZ = 2, - DT_PLTGOT = 3, - DT_HASH = 4, - DT_STRTAB = 5, - DT_SYMTAB = 6, - DT_RELA = 7, - DT_RELASZ = 8, - DT_RELAENT = 9, - DT_STRSZ = 10, - DT_SYMENT = 11, - DT_INIT = 12, - DT_FINI = 13, - DT_SONAME = 14, - DT_RPATH = 15, - DT_SYMBOLIC = 16, - DT_REL = 17, - DT_RELSZ = 18, - DT_RELENT = 19, - DT_PLTREL = 20, - DT_DEBUG = 21, - DT_TEXTREL = 22, - DT_JMPREL = 23, - DT_ENCODING = 32, - OLD_DT_LOOS = 0x60000000, - DT_LOOS = 0x6000000d, - DT_HIOS = 0x6ffff000, - DT_VALRNGLO = 0x6ffffd00, - DT_VALRNGHI = 0x6ffffdff, - DT_ADDRRNGLO = 0x6ffffe00, - DT_ADDRRNGHI = 0x6ffffeff, - DT_VERSYM = 0x6ffffff0, - DT_RELACOUNT = 0x6ffffff9, - DT_RELCOUNT = 0x6ffffffa, - DT_FLAGS_1 = 0x6ffffffb, - DT_VERDEF = 0x6ffffffc, - DT_VERDEFNUM = 0x6ffffffd, - DT_VERNEED = 0x6ffffffe, - DT_VERNEEDNUM = 0x6fffffff, - OLD_DT_HIOS = 0x6fffffff, - DT_LOPROC = 0x70000000, - DT_HIPROC = 0x7fffffff - }; - - /* This info is needed when parsing the symbol table */ - enum SymbolBinding - { - STB_LOCAL = 0, - STB_GLOBAL = 1, - STB_WEAK = 2, - STB_LOOS = 10, - STB_HIOS = 12, - STB_LOPROC, - STB_HIPROC = 0xf - }; - - enum SymbolType - { - STT_NOTYPE = 0, - STT_OBJECT = 1, - STT_FUNC = 2, - STT_SECTION = 3, - STT_FILE = 4, - STT_COMMON = 5, - STT_TLS = 6, - STT_LOOS = 10, - STT_HIOS = 12, - STT_LOPROC, - STT_HIPROC = 0xf - }; - - /* These constants define the permissions on sections in the program - header, p_flags. */ - enum PermissionFlag - { - PF_R = 0x4, - PF_W = 0x2, - PF_X = 0x1 - }; - - /* sh_type */ - enum SectionHeaderType - { - SHT_NULL = 0, - SHT_PROGBITS = 1, - SHT_SYMTAB = 2, - SHT_STRTAB = 3, - SHT_RELA = 4, - SHT_HASH = 5, - SHT_DYNAMIC = 6, - SHT_NOTE = 7, - SHT_NOBITS = 8, - SHT_REL = 9, - SHT_SHLIB = 10, - SHT_DYNSYM = 11, - SHT_NUM = 12, - SHT_LOPROC = 0x70000000, - SHT_HIPROC = 0x7fffffff, - SHT_LOUSER = 0x80000000, - SHT_HIUSER = 0xffffffff - }; - - /* sh_flags */ - enum SectionHeaderFlag - { - SHF_WRITE = 0x1, - SHF_ALLOC = 0x2, - SHF_EXECINSTR = 0x4, - SHF_RELA_LIVEPATCH = 0x00100000, - SHF_RO_AFTER_INIT = 0x00200000, - SHF_MASKPROC = 0xf0000000 - }; - - /* special section indexes */ - enum SpecialSectionIndex - { - SHN_UNDEF = 0, - SHN_LORESERVE = 0xff00, - SHN_LOPROC = 0xff00, - SHN_HIPROC = 0xff1f, - SHN_LOOS = 0xff20, - SHN_HIOS = 0xff3f, - SHN_ABS = 0xfff1, - SHN_COMMON = 0xfff2, - SHN_HIRESERVE = 0xffff - }; - - enum ElfIdentIndex - { - EI_MAG0 = 0, /* e_ident[] indexes */ - EI_MAG1 = 1, - EI_MAG2 = 2, - EI_MAG3 = 3, - EI_CLASS = 4, - EI_DATA = 5, - EI_VERSION = 6, - EI_OSABI = 7, - EI_PAD = 8 - }; - - enum ElfClass - { - ELFCLASSNONE = 0, /* EI_CLASS */ - ELFCLASS32 = 1, - ELFCLASS64 = 2, - ELFCLASSNUM = 3 - }; - - enum ElfData - { - ELFDATANONE = 0, /* e_ident[EI_DATA] */ - ELFDATA2LSB = 1, - ELFDATA2MSB = 2 - }; - - enum ElfVersion - { - EV_NONE = 0, /* e_version, EI_VERSION */ - EV_CURRENT = 1, - EV_NUM = 2, - }; - - enum ElfOsAbi - { - ELFOSABI_NONE = 0, - ELFOSABI_LINUX =3 - }; - - - /* - * Notes used in ET_CORE. Architectures export some of the arch register sets - * using the corresponding note types via the PTRACE_GETREGSET and - * PTRACE_SETREGSET requests. - */ - enum NoteType - { - NT_PRSTATUS = 1, - NT_PRFPREG = 2, - NT_PRPSINFO = 3, - NT_TASKSTRUCT = 4, - NT_AUXV = 6, - /* - * Note to userspace developers: size of NT_SIGINFO note may increase - * in the future to accomodate more fields, don't assume it is fixed! - */ - NT_SIGINFO = 0x53494749, - NT_FILE = 0x46494c45, - NT_PRXFPREG = 0x46e62b7f, /* copied from gdb5.1/include/elf/common.h */ - NT_PPC_VMX = 0x100, /* PowerPC Altivec/VMX registers */ - NT_PPC_SPE = 0x101, /* PowerPC SPE/EVR registers */ - NT_PPC_VSX = 0x102, /* PowerPC VSX registers */ - NT_PPC_TAR = 0x103, /* Target Address Register */ - NT_PPC_PPR = 0x104, /* Program Priority Register */ - NT_PPC_DSCR = 0x105, /* Data Stream Control Register */ - NT_PPC_EBB = 0x106, /* Event Based Branch Registers */ - NT_PPC_PMU = 0x107, /* Performance Monitor Registers */ - NT_PPC_TM_CGPR = 0x108, /* TM checkpointed GPR Registers */ - NT_PPC_TM_CFPR = 0x109, /* TM checkpointed FPR Registers */ - NT_PPC_TM_CVMX = 0x10a, /* TM checkpointed VMX Registers */ - NT_PPC_TM_CVSX = 0x10b, /* TM checkpointed VSX Registers */ - NT_PPC_TM_SPR = 0x10c, /* TM Special Purpose Registers */ - NT_PPC_TM_CTAR = 0x10d, /* TM checkpointed Target Address Register */ - NT_PPC_TM_CPPR = 0x10e, /* TM checkpointed Program Priority Register */ - NT_PPC_TM_CDSCR = 0x10f, /* TM checkpointed Data Stream Control Register */ - NT_PPC_PKEY = 0x110, /* Memory Protection Keys registers */ - NT_386_TLS = 0x200, /* i386 TLS slots (struct user_desc) */ - NT_386_IOPERM = 0x201, /* x86 io permission bitmap (1=deny) */ - NT_X86_XSTATE = 0x202, /* x86 extended state using xsave */ - NT_S390_HIGH_GPRS = 0x300, /* s390 upper register halves */ - NT_S390_TIMER = 0x301, /* s390 timer register */ - NT_S390_TODCMP = 0x302, /* s390 TOD clock comparator register */ - NT_S390_TODPREG = 0x303, /* s390 TOD programmable register */ - NT_S390_CTRS = 0x304, /* s390 control registers */ - NT_S390_PREFIX = 0x305, /* s390 prefix register */ - NT_S390_LAST_BREAK = 0x306, /* s390 breaking event address */ - NT_S390_SYSTEM_CALL = 0x307, /* s390 system call restart data */ - NT_S390_TDB = 0x308, /* s390 transaction diagnostic block */ - NT_S390_VXRS_LOW = 0x309, /* s390 vector registers 0-15 upper half */ - NT_S390_VXRS_HIGH = 0x30a, /* s390 vector registers 16-31 */ - NT_S390_GS_CB = 0x30b, /* s390 guarded storage registers */ - NT_S390_GS_BC = 0x30c, /* s390 guarded storage broadcast control block */ - NT_S390_RI_CB = 0x30d, /* s390 runtime instrumentation */ - NT_ARM_VFP = 0x400, /* ARM VFP/NEON registers */ - NT_ARM_TLS = 0x401, /* ARM TLS register */ - NT_ARM_HW_BREAK = 0x402, /* ARM hardware breakpoint registers */ - NT_ARM_HW_WATCH = 0x403, /* ARM hardware watchpoint registers */ - NT_ARM_SYSTEM_CALL = 0x404, /* ARM system call number */ - NT_ARM_SVE = 0x405, /* ARM Scalable Vector Extension registers */ - NT_ARC_V2 = 0x600, /* ARCv2 accumulator/extra registers */ - NT_VMCOREDD = 0x700, /* Vmcore Device Dump Note */ - NT_MIPS_DSP = 0x800, /* MIPS DSP ASE registers */ - NT_MIPS_FP_MODE = 0x801, /* MIPS floating-point mode */ - }; - - static const size_t kEIdentSize = 0x10; - static const byte_t kElfMagic[sizeof(uint32_t)] = {0x7f, 'E', 'L', 'F'}; - - - inline byte_t get_elf_st_bind(byte_t st_info) { return st_info >> 4; } - inline byte_t get_elf_st_type(byte_t st_info) { return st_info & 0xf; } - inline byte_t get_elf_st_info(byte_t st_bind, byte_t st_type) { return (st_type & 0xf) | ((st_bind & 0xf) << 4);} - - /* The following are used with relocations */ - #define ELF32_R_SYM(x) ((x) >> 8) - #define ELF32_R_TYPE(x) ((x) & 0xff) - - #define ELF64_R_SYM(i) ((i) >> 32) - #define ELF64_R_TYPE(i) ((i) & 0xffffffff) - } - - struct Elf32_Dyn - { - int32_t d_tag; - union{ - int32_t d_val; - uint32_t d_ptr; - } d_un; - }; - - struct Elf64_Dyn - { - int64_t d_tag; /* entry tag value */ - union { - uint64_t d_val; - uint64_t d_ptr; - } d_un; - }; - - struct Elf32_Rel - { - uint32_t r_offset; - uint32_t r_info; - }; - - struct Elf64_Rel - { - uint64_t r_offset; /* Location at which to apply the action */ - uint64_t r_info; /* index and type of relocation */ - }; - - struct Elf32_Rela - { - uint32_t r_offset; - uint32_t r_info; - int32_t r_addend; - }; - - struct Elf64_Rela - { - uint64_t r_offset; /* Location at which to apply the action */ - uint64_t r_info; /* index and type of relocation */ - int64_t r_addend; /* Constant addend used to compute value */ - }; - - struct Elf32_Sym - { - uint32_t st_name; - uint32_t st_value; - uint32_t st_size; - byte_t st_info; - byte_t st_other; - uint16_t st_shndx; - }; - - struct Elf64_Sym - { - uint32_t st_name; /* Symbol name, index in string tbl */ - byte_t st_info; /* Type and binding attributes */ - byte_t st_other; /* No defined meaning, 0 */ - uint16_t st_shndx; /* Associated section index */ - uint64_t st_value; /* Value of the symbol */ - uint64_t st_size; /* Associated symbol size */ - }; - - struct Elf32_Ehdr - { - byte_t e_ident[elf::kEIdentSize]; - uint16_t e_type; - uint16_t e_machine; - uint32_t e_version; - uint32_t e_entry; /* Entry point */ - uint32_t e_phoff; - uint32_t e_shoff; - uint32_t e_flags; - uint16_t e_ehsize; - uint16_t e_phentsize; - uint16_t e_phnum; - uint16_t e_shentsize; - uint16_t e_shnum; - uint16_t e_shstrndx; - }; - - struct Elf64_Ehdr - { - byte_t e_ident[elf::kEIdentSize]; /* ELF "magic number" */ - uint16_t e_type; - uint16_t e_machine; - uint32_t e_version; - uint64_t e_entry; /* Entry point virtual address */ - uint64_t e_phoff; /* Program header table file offset */ - uint64_t e_shoff; /* Section header table file offset */ - uint32_t e_flags; - uint16_t e_ehsize; - uint16_t e_phentsize; - uint16_t e_phnum; - uint16_t e_shentsize; - uint16_t e_shnum; - uint16_t e_shstrndx; - }; - - struct Elf32_Phdr - { - uint32_t p_type; - uint32_t p_offset; - uint32_t p_vaddr; - uint32_t p_paddr; - uint32_t p_filesz; - uint32_t p_memsz; - uint32_t p_flags; - uint32_t p_align; - }; - - struct Elf64_Phdr - { - uint32_t p_type; - uint32_t p_flags; - uint64_t p_offset; /* Segment file offset */ - uint64_t p_vaddr; /* Segment virtual address */ - uint64_t p_paddr; /* Segment physical address */ - uint64_t p_filesz; /* Segment size in file */ - uint64_t p_memsz; /* Segment size in memory */ - uint64_t p_align; /* Segment alignment, file & memory */ - }; - - struct Elf32_Shdr - { - uint32_t sh_name; - uint32_t sh_type; - uint32_t sh_flags; - uint32_t sh_addr; - uint32_t sh_offset; - uint32_t sh_size; - uint32_t sh_link; - uint32_t sh_info; - uint32_t sh_addralign; - uint32_t sh_entsize; - }; - - struct Elf64_Shdr - { - uint32_t sh_name; /* Section name, index in string tbl */ - uint32_t sh_type; /* Type of section */ - uint64_t sh_flags; /* Miscellaneous section attributes */ - uint64_t sh_addr; /* Section virtual addr at execution */ - uint64_t sh_offset; /* Section file offset */ - uint64_t sh_size; /* Size of section in bytes */ - uint32_t sh_link; /* Index of another section */ - uint32_t sh_info; /* Additional section information */ - uint64_t sh_addralign; /* Section alignment */ - uint64_t sh_entsize; /* Entry size if section holds table */ - }; - - /* Note header in a PT_NOTE section */ - struct Elf32_Nhdr - { - uint32_t n_namesz; /* Name size */ - uint32_t n_descsz; /* Content size */ - uint32_t n_type; /* Content type */ - }; - - /* Note header in a PT_NOTE section */ - struct Elf64_Nhdr - { - uint32_t n_namesz; /* Name size */ - uint32_t n_descsz; /* Content size */ - uint32_t n_type; /* Content type */ - }; -} \ No newline at end of file diff --git a/lib/libfnd/include/fnd/io.h b/lib/libfnd/include/fnd/io.h deleted file mode 100644 index 291a79b..0000000 --- a/lib/libfnd/include/fnd/io.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once -#include - -namespace fnd -{ - namespace io - { -#ifdef _WIN32 - const std::string kPathDivider = "\\"; -#else - const std::string kPathDivider = "/"; -#endif - - size_t getFileSize(const std::string& path); - void makeDirectory(const std::string& path); - void getEnvironVar(std::string& var, const std::string& key); - void appendToPath(std::string& base, const std::string& add); - } -} diff --git a/lib/libfnd/include/fnd/lz4.h b/lib/libfnd/include/fnd/lz4.h deleted file mode 100644 index 2d76857..0000000 --- a/lib/libfnd/include/fnd/lz4.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once -#include - -namespace fnd -{ - namespace lz4 - { - void compressData(const uint8_t* src, uint32_t src_len, uint8_t* dst, uint32_t dst_capacity, uint32_t& compressed_size); - void decompressData(const uint8_t* src, uint32_t src_len, uint8_t* dst, uint32_t dst_capacity, uint32_t& decompressed_size); - } -} \ No newline at end of file diff --git a/lib/libfnd/include/fnd/rsa.h b/lib/libfnd/include/fnd/rsa.h deleted file mode 100644 index fd05987..0000000 --- a/lib/libfnd/include/fnd/rsa.h +++ /dev/null @@ -1,124 +0,0 @@ -#pragma once -#include -#include -#include - -namespace fnd -{ - namespace rsa - { - const size_t kRsa1024Size = 0x80; - const size_t kRsa2048Size = 0x100; - const size_t kRsa4096Size = 0x200; - const size_t kRsaPublicExponentSize = 4; - - enum RsaType - { - RSA_1024, - RSA_2048, - RSA_4096, - }; - -#pragma pack (push, 1) - struct sRsa1024Key - { - uint8_t modulus[kRsa1024Size]; - uint8_t priv_exponent[kRsa1024Size]; - uint8_t public_exponent[kRsaPublicExponentSize]; - - void operator=(const sRsa1024Key& other) - { - memcpy(this->modulus, modulus, kRsa1024Size); - memcpy(this->priv_exponent, priv_exponent, kRsa1024Size); - memcpy(this->public_exponent, other.public_exponent, kRsaPublicExponentSize); - } - - bool operator==(const sRsa1024Key& other) const - { - return memcmp(this->modulus, other.modulus, kRsa1024Size) == 0 \ - && memcmp(this->priv_exponent, other.priv_exponent, kRsa1024Size) == 0 \ - && memcmp(this->public_exponent, other.public_exponent, kRsaPublicExponentSize) == 0; - } - - bool operator!=(const sRsa1024Key& other) const - { - return !operator==(other); - } - }; - - struct sRsa2048Key - { - uint8_t modulus[kRsa2048Size]; - uint8_t priv_exponent[kRsa2048Size]; - uint8_t public_exponent[kRsaPublicExponentSize]; - - void operator=(const sRsa2048Key& other) - { - memcpy(this->modulus, other.modulus, kRsa2048Size); - memcpy(this->priv_exponent, other.priv_exponent, kRsa2048Size); - memcpy(this->public_exponent, other.public_exponent, kRsaPublicExponentSize); - } - - bool operator==(const sRsa2048Key& other) const - { - return memcmp(this->modulus, other.modulus, kRsa2048Size) == 0 && memcmp(this->priv_exponent, other.priv_exponent, kRsa2048Size) == 0 && memcmp(this->public_exponent, other.public_exponent, kRsaPublicExponentSize) == 0; - } - - bool operator!=(const sRsa2048Key& other) const - { - return !operator==(other); - } - }; - - struct sRsa4096Key - { - uint8_t modulus[kRsa4096Size]; - uint8_t priv_exponent[kRsa4096Size]; - uint8_t public_exponent[kRsaPublicExponentSize]; - - void operator=(const sRsa4096Key& other) - { - memcpy(this->modulus, other.modulus, kRsa4096Size); - memcpy(this->priv_exponent, other.priv_exponent, kRsa4096Size); - memcpy(this->public_exponent, other.public_exponent, kRsaPublicExponentSize); - } - - bool operator==(const sRsa4096Key& other) const - { - return memcmp(this->modulus, other.modulus, kRsa4096Size) == 0 && memcmp(this->priv_exponent, other.priv_exponent, kRsa4096Size) == 0 && memcmp(this->public_exponent, other.public_exponent, kRsaPublicExponentSize) == 0; - } - - bool operator!=(const sRsa4096Key& other) const - { - return !operator==(other); - } - }; -#pragma pack (pop) - - namespace pkcs - { - // rsa1024 - int rsaSign(const sRsa1024Key& key, sha::HashType hash_type, const uint8_t* hash, uint8_t signature[kRsa1024Size]); - int rsaVerify(const sRsa1024Key& key, sha::HashType hash_type, const uint8_t* hash, const uint8_t signature[kRsa1024Size]); - // rsa2048 - int rsaSign(const sRsa2048Key& key, sha::HashType hash_type, const uint8_t* hash, uint8_t signature[kRsa2048Size]); - int rsaVerify(const sRsa2048Key& key, sha::HashType hash_type, const uint8_t* hash, const uint8_t signature[kRsa2048Size]); - // rsa4096 - int rsaSign(const sRsa4096Key& key, sha::HashType hash_type, const uint8_t* hash, uint8_t signature[kRsa4096Size]); - int rsaVerify(const sRsa4096Key& key, sha::HashType hash_type, const uint8_t* hash, const uint8_t signature[kRsa4096Size]); - } - - namespace pss - { - // rsa1024 - //int rsaSign(const sRsa1024Key& key, sha::HashType hash_type, const uint8_t* hash, uint8_t signature[kRsa1024Size]); - //int rsaVerify(const sRsa1024Key& key, sha::HashType hash_type, const uint8_t* hash, const uint8_t signature[kRsa1024Size]); - // rsa2048 - int rsaSign(const sRsa2048Key& key, sha::HashType hash_type, const uint8_t* hash, uint8_t signature[kRsa2048Size]); - int rsaVerify(const sRsa2048Key& key, sha::HashType hash_type, const uint8_t* hash, const uint8_t signature[kRsa2048Size]); - // rsa4096 - //int rsaSign(const sRsa4096Key& key, sha::HashType hash_type, const uint8_t* hash, uint8_t signature[kRsa4096Size]); - //int rsaVerify(const sRsa4096Key& key, sha::HashType hash_type, const uint8_t* hash, const uint8_t signature[kRsa4096Size]); - } - } -} diff --git a/lib/libfnd/include/fnd/sha.h b/lib/libfnd/include/fnd/sha.h deleted file mode 100644 index 55d042d..0000000 --- a/lib/libfnd/include/fnd/sha.h +++ /dev/null @@ -1,89 +0,0 @@ -#pragma once -#include -#include - -namespace fnd -{ - namespace sha - { - const size_t kSha1HashLen = 20; - const size_t kSha256HashLen = 32; - - enum HashType - { - HASH_SHA1, - HASH_SHA256 - }; - -#pragma pack (push, 1) - struct sSha1Hash - { - uint8_t bytes[kSha1HashLen]; - - void set(const uint8_t hash[kSha1HashLen]) - { - memcpy(this->bytes, hash, kSha1HashLen); - } - - bool compare(const uint8_t hash[kSha1HashLen]) const - { - return memcmp(this->bytes, hash, kSha1HashLen) == 0; - } - - bool compare(const sSha1Hash& other) const - { - return memcmp(this->bytes, other.bytes, kSha1HashLen) == 0; - } - - void operator=(const sSha1Hash& other) - { - set(other.bytes); - } - bool operator==(const sSha1Hash& other) const - { - return compare(other); - } - bool operator!=(const sSha1Hash& other) const - { - return !compare(other); - } - }; - - struct sSha256Hash - { - uint8_t bytes[kSha256HashLen]; - - void set(const uint8_t hash[kSha256HashLen]) - { - memcpy(this->bytes, hash, kSha256HashLen); - } - - bool compare(const uint8_t hash[kSha256HashLen]) const - { - return memcmp(this->bytes, hash, kSha256HashLen) == 0; - } - - bool compare(const sSha256Hash& other) const - { - return memcmp(this->bytes, other.bytes, kSha256HashLen) == 0; - } - - void operator=(const sSha256Hash& other) - { - set(other.bytes); - } - bool operator==(const sSha256Hash& other) const - { - return compare(other); - } - bool operator!=(const sSha256Hash& other) const - { - return !compare(other); - } - }; -#pragma pack (pop) - - void Sha1(const uint8_t* in, uint64_t size, uint8_t hash[kSha1HashLen]); - void Sha256(const uint8_t* in, uint64_t size, uint8_t hash[kSha256HashLen]); - } -} \ No newline at end of file diff --git a/lib/libfnd/include/fnd/types.h b/lib/libfnd/include/fnd/types.h deleted file mode 100644 index 81cac74..0000000 --- a/lib/libfnd/include/fnd/types.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once -#include -#include -#include -#include - -typedef uint8_t byte_t; - -#define _MIN(x,y) ((x) <= (y)? (x) : (y)) -#define _MAX(x,y) ((x) >= (y)? (x) : (y)) - -static inline uint64_t align(uint64_t size, uint64_t align) -{ - return (size % align) == 0? size : (size - (size % align) + align); -} - diff --git a/lib/libfnd/libfnd.vcxproj b/lib/libfnd/libfnd.vcxproj deleted file mode 100644 index 927922b..0000000 --- a/lib/libfnd/libfnd.vcxproj +++ /dev/null @@ -1,170 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 15.0 - {4D27EDB9-5110-44FE-8CE2-D46C5AD3C55B} - 10.0.16299.0 - - - - StaticLibrary - true - v141 - MultiByte - - - StaticLibrary - false - v141 - true - MultiByte - - - StaticLibrary - true - v141 - MultiByte - - - StaticLibrary - false - v141 - true - MultiByte - - - - - - - - - - - - - - - - - - - - - - - Level3 - Disabled - true - ..\libfnd\include;..\libpolarssl\include;..\liblz4\include; - _MBCS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - - - Level3 - Disabled - true - ..\libfnd\include;..\libpolarssl\include;..\liblz4\include; - _MBCS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - - - Level3 - MaxSpeed - true - true - true - ..\libfnd\include;..\libpolarssl\include;..\liblz4\include; - _MBCS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - true - true - - - - - Level3 - MaxSpeed - true - true - true - ..\libfnd\include;..\libpolarssl\include;..\liblz4\include; - _MBCS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - true - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/lib/libfnd/libfnd.vcxproj.filters b/lib/libfnd/libfnd.vcxproj.filters deleted file mode 100644 index 95e68e0..0000000 --- a/lib/libfnd/libfnd.vcxproj.filters +++ /dev/null @@ -1,144 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - \ No newline at end of file diff --git a/lib/libfnd/libfnd.vcxproj.user b/lib/libfnd/libfnd.vcxproj.user deleted file mode 100644 index be25078..0000000 --- a/lib/libfnd/libfnd.vcxproj.user +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/lib/libfnd/makefile b/lib/libfnd/makefile deleted file mode 100644 index 0ec7dcf..0000000 --- a/lib/libfnd/makefile +++ /dev/null @@ -1,46 +0,0 @@ -# Sources -SRC_DIR = source -OBJS = $(foreach dir,$(SRC_DIR),$(subst .cpp,.o,$(wildcard $(dir)/*.cpp))) $(foreach dir,$(SRC_DIR),$(subst .c,.o,$(wildcard $(dir)/*.c))) - -# External dependencies -DEPENDS = polarssl lz4 -LIB_DIR = .. -INCS = -I"include" $(foreach dep,$(DEPENDS), -I"$(LIB_DIR)/lib$(dep)/include") - -# Compiler Settings -CXXFLAGS = -std=c++11 $(INCS) -D__STDC_FORMAT_MACROS -Wall -Wno-unused-value -CFLAGS = -std=c11 $(INCS) -Wall -Wno-unused-value -ARFLAGS = cr -o -ifeq ($(OS),Windows_NT) - # Windows Only Flags/Libs - CC = x86_64-w64-mingw32-gcc - CXX = x86_64-w64-mingw32-g++ - CFLAGS += -Wno-unused-but-set-variable - CXXFLAGS += -Wno-unused-but-set-variable -else - UNAME = $(shell uname -s) - ifeq ($(UNAME), Darwin) - # MacOS Only Flags/Libs - CFLAGS += -Wno-unused-private-field - CXXFLAGS += -Wno-unused-private-field - ARFLAGS = rc - else - # *nix Only Flags/Libs - CFLAGS += -Wno-unused-but-set-variable - CXXFLAGS += -Wno-unused-but-set-variable - endif - -endif - -# Output -OUTPUT = $(shell basename "$(CURDIR)").a - -main: build - -rebuild: clean build - -build: $(OBJS) - ar $(ARFLAGS) $(OUTPUT) $(OBJS) - -clean: - rm -rf $(OUTPUT) $(OBJS) \ No newline at end of file diff --git a/lib/libfnd/source/AesCtrWrappedIFile.cpp b/lib/libfnd/source/AesCtrWrappedIFile.cpp deleted file mode 100644 index ce8daf3..0000000 --- a/lib/libfnd/source/AesCtrWrappedIFile.cpp +++ /dev/null @@ -1,80 +0,0 @@ -#include - -fnd::AesCtrWrappedIFile::AesCtrWrappedIFile(const fnd::SharedPtr& file, const fnd::aes::sAes128Key& key, const fnd::aes::sAesIvCtr& ctr) : - mFile(file), - mKey(key), - mBaseCtr(ctr), - mFileOffset(0) -{ - mCache.alloc(kCacheSizeAllocSize); -} - -size_t fnd::AesCtrWrappedIFile::size() -{ - return (*mFile)->size(); -} - -void fnd::AesCtrWrappedIFile::seek(size_t offset) -{ - mFileOffset = offset; -} - -void fnd::AesCtrWrappedIFile::read(byte_t* out, size_t len) -{ - size_t read_len; - size_t read_pos; - - size_t cache_reads = (len / kCacheSize) + ((len % kCacheSize) != 0); - - for (size_t i = 0; i < cache_reads; i++) - { - read_len = _MIN(len - (i * kCacheSize), kCacheSize); - read_pos = ((mFileOffset >> 4) << 4) + (i * kCacheSize); - - (*mFile)->seek(read_pos); - (*mFile)->read(mCache.data(), kCacheSizeAllocSize); - - fnd::aes::AesIncrementCounter(mBaseCtr.iv, read_pos>>4, mCurrentCtr.iv); - fnd::aes::AesCtr(mCache.data(), kCacheSizeAllocSize, mKey.key, mCurrentCtr.iv, mCache.data()); - - memcpy(out + (i * kCacheSize), mCache.data() + (mFileOffset & 0xf), read_len); - } - - seek(mFileOffset + len); -} - -void fnd::AesCtrWrappedIFile::read(byte_t* out, size_t offset, size_t len) -{ - seek(offset); - read(out, len); -} - -void fnd::AesCtrWrappedIFile::write(const byte_t* in, size_t len) -{ - size_t write_len; - size_t write_pos; - - size_t cache_writes = (len / kCacheSize) + ((len % kCacheSize) != 0); - - for (size_t i = 0; i < cache_writes; i++) - { - write_len = _MIN(len - (i * kCacheSize), kCacheSize); - write_pos = ((mFileOffset >> 4) << 4) + (i * kCacheSize); - - memcpy(mCache.data() + (mFileOffset & 0xf), in + (i * kCacheSize), write_len); - - fnd::aes::AesIncrementCounter(mBaseCtr.iv, write_pos>>4, mCurrentCtr.iv); - fnd::aes::AesCtr(mCache.data(), kCacheSizeAllocSize, mKey.key, mCurrentCtr.iv, mCache.data()); - - (*mFile)->seek(write_pos); - (*mFile)->write(mCache.data(), kCacheSizeAllocSize); - } - - seek(mFileOffset + len); -} - -void fnd::AesCtrWrappedIFile::write(const byte_t* in, size_t offset, size_t len) -{ - seek(offset); - write(in, len); -} \ No newline at end of file diff --git a/lib/libfnd/source/Exception.cpp b/lib/libfnd/source/Exception.cpp deleted file mode 100644 index e123cc4..0000000 --- a/lib/libfnd/source/Exception.cpp +++ /dev/null @@ -1,48 +0,0 @@ -#include - -using namespace fnd; - -Exception::Exception() noexcept : - what_(""), - module_(""), - error_("") -{ - -} - -Exception::Exception(const std::string & what) noexcept : - what_(what), - module_(""), - error_(what) -{ -} - -Exception::Exception(const std::string & module, const std::string & what) noexcept : - what_(""), - module_(module), - error_(what) -{ - if (module_.length() > 0) - { - what_ = "[" + module_ + " ERROR] " + error_; - } - else - { - what_ = error_; - } -} - -const char* Exception::what() const noexcept -{ - return what_.c_str(); -} - -const char* Exception::module() const noexcept -{ - return module_.c_str(); -} - -const char * fnd::Exception::error() const noexcept -{ - return error_.c_str(); -} diff --git a/lib/libfnd/source/LayeredIntegrityMetadata.cpp b/lib/libfnd/source/LayeredIntegrityMetadata.cpp deleted file mode 100644 index 95c06da..0000000 --- a/lib/libfnd/source/LayeredIntegrityMetadata.cpp +++ /dev/null @@ -1,71 +0,0 @@ -#include - -fnd::LayeredIntegrityMetadata::LayeredIntegrityMetadata() : - mLayerInfo(), - mDataLayer(), - mMasterHashList(), - mDoAlignHashToBlock(false) -{ - -} - -void fnd::LayeredIntegrityMetadata::operator=(const LayeredIntegrityMetadata& other) -{ - mLayerInfo = other.mLayerInfo; - mDataLayer = other.mDataLayer; - mMasterHashList = other.mMasterHashList; - mDoAlignHashToBlock = other.mDoAlignHashToBlock; -} - -bool fnd::LayeredIntegrityMetadata::operator==(const LayeredIntegrityMetadata& other) const -{ - return (mLayerInfo == other.mLayerInfo) \ - && (mDataLayer == other.mDataLayer) \ - && (mMasterHashList == other.mMasterHashList) \ - && (mDoAlignHashToBlock == other.mDoAlignHashToBlock); -} - -bool fnd::LayeredIntegrityMetadata::operator!=(const LayeredIntegrityMetadata& other) const -{ - return !(*this == other); -} - -const fnd::List& fnd::LayeredIntegrityMetadata::getHashLayerInfo() const -{ - return mLayerInfo; -} - -void fnd::LayeredIntegrityMetadata::setHashLayerInfo(const fnd::List& layer_info) -{ - mLayerInfo = layer_info; -} - -const fnd::LayeredIntegrityMetadata::sLayer& fnd::LayeredIntegrityMetadata::getDataLayer() const -{ - return mDataLayer; -} - -void fnd::LayeredIntegrityMetadata::setDataLayerInfo(const sLayer& data_info) -{ - mDataLayer = data_info; -} - -const fnd::List& fnd::LayeredIntegrityMetadata::getMasterHashList() const -{ - return mMasterHashList; -} - -void fnd::LayeredIntegrityMetadata::setMasterHashList(const fnd::List& master_hash_list) -{ - mMasterHashList = master_hash_list; -} - -bool fnd::LayeredIntegrityMetadata::getAlignHashToBlock() const -{ - return mDoAlignHashToBlock; -} - -void fnd::LayeredIntegrityMetadata::setAlignHashToBlock(bool doAlign) -{ - mDoAlignHashToBlock = doAlign; -} \ No newline at end of file diff --git a/lib/libfnd/source/LayeredIntegrityWrappedIFile.cpp b/lib/libfnd/source/LayeredIntegrityWrappedIFile.cpp deleted file mode 100644 index 38b5602..0000000 --- a/lib/libfnd/source/LayeredIntegrityWrappedIFile.cpp +++ /dev/null @@ -1,191 +0,0 @@ -#include -#include - -fnd::LayeredIntegrityWrappedIFile::LayeredIntegrityWrappedIFile(const fnd::SharedPtr& file, const fnd::LayeredIntegrityMetadata& hdr) : - mFile(file), - mData(nullptr), - mDataHashLayer(), - mAlignHashCalcToBlock(false) -{ - initialiseDataLayer(hdr); -} - -size_t fnd::LayeredIntegrityWrappedIFile::size() -{ - return (*mData)->size(); -} - -void fnd::LayeredIntegrityWrappedIFile::seek(size_t offset) -{ - mDataOffset = offset; -} - -void fnd::LayeredIntegrityWrappedIFile::read(byte_t* out, size_t len) -{ - struct sBlockPosition - { - size_t index; - size_t pos; - } start_blk, end_blk; - - start_blk.index = getOffsetBlock(mDataOffset); - start_blk.pos = getOffsetInBlock(mDataOffset); - - end_blk.index = getOffsetBlock(mDataOffset + len); - end_blk.pos = getOffsetInBlock(mDataOffset + len); - if (end_blk.pos == 0 && len != 0) - { - end_blk.index -= 1; - end_blk.pos = mDataBlockSize; - } - - size_t total_blk_num = (end_blk.index - start_blk.index) + 1; - - size_t read_blk_num = 0; - size_t cache_export_start_pos, cache_export_end_pos, cache_export_size; - size_t export_pos = 0; - for (size_t i = 0; i < total_blk_num; i += read_blk_num, export_pos += cache_export_size) - { - read_blk_num = _MIN(mCacheBlockNum, (total_blk_num - i)); - readData(start_blk.index + i, read_blk_num); - - // if this is the first read, adjust offset - if (i == 0) - cache_export_start_pos = start_blk.pos; - else - cache_export_start_pos = 0; - - // if this is the last block, adjust end offset - if ((i + read_blk_num) == total_blk_num) - cache_export_end_pos = ((read_blk_num - 1) * mDataBlockSize) + end_blk.pos; - else - cache_export_end_pos = read_blk_num * mDataBlockSize; - - // determine cache export size - cache_export_size = cache_export_end_pos - cache_export_start_pos; - - memcpy(out + export_pos, mCache.data() + cache_export_start_pos, cache_export_size); - } - - // update offset - seek(mDataOffset + len); -} - -void fnd::LayeredIntegrityWrappedIFile::read(byte_t* out, size_t offset, size_t len) -{ - seek(offset); - read(out, len); -} - -void fnd::LayeredIntegrityWrappedIFile::write(const byte_t* out, size_t len) -{ - throw fnd::Exception(kModuleName, "write() not supported"); -} - -void fnd::LayeredIntegrityWrappedIFile::write(const byte_t* out, size_t offset, size_t len) -{ - throw fnd::Exception(kModuleName, "write() not supported"); -} - -void fnd::LayeredIntegrityWrappedIFile::initialiseDataLayer(const fnd::LayeredIntegrityMetadata& hdr) -{ - fnd::sha::sSha256Hash hash; - fnd::Vec cur, prev; - - mAlignHashCalcToBlock = hdr.getAlignHashToBlock(); - - // copy master hash into prev - prev.alloc(sizeof(fnd::sha::sSha256Hash) * hdr.getMasterHashList().size()); - for (size_t i = 0; i < hdr.getMasterHashList().size(); i++) - { - ((fnd::sha::sSha256Hash*)prev.data())[i] = hdr.getMasterHashList()[i]; - } - - // check each hash layer - for (size_t i = 0; i < hdr.getHashLayerInfo().size(); i++) - { - // get block size - const fnd::LayeredIntegrityMetadata::sLayer& layer = hdr.getHashLayerInfo()[i]; - - // allocate layer - cur.alloc(align(layer.size, layer.block_size)); - - // read layer - (*mFile)->read(cur.data(), layer.offset, layer.size); - - // validate blocks - size_t validate_size; - for (size_t j = 0; j < cur.size() / layer.block_size; j++) - { - validate_size = mAlignHashCalcToBlock? layer.block_size : _MIN(layer.size - (j * layer.block_size), layer.block_size); - fnd::sha::Sha256(cur.data() + (j * layer.block_size), validate_size, hash.bytes); - if (hash.compare(prev.data() + j * sizeof(fnd::sha::sSha256Hash)) == false) - { - mErrorSs << "Hash tree layer verification failed (layer: " << i << ", block: " << j << ")"; - throw fnd::Exception(kModuleName, mErrorSs.str()); - } - } - - // set prev to cur - prev = cur; - } - - // save last layer as hash table for data layer - fnd::sha::sSha256Hash* hash_list = (fnd::sha::sSha256Hash*)prev.data(); - for (size_t i = 0; i < prev.size() / sizeof(fnd::sha::sSha256Hash); i++) - { - mDataHashLayer.addElement(hash_list[i]); - } - - // generate reader for data layer - mData = new fnd::OffsetAdjustedIFile(mFile, hdr.getDataLayer().offset, hdr.getDataLayer().size); - mDataOffset = 0; - mDataBlockSize = hdr.getDataLayer().block_size; - - // allocate cache - size_t cache_size = align(kDefaultCacheSize, mDataBlockSize); - mCacheBlockNum = cache_size / mDataBlockSize; - mCache.alloc(cache_size); -} - -void fnd::LayeredIntegrityWrappedIFile::readData(size_t block_offset, size_t block_num) -{ - fnd::sha::sSha256Hash hash; - - // determine read size - size_t read_len = 0; - if ((block_offset + block_num) == getBlockNum((*mData)->size())) - { - read_len = (block_num-1) * mDataBlockSize + getRemanderBlockReadSize((*mData)->size()); - memset(mCache.data(), 0, block_num * mDataBlockSize); - } - else if ((block_offset + block_num) < getBlockNum((*mData)->size())) - { - read_len = block_num * mDataBlockSize; - } - else - { - throw fnd::Exception(kModuleName, "Out of bounds file read"); - } - - // read - (*mData)->read(mCache.data(), block_offset * mDataBlockSize, read_len); - - if (block_num > mCacheBlockNum) - { - throw fnd::Exception(kModuleName, "Read excessive of cache size"); - } - - // validate blocks - size_t validate_size; - for (size_t i = 0; i < block_num; i++) - { - validate_size = mAlignHashCalcToBlock? mDataBlockSize : _MIN(read_len - (i * mDataBlockSize), mDataBlockSize); - fnd::sha::Sha256(mCache.data() + (i * mDataBlockSize), validate_size, hash.bytes); - if (hash != mDataHashLayer[block_offset + i]) - { - mErrorSs << "Hash tree layer verification failed (layer: data, block: " << (block_offset + i) << " ( " << i << "/" << block_num-1 << " ), offset: 0x" << std::hex << ((block_offset + i) * mDataBlockSize) << ", size: 0x" << std::hex << validate_size <<")"; - throw fnd::Exception(kModuleName, mErrorSs.str()); - } - } -} \ No newline at end of file diff --git a/lib/libfnd/source/OffsetAdjustedIFile.cpp b/lib/libfnd/source/OffsetAdjustedIFile.cpp deleted file mode 100644 index 4cebf16..0000000 --- a/lib/libfnd/source/OffsetAdjustedIFile.cpp +++ /dev/null @@ -1,47 +0,0 @@ -#include - -fnd::OffsetAdjustedIFile::OffsetAdjustedIFile(const fnd::SharedPtr& file, size_t offset, size_t size) : - mFile(file), - mBaseOffset(offset), - mCurrentOffset(0), - mSize(size) -{ -} - -size_t fnd::OffsetAdjustedIFile::size() -{ - return mSize; -} - -void fnd::OffsetAdjustedIFile::seek(size_t offset) -{ - mCurrentOffset = _MIN(offset, mSize); -} - -void fnd::OffsetAdjustedIFile::read(byte_t* out, size_t len) -{ - // assert proper position in file - (*mFile)->seek(mCurrentOffset + mBaseOffset); - (*mFile)->read(out, len); - seek(mCurrentOffset + len); -} - -void fnd::OffsetAdjustedIFile::read(byte_t* out, size_t offset, size_t len) -{ - seek(offset); - read(out, len); -} - -void fnd::OffsetAdjustedIFile::write(const byte_t* out, size_t len) -{ - // assert proper position in file - (*mFile)->seek(mCurrentOffset + mBaseOffset); - (*mFile)->write(out, len); - seek(mCurrentOffset + len); -} - -void fnd::OffsetAdjustedIFile::write(const byte_t* out, size_t offset, size_t len) -{ - seek(offset); - write(out, len); -} \ No newline at end of file diff --git a/lib/libfnd/source/ResourceFileReader.cpp b/lib/libfnd/source/ResourceFileReader.cpp deleted file mode 100644 index 956dde6..0000000 --- a/lib/libfnd/source/ResourceFileReader.cpp +++ /dev/null @@ -1,64 +0,0 @@ -#include -#include -#include -#include -#include - -fnd::ResourceFileReader::ResourceFileReader() -{ -} - -inline bool isNotPrintable(char chr) { return isprint(chr) == false; } - -void fnd::ResourceFileReader::processFile(const std::string& path) -{ - std::ifstream file; - file.open(path, std::ios::in); - if (file.is_open() == false) - { - throw fnd::Exception(kModuleName, "Failed to open file"); - } - - std::string line, key, value; - while (std::getline(file, line)) - { - // read up to comment line - if (line.find(";") != std::string::npos) - line = line.substr(0, line.find(";")); - - // change chars to lower string - std::transform(line.begin(), line.end(), line.begin(), ::tolower); - - // strip whitespace - line.erase(std::remove(line.begin(), line.end(), ' '), line.end()); - - // strip nonprintable - line.erase(std::remove_if(line.begin(), line.end(), isNotPrintable), line.end()); - - // skip lines that don't have '=' - if (line.find("=") == std::string::npos) - continue; - - key = line.substr(0,line.find("=")); - value = line.substr(line.find("=")+1); - - // skip if key or value is empty - if (key.empty() || value.empty()) - continue; - - //std::cout << "[" + key + "]=(" + value + ")" << std::endl; - - mResources[key] = value; - } - file.close(); -} - -bool fnd::ResourceFileReader::doesExist(const std::string& key) const -{ - return (mResources.find(key) != mResources.end()); -} - -const std::string& fnd::ResourceFileReader::operator[](const std::string& key) -{ - return mResources[key]; -} \ No newline at end of file diff --git a/lib/libfnd/source/SimpleFile.cpp b/lib/libfnd/source/SimpleFile.cpp deleted file mode 100644 index c232869..0000000 --- a/lib/libfnd/source/SimpleFile.cpp +++ /dev/null @@ -1,331 +0,0 @@ -#include -#include - -using namespace fnd; - -SimpleFile::SimpleFile() : - mOpen(false), - mMode(Read), -#ifdef _WIN32 - mFileHandle() -#else - mFp(nullptr) -#endif -{ -} - -SimpleFile::SimpleFile(const std::string& path, OpenMode mode) : - SimpleFile() -{ - open(path, mode); -} - -SimpleFile::~SimpleFile() -{ - close(); -} - -void SimpleFile::open(const std::string& path, OpenMode mode) -{ -#ifdef _WIN32 - // convert string to unicode - std::u16string unicodePath = fnd::StringConv::ConvertChar8ToChar16(path); - - // save mode - mMode = mode; - - // open file - mFileHandle = CreateFileW((LPCWSTR)unicodePath.c_str(), - getOpenModeFlag(mMode), - getShareModeFlag(mMode), - 0, - getCreationModeFlag(mMode), - FILE_ATTRIBUTE_NORMAL, - NULL); - // check file handle - if (mFileHandle == INVALID_HANDLE_VALUE) - { - throw fnd::Exception(kModuleName, "Failed to open file."); - } - - -#else - //close(); - mMode = mode; - //printf("fopen(%s,%s);\n", path.c_str(), getOpenModeStr(mMode)); - mFp = fopen(path.c_str(), getOpenModeStr(mMode)); - if (mFp == nullptr) - throw fnd::Exception(kModuleName, "Failed to open file."); - mOpen = true; -#endif - - seek(0); -} - -bool SimpleFile::isOpen() const -{ - return mOpen == true; -} - -void SimpleFile::close() -{ - if (isOpen()) - { -#ifdef _WIN32 - CloseHandle(mFileHandle); -#else - fclose(mFp); - mFp = nullptr; -#endif - } - mOpen = false; -} - -size_t SimpleFile::size() -{ - size_t fsize = 0; -#ifdef _WIN32 - if (mMode != Create) - { - LARGE_INTEGER win_fsize; - if (GetFileSizeEx(mFileHandle, &win_fsize) == false) - { - throw fnd::Exception(kModuleName, "Failed to check filesize"); - } - - fsize = win_fsize.QuadPart; - } - else - { - fsize = 0; - } -#else - size_t cur_pos = pos(); - fseek(mFp, 0, SEEK_END); - fsize = pos(); - seek(cur_pos); -#endif - return fsize; -} - -void SimpleFile::seek(size_t offset) -{ -#ifdef _WIN32 - LARGE_INTEGER win_pos, out; - win_pos.QuadPart = offset; - if (SetFilePointerEx( - mFileHandle, - win_pos, - &out, - FILE_BEGIN - ) == false || out.QuadPart != win_pos.QuadPart) - { - throw fnd::Exception(kModuleName, "Failed to change file offset"); - } -#else - fseek(mFp, offset, SEEK_SET); -#endif -} - -size_t SimpleFile::pos() -{ -#ifdef _WIN32 - LARGE_INTEGER win_pos, out; - win_pos.QuadPart = 0; - if (SetFilePointerEx( - mFileHandle, - win_pos, - &out, - FILE_CURRENT - ) == false) - { - throw fnd::Exception(kModuleName, "Failed to check file offset"); - } - - return out.QuadPart; -#else - return ftell(mFp); -#endif -} - -void SimpleFile::read(byte_t* out, size_t len) -{ -#ifdef _WIN32 - LARGE_INTEGER win_len; - win_len.QuadPart = len; - - static const DWORD kDwordHalf = (MAXDWORD / (DWORD)2) + 1; // 0x80000000 - static const size_t kDwordFull = (size_t)kDwordHalf * (size_t)2; // 0x100000000 - - // if the size is greater than a DWORD, read it in parts, - for (LONG i = 0; i < win_len.HighPart; i++) - { - // since kDwordFull isn't a valid DWORD value, read in two parts - ReadFile( - mFileHandle, - out + i * kDwordFull, - kDwordHalf, - NULL, - NULL - ); - ReadFile( - mFileHandle, - out + i * kDwordFull + kDwordHalf, - kDwordHalf, - NULL, - NULL - ); - } - - // read remainding low part - if (win_len.LowPart > 0) - { - ReadFile( - mFileHandle, - out + win_len.HighPart * kDwordFull, - win_len.LowPart, - NULL, - NULL - ); - } -#else - fread(out, len, 1, mFp); -#endif -} - -void SimpleFile::read(byte_t* out, size_t offset, size_t len) -{ - seek(offset); - read(out, len); -} - -void SimpleFile::write(const byte_t* out, size_t len) -{ -#ifdef _WIN32 - LARGE_INTEGER win_len; - win_len.QuadPart = len; - - static const DWORD kDwordHalf = ((DWORD)MAXDWORD / (DWORD)2) + 1; // 0x80000000 - static const size_t kDwordFull = (size_t)kDwordHalf * (size_t)2; // 0x100000000 - - // if the size is greater than a DWORD, read it in parts, - for (LONG i = 0; i < win_len.HighPart; i++) - { - // since kDwordFull isn't a valid DWORD value, read in two parts - WriteFile( - mFileHandle, - out + i * kDwordFull, - kDwordHalf, - NULL, - NULL - ); - WriteFile( - mFileHandle, - out + i * kDwordFull + kDwordHalf, - kDwordHalf, - NULL, - NULL - ); - } - - // read remainding low part - if (win_len.LowPart > 0) - { - WriteFile( - mFileHandle, - out + win_len.HighPart * kDwordFull, - win_len.LowPart, - NULL, - NULL - ); - } -#else - fwrite(out, len, 1, mFp); -#endif -} - -void SimpleFile::write(const byte_t* out, size_t offset, size_t len) -{ - seek(offset); - write(out, len); -} - -#ifdef _WIN32 -DWORD SimpleFile::getOpenModeFlag(OpenMode mode) const -{ - DWORD flag = 0; - switch (mode) - { - case (Read): - flag = GENERIC_READ; - break; - case (Edit): - flag = GENERIC_READ | GENERIC_WRITE; - break; - case (Create): - flag = GENERIC_WRITE; - break; - default: - throw fnd::Exception(kModuleName, "Unknown open mode"); - } - return flag; -} -DWORD fnd::SimpleFile::getShareModeFlag(OpenMode mode) const -{ - DWORD flag = 0; - switch (mode) - { - case (Read): - flag = FILE_SHARE_READ; - break; - case (Edit): - flag = FILE_SHARE_READ; - break; - case (Create): - flag = 0; - break; - default: - throw fnd::Exception(kModuleName, "Unknown open mode"); - } - return flag; -} -DWORD fnd::SimpleFile::getCreationModeFlag(OpenMode mode) const -{ - DWORD flag = 0; - switch (mode) - { - case (Read): - flag = OPEN_EXISTING; - break; - case (Edit): - flag = OPEN_EXISTING; - break; - case (Create): - flag = CREATE_ALWAYS; - break; - default: - throw fnd::Exception(kModuleName, "Unknown open mode"); - } - return flag; -} -#else -const char* SimpleFile::getOpenModeStr(OpenMode mode) -{ - const char* str = ""; - switch(mode) - { - case (Read): - str = "rb"; - break; - case (Edit): - str = "rb+"; - break; - case (Create): - str = "wb"; - break; - default: - throw fnd::Exception(kModuleName, "Unknown open mode"); - } - return str; -} -#endif \ No newline at end of file diff --git a/lib/libfnd/source/SimpleTextOutput.cpp b/lib/libfnd/source/SimpleTextOutput.cpp deleted file mode 100644 index 1ee71ce..0000000 --- a/lib/libfnd/source/SimpleTextOutput.cpp +++ /dev/null @@ -1,117 +0,0 @@ -#include -#include -#include -#include -#include - -void fnd::SimpleTextOutput::hxdStyleDump(const byte_t* data, size_t len, size_t row_len, size_t byte_grouping_size) -{ - // iterate over blocks - for (size_t i = 0; i < (len / row_len); i++) - { - printf("%08" PRIx64 " | ", (uint64_t)(i * row_len)); - // for block i print each byte - for (size_t j = 0; j < row_len; j++) - { - printf("%02X", data[(i * row_len) + j]); - if (((j+1) % byte_grouping_size) == 0) - { - putchar(' '); - } - } - printf(" "); - for (size_t j = 0; j < row_len; j++) - { - printf("%c", iscntrl(data[(i * row_len) + j]) ? '.' : data[(i * row_len) + j]); - } - printf("\n"); - } - if ((len % row_len) > 0) - { - size_t i = (len / row_len); - printf("%08" PRIx64 " | ", (uint64_t)(i * row_len)); - // for block i print each byte - for (size_t j = 0; j < row_len; j++) - { - if (j < (len % row_len)) - printf("%02X", data[(i * row_len) + j]); - else - printf(" "); - if (((j+1) % byte_grouping_size) == 0) - { - putchar(' '); - } - } - printf(" "); - for (size_t j = 0; j < row_len; j++) - { - if (j < (len % row_len)) - printf("%c", iscntrl(data[(i * row_len) + j]) ? '.' : data[(i * row_len) + j]); - else - printf(" "); - } - printf("\n"); - } -} - -void fnd::SimpleTextOutput::hxdStyleDump(const byte_t* data, size_t len) -{ - hxdStyleDump(data, len, kDefaultRowLen, kDefaultByteGroupingSize); -} - -void fnd::SimpleTextOutput::hexDump(const byte_t* data, size_t len, size_t row_len, size_t indent_len) -{ - for (size_t i = 0; i < len; i += row_len) - { - for (size_t j = 0; j < indent_len; j++) - std::cout << " "; - std::cout << arrayToString(data+i, _MIN(len-i, row_len), true, "") << std::endl; - } -} - -void fnd::SimpleTextOutput::hexDump(const byte_t* data, size_t len) -{ - std::cout << arrayToString(data, len, true, "") << std::endl; -} - -std::string fnd::SimpleTextOutput::arrayToString(const byte_t* data, size_t len, bool upper_case, const std::string& separator) -{ - std::stringstream ss; - - if (upper_case) - ss << std::uppercase; - for (size_t i = 0; i < len; i++) - { - ss << std::hex << std::setw(2) << std::setfill('0') << (uint32_t)data[i]; - if (i+1 < len) - ss << separator; - } - return ss.str(); -} - -inline byte_t charToByte(char chr) -{ - if (chr >= 'a' && chr <= 'f') - return (chr - 'a') + 0xa; - else if (chr >= 'A' && chr <= 'F') - return (chr - 'A') + 0xa; - else if (chr >= '0' && chr <= '9') - return chr - '0'; - return 0; -} - -void fnd::SimpleTextOutput::stringToArray(const std::string& str, fnd::Vec& array) -{ - size_t size = str.size(); - if ((size % 2)) - { - return; - } - - array.alloc(size/2); - - for (size_t i = 0; i < array.size(); i++) - { - array[i] = (charToByte(str[i * 2]) << 4) | charToByte(str[(i * 2) + 1]); - } -} \ No newline at end of file diff --git a/lib/libfnd/source/StringConv.cpp b/lib/libfnd/source/StringConv.cpp deleted file mode 100644 index 9d23ab0..0000000 --- a/lib/libfnd/source/StringConv.cpp +++ /dev/null @@ -1,147 +0,0 @@ -#include -#include -#include - -using namespace fnd; - -std::u16string StringConv::ConvertChar8ToChar16(const std::string & in) -{ - std::u32string unicode; - size_t done = 0; - for (size_t i = 0; i < in.length(); i += done) - { - // get number of leading high bits in first byte - uint8_t prefix = get_utf8_prefix(in[i]); - if (prefix == 1 || prefix > 4) // 1 is reserved for trailer bytes - { - throw std::logic_error("not a UTF-8 string"); - } - - // if there are no prefix bits, this is ASCII - if (prefix == 0) - { - unicode.push_back(in[i]); - done = 1; - } - // otherwise this is a multibyte character - else - { - // there must be enough characters - if ((i + prefix) > in.length()) - { - throw std::logic_error("not a UTF-8 string"); - } - - char32_t uni = get_utf8_data(prefix, in[i]); - - for (uint8_t j = 1; j < prefix; j++) - { - if (utf8_has_prefix(1, in[i + j]) == false) - { - throw std::logic_error("not a UTF-8 string"); - } - - uni <<= 6; - uni |= get_utf8_data(1, in[i + j]); - } - - if (uni >= kUtf16HighSurrogateStart && uni <= kUtf16LowSurrogateEnd) - { - throw std::logic_error("not a UTF-8 string"); - } - - if (uni > kUtf16EncodeMax) - { - throw std::logic_error("not a UTF-8 string"); - } - - unicode.push_back(uni); - done = prefix; - } - - } - - std::u16string utf16; - for (size_t i = 0; i < unicode.size(); i++) - { - char32_t uni = unicode[i]; - if (uni < kUtf16NonNativeStart) - { - utf16.push_back((char16_t)uni); - } - else - { - uni -= kUtf16NonNativeStart; - utf16.push_back(((uni >> kUtf16SurrogateBits) & kUtf16SurrogateMask) + kUtf16HighSurrogateStart); - utf16.push_back((uni & kUtf16SurrogateMask) + kUtf16LowSurrogateStart); - } - } - return utf16; -} - -std::string StringConv::ConvertChar16ToChar8(const std::u16string & in) -{ - std::u32string unicode; - size_t done = 0; - for (size_t i = 0; i < in.length(); i+=done) - { - // this isn't a utf16 reserved character, so just add to unicode string - if (in[i] < kUtf16HighSurrogateStart || in[i] > kUtf16LowSurrogateEnd) - { - unicode.push_back(in[i]); - done = 1; - } - // otherwise we need to decode it - else - { - // check that the high surrogate char exists first - if (in[i] < kUtf16HighSurrogateStart || in[i] > kUtf16HighSurrogateEnd) - { - throw std::logic_error("not a UTF-16 string"); - } - // check that the low surrogate char exists next - if (i >= in.length() - 1 || in[i + 1] < kUtf16LowSurrogateStart || in[i + 1] > kUtf16LowSurrogateEnd) - { - throw std::logic_error("not a UTF-16 string"); - } - - char32_t uni = ((in[i] & kUtf16SurrogateMask) << kUtf16SurrogateBits) | (in[i + 1] & kUtf16SurrogateMask) | 0x10000; - - unicode.push_back(uni); - done = 2; - } - } - - std::string utf8; - for (size_t i = 0; i < unicode.length(); i++) - { - if (unicode[i] <= kUtf8AsciiEnd) - { - utf8.push_back((char)unicode[i]); - } - else if (unicode[i] <= kUtf82ByteEnd) - { - utf8.push_back(make_utf8(2, (uint8_t)(unicode[i] >> 6))); - utf8.push_back(make_utf8(1, (uint8_t)(unicode[i] >> 0))); - } - else if (unicode[i] <= kUtf83ByteEnd) - { - utf8.push_back(make_utf8(3, (uint8_t)(unicode[i] >> 12))); - utf8.push_back(make_utf8(1, (uint8_t)(unicode[i] >> 6))); - utf8.push_back(make_utf8(1, (uint8_t)(unicode[i] >> 0))); - } - else if (unicode[i] <= kUtf84ByteEnd) - { - utf8.push_back(make_utf8(4, (uint8_t)(unicode[i] >> 18))); - utf8.push_back(make_utf8(1, (uint8_t)(unicode[i] >> 12))); - utf8.push_back(make_utf8(1, (uint8_t)(unicode[i] >> 6))); - utf8.push_back(make_utf8(1, (uint8_t)(unicode[i] >> 0))); - } - else - { - throw std::logic_error("not a UTF-16 string"); - } - } - - return utf8; -} diff --git a/lib/libfnd/source/aes_wrapper.cpp b/lib/libfnd/source/aes_wrapper.cpp deleted file mode 100644 index 0013dce..0000000 --- a/lib/libfnd/source/aes_wrapper.cpp +++ /dev/null @@ -1,159 +0,0 @@ -#include -#include - -using namespace fnd::aes; - -inline void XorBlock(const uint8_t a[kAesBlockSize], const uint8_t b[kAesBlockSize], uint8_t out[kAesBlockSize]) -{ - for (uint8_t i = 0; i < 16; i++) - { - out[i] = a[i] ^ b[i]; - } -} - -inline uint32_t getbe32(const uint8_t* data) { return data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3]; } -inline void putbe32(uint8_t* data, uint32_t val) { data[0] = val >> 24; data[1] = val >> 16; data[2] = val >> 8; data[3] = val; } - - - -void fnd::aes::AesEcbDecrypt(const uint8_t * in, uint64_t size, const uint8_t key[kAes128KeySize], uint8_t * out) -{ - aes_context ctx; - aes_setkey_dec(&ctx, key, 128); - - for (size_t i = 0; i < size / kAesBlockSize; i++) - { - aes_crypt_ecb(&ctx, AES_DECRYPT, in + kAesBlockSize * i, out + kAesBlockSize * i); - } - -} - -void fnd::aes::AesEcbEncrypt(const uint8_t * in, uint64_t size, const uint8_t key[kAes128KeySize], uint8_t * out) -{ - aes_context ctx; - aes_setkey_enc(&ctx, key, 128); - for (size_t i = 0; i < size / kAesBlockSize; i++) - { - aes_crypt_ecb(&ctx, AES_ENCRYPT, in + kAesBlockSize * i, out + kAesBlockSize * i); - } -} - -void fnd::aes::AesCtr(const uint8_t* in, uint64_t size, const uint8_t key[kAes128KeySize], uint8_t ctr[kAesBlockSize], uint8_t* out) -{ - aes_context ctx; - uint8_t block[kAesBlockSize] = { 0 }; - size_t counterOffset = 0; - - aes_setkey_enc(&ctx, key, 128); - aes_crypt_ctr(&ctx, size, &counterOffset, ctr, block, in, out); -} - -void fnd::aes::AesIncrementCounter(const uint8_t in[kAesBlockSize], size_t block_num, uint8_t out[kAesBlockSize]) -{ - memcpy(out, in, kAesBlockSize); - - uint32_t ctr[4]; - ctr[3] = getbe32(&in[0]); - ctr[2] = getbe32(&in[4]); - ctr[1] = getbe32(&in[8]); - ctr[0] = getbe32(&in[12]); - - for (uint32_t i = 0; i < 4; i++) { - uint64_t total = ctr[i] + block_num; - // if there wasn't a wrap around, add the two together and exit - if (total <= 0xffffffff) { - ctr[i] += (uint32_t)block_num; - break; - } - - // add the difference - ctr[i] = (uint32_t)(total - 0x100000000); - // carry to next word - block_num = (uint32_t)(total >> 32); - } - - putbe32(&out[0], ctr[3]); - putbe32(&out[4], ctr[2]); - putbe32(&out[8], ctr[1]); - putbe32(&out[12], ctr[0]); -} - -void fnd::aes::AesCbcDecrypt(const uint8_t* in, uint64_t size, const uint8_t key[kAes128KeySize], uint8_t iv[kAesBlockSize], uint8_t* out) -{ - aes_context ctx; - aes_setkey_dec(&ctx, key, 128); - aes_crypt_cbc(&ctx, AES_DECRYPT, size, iv, in, out); -} - -void fnd::aes::AesCbcEncrypt(const uint8_t* in, uint64_t size, const uint8_t key[kAes128KeySize], uint8_t iv[kAesBlockSize], uint8_t* out) -{ - aes_context ctx; - aes_setkey_enc(&ctx, key, 128); - aes_crypt_cbc(&ctx, AES_ENCRYPT, size, iv, in, out); -} - -void fnd::aes::AesXtsDecryptSector(const uint8_t * in, uint64_t sector_size, const uint8_t key1[kAes128KeySize], const uint8_t key2[kAes128KeySize], uint8_t tweak[kAesBlockSize], uint8_t * out) -{ - aes_context data_ctx; - aes_setkey_dec(&data_ctx, key1, 128); - - uint8_t enc_tweak[kAesBlockSize]; - AesEcbEncrypt(tweak, kAesBlockSize, key2, enc_tweak); - - size_t block_num = sector_size / kAesBlockSize; - uint8_t block[kAesBlockSize]; - for (size_t i = 0; i < block_num; i++) - { - XorBlock(in + (i * kAesBlockSize), enc_tweak, block); - aes_crypt_ecb(&data_ctx, AES_DECRYPT, block, block); - XorBlock(block, enc_tweak, out + i * kAesBlockSize); - GaloisFunc(enc_tweak); - } - - if (sector_size % kAesBlockSize) - { - // TODO: implement ciphertext stealing - } -} - -void fnd::aes::AesXtsEncryptSector(const uint8_t * in, uint64_t sector_size, const uint8_t key1[kAes128KeySize], const uint8_t key2[kAes128KeySize], uint8_t tweak[kAesBlockSize], uint8_t * out) -{ - aes_context data_ctx; - aes_setkey_enc(&data_ctx, key1, 128); - - uint8_t enc_tweak[kAesBlockSize]; - AesEcbEncrypt(tweak, kAesBlockSize, key2, enc_tweak); - - size_t block_num = sector_size / kAesBlockSize; - uint8_t block[kAesBlockSize]; - for (size_t i = 0; i < block_num; i++) - { - XorBlock(in + (i * kAesBlockSize), enc_tweak, block); - aes_crypt_ecb(&data_ctx, AES_ENCRYPT, block, block); - XorBlock(block, enc_tweak, out + (i * kAesBlockSize)); - GaloisFunc(enc_tweak); - } - - if (sector_size % kAesBlockSize) - { - // TODO: implement ciphertext stealing - } -} - -void fnd::aes::AesXtsMakeTweak(uint8_t tweak[kAesBlockSize], size_t block_index) -{ - memset(tweak, 0, kAesBlockSize); - AesIncrementCounter(tweak, block_index, tweak); -} - -void fnd::aes::GaloisFunc(uint8_t x[kAesBlockSize]) -{ - uint8_t t = x[15]; - - for (uint8_t i = 15; i > 0; i--) - { - x[i] = (x[i] << 1) | (x[i - 1] & 0x80 ? 1 : 0); - } - - x[0] = (x[0] << 1) ^ (t & 0x80 ? 0x87 : 0x00); -} \ No newline at end of file diff --git a/lib/libfnd/source/base64_wrapper.cpp b/lib/libfnd/source/base64_wrapper.cpp deleted file mode 100644 index cd3e48b..0000000 --- a/lib/libfnd/source/base64_wrapper.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include -#include - -size_t fnd::base64::B64_GetEncodeLen(const uint8_t* src, size_t slen) -{ - size_t dlen = 0; - - base64_encode(nullptr, &dlen, src, slen); - - return dlen; -} - -void fnd::base64::B64_Encode(const uint8_t* src, size_t slen, uint8_t* dst, size_t dlen) -{ - base64_encode(dst, &dlen, src, slen); -} - -size_t fnd::base64::B64_GetDecodeLen(const uint8_t* src, size_t slen) -{ - size_t dlen = 0; - - base64_decode(nullptr, &dlen, src, slen); - - return dlen; -} - -void fnd::base64::B64_Decode(const uint8_t* src, size_t slen, uint8_t* dst, size_t dlen) -{ - base64_decode(dst, &dlen, src, slen); -} \ No newline at end of file diff --git a/lib/libfnd/source/io.cpp b/lib/libfnd/source/io.cpp deleted file mode 100644 index 1c1d5dd..0000000 --- a/lib/libfnd/source/io.cpp +++ /dev/null @@ -1,74 +0,0 @@ -#include -#include -#include -#include -#ifdef _WIN32 -#include -#include -#else -#include -#endif - -using namespace fnd; - -size_t io::getFileSize(const std::string& path) -{ - std::ifstream f; - f.open(path, std::ios_base::binary | std::ios_base::in); - if (!f.good() || f.eof() || !f.is_open()) { return 0; } - f.seekg(0, std::ios_base::beg); - std::ifstream::pos_type begin_pos = f.tellg(); - f.seekg(0, std::ios_base::end); - return static_cast(f.tellg() - begin_pos); -} - -void io::makeDirectory(const std::string& path) -{ -#ifdef _WIN32 - std::u16string wpath = fnd::StringConv::ConvertChar8ToChar16(path); - _wmkdir((wchar_t*)wpath.c_str()); -#else - mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); -#endif -} - -void fnd::io::getEnvironVar(std::string & var, const std::string & key) -{ -#ifdef _WIN32 - char* var_tmp = nullptr; - size_t var_len = 0; - _dupenv_s(&var_tmp, &var_len, key.c_str()); - - if (var_len > 0) - { - var = std::string(var_tmp); - free(var_tmp); - } -#else - char* var_tmp = nullptr; - - var_tmp = getenv(key.c_str()); - - if (var_tmp != nullptr) - { - var = std::string(var_tmp); - } -#endif -} - -void fnd::io::appendToPath(std::string& base, const std::string& add) -{ - if (add.empty()) - return; - - if (base.empty()) - { - base = add; - } - else - { - if (base[base.length()-1] != io::kPathDivider[0]) - base += io::kPathDivider; - base += add; - } -} diff --git a/lib/libfnd/source/lz4_wrapper.cpp b/lib/libfnd/source/lz4_wrapper.cpp deleted file mode 100644 index 7dee71e..0000000 --- a/lib/libfnd/source/lz4_wrapper.cpp +++ /dev/null @@ -1,14 +0,0 @@ -#include -#include - -void fnd::lz4::compressData(const uint8_t* src, uint32_t src_len, uint8_t* dst, uint32_t dst_capacity, uint32_t& compressed_size) -{ - compressed_size = LZ4_compress_default((const char*)src, (char*)dst, (int)src_len, (int)dst_capacity); -} - -void fnd::lz4::decompressData(const uint8_t* src, uint32_t src_len, uint8_t* dst, uint32_t dst_capacity, uint32_t& decompressed_size) -{ - decompressed_size = LZ4_decompress_safe((const char*)src, (char*)dst, (int)src_len, (int)dst_capacity); -} - - \ No newline at end of file diff --git a/lib/libfnd/source/rsa_wrapper.cpp b/lib/libfnd/source/rsa_wrapper.cpp deleted file mode 100644 index c6aee2a..0000000 --- a/lib/libfnd/source/rsa_wrapper.cpp +++ /dev/null @@ -1,214 +0,0 @@ -#include -#include -#include -#include -#include - -using namespace fnd::rsa; -using namespace fnd::sha; - -int getWrappedHashType(HashType type) -{ - switch (type) - { - case HASH_SHA1: - return SIG_RSA_SHA1; - break; - case HASH_SHA256: - return SIG_RSA_SHA256; - break; - default: - return SIG_RSA_RAW; - break; - } - return 0; -} - -int getMdWrappedHashType(HashType type) -{ - switch (type) - { - case HASH_SHA1: - return POLARSSL_MD_SHA1; - break; - case HASH_SHA256: - return POLARSSL_MD_SHA256; - break; - default: - return POLARSSL_MD_NONE; - break; - } - return 0; -} - -uint32_t getWrappedHashSize(HashType type) -{ - uint32_t size = 0; - - switch (type) - { - case HASH_SHA1: - size = kSha1HashLen; - break; - case HASH_SHA256: - size = kSha256HashLen; - break; - default: - break; - } - return size; -} - -int fnd::rsa::pkcs::rsaSign(const sRsa1024Key & key, HashType hash_type, const uint8_t * hash, uint8_t signature[kRsa1024Size]) -{ - int ret; - rsa_context ctx; - rsa_init(&ctx, RSA_PKCS_V15, 0); - - ctx.len = kRsa1024Size; - mpi_read_binary(&ctx.D, key.priv_exponent, ctx.len); - mpi_read_binary(&ctx.N, key.modulus, ctx.len); - - ret = rsa_rsassa_pkcs1_v15_sign(&ctx, RSA_PRIVATE, getWrappedHashType(hash_type), getWrappedHashSize(hash_type), hash, signature); - - rsa_free(&ctx); - - return ret; -} - -int fnd::rsa::pkcs::rsaVerify(const sRsa1024Key & key, HashType hash_type, const uint8_t * hash, const uint8_t signature[kRsa1024Size]) -{ - static const uint8_t public_exponent[3] = { 0x01, 0x00, 0x01 }; - - int ret; - rsa_context ctx; - rsa_init(&ctx, RSA_PKCS_V15, 0); - - ctx.len = kRsa1024Size; - mpi_read_binary(&ctx.E, public_exponent, sizeof(public_exponent)); - mpi_read_binary(&ctx.N, key.modulus, ctx.len); - - ret = rsa_rsassa_pkcs1_v15_verify(&ctx, RSA_PUBLIC, getWrappedHashType(hash_type), getWrappedHashSize(hash_type), hash, signature); - - rsa_free(&ctx); - - return ret; -} - -int fnd::rsa::pkcs::rsaSign(const sRsa2048Key & key, HashType hash_type, const uint8_t * hash, uint8_t signature[kRsa2048Size]) -{ - int ret; - rsa_context ctx; - rsa_init(&ctx, RSA_PKCS_V15, 0); - - ctx.len = kRsa2048Size; - mpi_read_binary(&ctx.D, key.priv_exponent, ctx.len); - mpi_read_binary(&ctx.N, key.modulus, ctx.len); - - ret = rsa_rsassa_pkcs1_v15_sign(&ctx, RSA_PRIVATE, getWrappedHashType(hash_type), getWrappedHashSize(hash_type), hash, signature); - - rsa_free(&ctx); - - return ret; -} - -int fnd::rsa::pkcs::rsaVerify(const sRsa2048Key & key, HashType hash_type, const uint8_t * hash, const uint8_t signature[kRsa2048Size]) -{ - static const uint8_t public_exponent[3] = { 0x01, 0x00, 0x01 }; - - int ret; - rsa_context ctx; - rsa_init(&ctx, RSA_PKCS_V15, 0); - - ctx.len = kRsa2048Size; - mpi_read_binary(&ctx.E, public_exponent, sizeof(public_exponent)); - mpi_read_binary(&ctx.N, key.modulus, ctx.len); - - ret = rsa_rsassa_pkcs1_v15_verify(&ctx, RSA_PUBLIC, getWrappedHashType(hash_type), getWrappedHashSize(hash_type), hash, signature); - - rsa_free(&ctx); - - return ret; -} - -int fnd::rsa::pkcs::rsaSign(const sRsa4096Key & key, HashType hash_type, const uint8_t * hash, uint8_t signature[kRsa4096Size]) -{ - int ret; - rsa_context ctx; - rsa_init(&ctx, RSA_PKCS_V15, 0); - - ctx.len = kRsa4096Size; - mpi_read_binary(&ctx.D, key.priv_exponent, ctx.len); - mpi_read_binary(&ctx.N, key.modulus, ctx.len); - - ret = rsa_rsassa_pkcs1_v15_sign(&ctx, RSA_PRIVATE, getWrappedHashType(hash_type), getWrappedHashSize(hash_type), hash, signature); - - rsa_free(&ctx); - - return ret; -} - -int fnd::rsa::pkcs::rsaVerify(const sRsa4096Key & key, HashType hash_type, const uint8_t * hash, const uint8_t signature[kRsa4096Size]) -{ - static const uint8_t public_exponent[3] = { 0x01, 0x00, 0x01 }; - - int ret; - rsa_context ctx; - rsa_init(&ctx, RSA_PKCS_V15, 0); - - ctx.len = kRsa4096Size; - mpi_read_binary(&ctx.E, public_exponent, sizeof(public_exponent)); - mpi_read_binary(&ctx.N, key.modulus, ctx.len); - - ret = rsa_rsassa_pkcs1_v15_verify(&ctx, RSA_PUBLIC, getWrappedHashType(hash_type), getWrappedHashSize(hash_type), hash, signature); - - rsa_free(&ctx); - - return ret; -} - -int fnd::rsa::pss::rsaSign(const sRsa2048Key & key, HashType hash_type, const uint8_t * hash, uint8_t signature[kRsa2048Size]) -{ - int ret; - const char* pers = "fnd::rsa::pss::rsaSign"; - - // rsa - rsa_context rsa; - rsa_init(&rsa, RSA_PKCS_V21, getMdWrappedHashType(hash_type)); - rsa.len = kRsa2048Size; - mpi_read_binary(&rsa.D, key.priv_exponent, rsa.len); - mpi_read_binary(&rsa.N, key.modulus, rsa.len); - - entropy_context entropy; - entropy_init(&entropy); - - ctr_drbg_context ctr_drbg; - ctr_drbg_init(&ctr_drbg, entropy_func, &entropy, (const uint8_t*)pers, strlen(pers)); - - ret = rsa_rsassa_pss_sign(&rsa, ctr_drbg_random, &ctr_drbg, RSA_PRIVATE, getWrappedHashType(hash_type), getWrappedHashSize(hash_type), hash, signature); - - rsa_free(&rsa); - - - return ret; -} - - -int fnd::rsa::pss::rsaVerify(const sRsa2048Key & key, HashType hash_type, const uint8_t * hash, const uint8_t signature[kRsa2048Size]) -{ - static const uint8_t public_exponent[3] = { 0x01, 0x00, 0x01 }; - - int ret; - rsa_context ctx; - rsa_init(&ctx, RSA_PKCS_V21, getMdWrappedHashType(hash_type)); - - ctx.len = kRsa2048Size; - mpi_read_binary(&ctx.E, public_exponent, sizeof(public_exponent)); - mpi_read_binary(&ctx.N, key.modulus, ctx.len); - - ret = rsa_rsassa_pss_verify(&ctx, RSA_PUBLIC, getWrappedHashType(hash_type), getWrappedHashSize(hash_type), hash, signature); - - rsa_free(&ctx); - - return ret; -} \ No newline at end of file diff --git a/lib/libfnd/source/sha_wrapper.cpp b/lib/libfnd/source/sha_wrapper.cpp deleted file mode 100644 index a1c7eb4..0000000 --- a/lib/libfnd/source/sha_wrapper.cpp +++ /dev/null @@ -1,15 +0,0 @@ -#include -#include -#include - -using namespace fnd::sha; - -void fnd::sha::Sha1(const uint8_t* in, uint64_t size, uint8_t hash[kSha1HashLen]) -{ - sha1(in, size, hash); -} - -void fnd::sha::Sha256(const uint8_t* in, uint64_t size, uint8_t hash[kSha256HashLen]) -{ - sha2(in, size, hash, false); -} \ No newline at end of file diff --git a/lib/libhac-hb/include/nn/hac/AssetHeader.h b/lib/libhac-hb/include/nn/hac/AssetHeader.h deleted file mode 100644 index fe2c077..0000000 --- a/lib/libhac-hb/include/nn/hac/AssetHeader.h +++ /dev/null @@ -1,72 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class AssetHeader : - public fnd::IByteModel - { - public: - struct sSection - { - uint64_t offset; - uint64_t size; - - void operator=(const sSection& other) - { - offset = other.offset; - size = other.size; - } - - bool operator==(const sSection& other) const - { - return (offset == other.offset) \ - && (size == other.size); - } - - bool operator!=(const sSection& other) const - { - return !operator==(other); - } - }; - - AssetHeader(); - AssetHeader(const AssetHeader& other); - - void operator=(const AssetHeader& other); - bool operator==(const AssetHeader& other) const; - bool operator!=(const AssetHeader& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* bytes, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - const sSection& getIconInfo() const; - void setIconInfo(const sSection& info); - - const sSection& getNacpInfo() const; - void setNacpInfo(const sSection& info); - - const sSection& getRomfsInfo() const; - void setRomfsInfo(const sSection& info); - private: - const std::string kModuleName = "NRO_ASSET_HEADER"; - - // binary - fnd::Vec mRawBinary; - - // data - sSection mIconInfo; - sSection mNacpInfo; - sSection mRomfsInfo; - }; -} -} \ No newline at end of file diff --git a/lib/libhac-hb/include/nn/hac/define/aset.h b/lib/libhac-hb/include/nn/hac/define/aset.h deleted file mode 100644 index c22b2eb..0000000 --- a/lib/libhac-hb/include/nn/hac/define/aset.h +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once -#include -#include - -namespace nn -{ -namespace hac -{ - namespace aset - { - static const uint32_t kAssetStructMagic = _MAKE_STRUCT_MAGIC_U32("ASET"); - - static const uint32_t kDefaultAssetFormatVersion = 0; - } - -#pragma pack(push,1) - struct sAssetSection - { - le_uint64_t offset; - le_uint64_t size; - }; - - struct sAssetHeader - { - le_uint32_t st_magic; - le_uint32_t format_version; - sAssetSection icon; - sAssetSection nacp; - sAssetSection romfs; - }; -#pragma pack(pop) -} -} \ No newline at end of file diff --git a/lib/libhac-hb/include/nn/hac/define/nro-hb.h b/lib/libhac-hb/include/nn/hac/define/nro-hb.h deleted file mode 100644 index 172850c..0000000 --- a/lib/libhac-hb/include/nn/hac/define/nro-hb.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once -#include -#include - -namespace nn -{ -namespace hac -{ - namespace nro - { - static const uint64_t kNroHomebrewStructMagic = _MAKE_STRUCT_MAGIC_U64("HOMEBREW"); - } -} -} \ No newline at end of file diff --git a/lib/libhac-hb/libhac-hb.vcxproj b/lib/libhac-hb/libhac-hb.vcxproj deleted file mode 100644 index 58ff29a..0000000 --- a/lib/libhac-hb/libhac-hb.vcxproj +++ /dev/null @@ -1,134 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 15.0 - {738CB4FC-CD9E-4B81-A04B-DEADBFA71C63} - 10.0.16299.0 - - - - StaticLibrary - true - v141 - MultiByte - - - StaticLibrary - false - v141 - true - MultiByte - - - StaticLibrary - true - v141 - MultiByte - - - StaticLibrary - false - v141 - true - MultiByte - - - - - - - - - - - - - - - - - - - - - - - Level3 - MaxSpeed - true - true - true - true - ..\libfnd\include;..\libhac\include;..\libhac-hb\include; - - - true - true - - - - - Level3 - Disabled - true - true - ..\libfnd\include;..\libhac\include;..\libhac-hb\include; - - - - - Level3 - Disabled - true - true - ..\libfnd\include;..\libhac\include;..\libhac-hb\include; - - - - - Level3 - MaxSpeed - true - true - true - true - ..\libfnd\include;..\libhac\include;..\libhac-hb\include; - - - true - true - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/lib/libhac-hb/libhac-hb.vcxproj.filters b/lib/libhac-hb/libhac-hb.vcxproj.filters deleted file mode 100644 index 8b43938..0000000 --- a/lib/libhac-hb/libhac-hb.vcxproj.filters +++ /dev/null @@ -1,39 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - {33064298-d382-4e79-9fcd-bc401bdaa763} - - - - - Header Files - - - Header Files\define - - - Header Files\define - - - - - Source Files - - - - - - \ No newline at end of file diff --git a/lib/libhac-hb/libhac-hb.vcxproj.user b/lib/libhac-hb/libhac-hb.vcxproj.user deleted file mode 100644 index be25078..0000000 --- a/lib/libhac-hb/libhac-hb.vcxproj.user +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/lib/libhac-hb/makefile b/lib/libhac-hb/makefile deleted file mode 100644 index f84b880..0000000 --- a/lib/libhac-hb/makefile +++ /dev/null @@ -1,46 +0,0 @@ -# Sources -SRC_DIR = source -OBJS = $(foreach dir,$(SRC_DIR),$(subst .cpp,.o,$(wildcard $(dir)/*.cpp))) $(foreach dir,$(SRC_DIR),$(subst .c,.o,$(wildcard $(dir)/*.c))) - -# External dependencies -DEPENDS = fnd crypto hac -LIB_DIR = .. -INCS = -I"include" $(foreach dep,$(DEPENDS), -I"$(LIB_DIR)/lib$(dep)/include") - -# Compiler Settings -CXXFLAGS = -std=c++11 $(INCS) -D__STDC_FORMAT_MACROS -Wall -Wno-unused-value -CFLAGS = -std=c11 $(INCS) -Wall -Wno-unused-value -ARFLAGS = cr -o -ifeq ($(OS),Windows_NT) - # Windows Only Flags/Libs - CC = x86_64-w64-mingw32-gcc - CXX = x86_64-w64-mingw32-g++ - CFLAGS += -Wno-unused-but-set-variable - CXXFLAGS += -Wno-unused-but-set-variable -else - UNAME = $(shell uname -s) - ifeq ($(UNAME), Darwin) - # MacOS Only Flags/Libs - CFLAGS += -Wno-unused-private-field - CXXFLAGS += -Wno-unused-private-field - ARFLAGS = rc - else - # *nix Only Flags/Libs - CFLAGS += -Wno-unused-but-set-variable - CXXFLAGS += -Wno-unused-but-set-variable - endif - -endif - -# Output -OUTPUT = $(shell basename "$(CURDIR)").a - -main: build - -rebuild: clean build - -build: $(OBJS) - ar $(ARFLAGS) $(OUTPUT) $(OBJS) - -clean: - rm -rf $(OUTPUT) $(OBJS) \ No newline at end of file diff --git a/lib/libhac-hb/source/AssetHeader.cpp b/lib/libhac-hb/source/AssetHeader.cpp deleted file mode 100644 index 666ebe0..0000000 --- a/lib/libhac-hb/source/AssetHeader.cpp +++ /dev/null @@ -1,135 +0,0 @@ -#include -#include - -nn::hac::AssetHeader::AssetHeader() -{ - clear(); -} - -nn::hac::AssetHeader::AssetHeader(const AssetHeader& other) -{ - *this = other; -} - -void nn::hac::AssetHeader::operator=(const AssetHeader& other) -{ - mRawBinary = other.mRawBinary; - mIconInfo = other.mIconInfo; - mNacpInfo = other.mNacpInfo; - mRomfsInfo = other.mRomfsInfo; -} - -bool nn::hac::AssetHeader::operator==(const AssetHeader& other) const -{ - return (mIconInfo == other.mIconInfo) \ - && (mNacpInfo == other.mNacpInfo) \ - && (mRomfsInfo == other.mRomfsInfo); -} - -bool nn::hac::AssetHeader::operator!=(const AssetHeader& other) const -{ - return !(*this == other); -} - -void nn::hac::AssetHeader::toBytes() -{ - mRawBinary.alloc(sizeof(sAssetHeader)); - nn::hac::sAssetHeader* hdr = (nn::hac::sAssetHeader*)mRawBinary.data(); - - // set header identifers - hdr->st_magic = aset::kAssetStructMagic; - hdr->format_version = aset::kDefaultAssetFormatVersion; - - // set icon section - hdr->icon.offset = mIconInfo.offset; - hdr->icon.size = mIconInfo.size; - - // set nacp section - hdr->nacp.offset = mNacpInfo.offset; - hdr->nacp.size = mNacpInfo.size; - - // set romfs section - hdr->romfs.offset = mRomfsInfo.offset; - hdr->romfs.size = mRomfsInfo.size; -} - -void nn::hac::AssetHeader::fromBytes(const byte_t* bytes, size_t len) -{ - // check input data size - if (len < sizeof(sAssetHeader)) - { - throw fnd::Exception(kModuleName, "ASET header size is too small"); - } - - // clear internal members - clear(); - - // allocate internal local binary copy - mRawBinary.alloc(sizeof(sAssetHeader)); - memcpy(mRawBinary.data(), bytes, mRawBinary.size()); - - // get sAssetHeader ptr - const nn::hac::sAssetHeader* hdr = (const nn::hac::sAssetHeader*)mRawBinary.data(); - - // check NRO signature - if (hdr->st_magic.get() != aset::kAssetStructMagic) - { - throw fnd::Exception(kModuleName, "ASET header corrupt (unrecognised header signature)"); - } - - // check NRO format version - if (hdr->format_version.get() != aset::kDefaultAssetFormatVersion) - { - throw fnd::Exception(kModuleName, "ASET header corrupt (unsupported format version)"); - } - - mIconInfo.offset = hdr->icon.offset.get(); - mIconInfo.size = hdr->icon.size.get(); - mNacpInfo.offset = hdr->nacp.offset.get(); - mNacpInfo.size = hdr->nacp.size.get(); - mRomfsInfo.offset = hdr->romfs.offset.get(); - mRomfsInfo.size = hdr->romfs.size.get(); -} - -const fnd::Vec& nn::hac::AssetHeader::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::AssetHeader::clear() -{ - mRawBinary.clear(); - memset(&mIconInfo, 0, sizeof(mIconInfo)); - memset(&mNacpInfo, 0, sizeof(mNacpInfo)); - memset(&mRomfsInfo, 0, sizeof(mRomfsInfo)); -} - -const nn::hac::AssetHeader::sSection& nn::hac::AssetHeader::getIconInfo() const -{ - return mIconInfo; -} - -void nn::hac::AssetHeader::setIconInfo(const nn::hac::AssetHeader::sSection& info) -{ - mIconInfo = info; -} - -const nn::hac::AssetHeader::sSection& nn::hac::AssetHeader::getNacpInfo() const -{ - return mNacpInfo; -} - -void nn::hac::AssetHeader::setNacpInfo(const sSection& info) -{ - mNacpInfo = info; -} - -const nn::hac::AssetHeader::sSection& nn::hac::AssetHeader::getRomfsInfo() const -{ - return mRomfsInfo; -} - -void nn::hac::AssetHeader::setRomfsInfo(const sSection& info) -{ - mRomfsInfo = info; -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/AccessControlInfo.h b/lib/libhac/include/nn/hac/AccessControlInfo.h deleted file mode 100644 index d25a182..0000000 --- a/lib/libhac/include/nn/hac/AccessControlInfo.h +++ /dev/null @@ -1,57 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class AccessControlInfo : - public fnd::IByteModel - { - public: - AccessControlInfo(); - AccessControlInfo(const AccessControlInfo& other); - - void operator=(const AccessControlInfo& other); - bool operator==(const AccessControlInfo& other) const; - bool operator!=(const AccessControlInfo& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* data, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - uint64_t getProgramId() const; - void setProgramId(uint64_t program_id); - - const nn::hac::FileSystemAccessControl& getFileSystemAccessControl() const; - void setFileSystemAccessControl(const FileSystemAccessControl& fac); - - const nn::hac::ServiceAccessControl& getServiceAccessControl() const; - void setServiceAccessControl(const ServiceAccessControl& sac); - - const nn::hac::KernelCapabilityControl& getKernelCapabilities() const; - void setKernelCapabilities(const KernelCapabilityControl& kc); - private: - const std::string kModuleName = "ACCESS_CONTROL_INFO_BINARY"; - - // raw data - fnd::Vec mRawBinary; - - // variables - uint64_t mProgramId; - nn::hac::FileSystemAccessControl mFileSystemAccessControl; - nn::hac::ServiceAccessControl mServiceAccessControl; - nn::hac::KernelCapabilityControl mKernelCapabilities; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/AccessControlInfoDesc.h b/lib/libhac/include/nn/hac/AccessControlInfoDesc.h deleted file mode 100644 index 93da791..0000000 --- a/lib/libhac/include/nn/hac/AccessControlInfoDesc.h +++ /dev/null @@ -1,92 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class AccessControlInfoDesc : - public fnd::IByteModel - { - public: - struct sProgramIdRestrict - { - uint64_t min; - uint64_t max; - - void operator=(const sProgramIdRestrict& other) - { - min = other.min; - max = other.max; - } - - bool operator==(const sProgramIdRestrict& other) const - { - return (min == other.min) \ - && (max == other.max); - } - - bool operator!=(const sProgramIdRestrict& other) const - { - return !(*this == other); - } - }; - - AccessControlInfoDesc(); - AccessControlInfoDesc(const AccessControlInfoDesc& other); - - void operator=(const AccessControlInfoDesc& other); - bool operator==(const AccessControlInfoDesc& other) const; - bool operator!=(const AccessControlInfoDesc& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* data, size_t len); - const fnd::Vec& getBytes() const; - - void generateSignature(const fnd::rsa::sRsa2048Key& key); - void validateSignature(const fnd::rsa::sRsa2048Key& key) const; - - // variables - void clear(); - - const fnd::rsa::sRsa2048Key& getContentArchiveHeaderSignature2Key() const; - void setContentArchiveHeaderSignature2Key(const fnd::rsa::sRsa2048Key& key); - - const fnd::List& getFlagList() const; - void setFlagList(const fnd::List& flags); - - const sProgramIdRestrict& getProgramIdRestrict() const; - void setProgramIdRestrict(const sProgramIdRestrict& pid_restrict); - - const nn::hac::FileSystemAccessControl& getFileSystemAccessControl() const; - void setFileSystemAccessControl(const FileSystemAccessControl& fac); - - const nn::hac::ServiceAccessControl& getServiceAccessControl() const; - void setServiceAccessControl(const ServiceAccessControl& sac); - - const nn::hac::KernelCapabilityControl& getKernelCapabilities() const; - void setKernelCapabilities(const KernelCapabilityControl& kc); - private: - const std::string kModuleName = "ACCESS_CONTROL_INFO_DESC_BINARY"; - - // raw data - fnd::Vec mRawBinary; - - // variables - fnd::rsa::sRsa2048Key mContentArchiveHeaderSignature2Key; - fnd::List mFlags; - sProgramIdRestrict mProgramIdRestrict; - nn::hac::FileSystemAccessControl mFileSystemAccessControl; - nn::hac::ServiceAccessControl mServiceAccessControl; - nn::hac::KernelCapabilityControl mKernelCapabilities; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/AddOnContentMetaExtendedHeader.h b/lib/libhac/include/nn/hac/AddOnContentMetaExtendedHeader.h deleted file mode 100644 index b3519b5..0000000 --- a/lib/libhac/include/nn/hac/AddOnContentMetaExtendedHeader.h +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once -#include -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class AddOnContentMetaExtendedHeader : - public fnd::IByteModel - { - public: - AddOnContentMetaExtendedHeader(); - AddOnContentMetaExtendedHeader(const AddOnContentMetaExtendedHeader& other); - - void operator=(const AddOnContentMetaExtendedHeader& other); - bool operator==(const AddOnContentMetaExtendedHeader& other) const; - bool operator!=(const AddOnContentMetaExtendedHeader& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* bytes, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - uint64_t getApplicationId() const; - void setApplicationId(uint64_t application_id); - - uint32_t getRequiredApplicationVersion() const; - void setRequiredApplicationVersion(uint32_t app_ver); - private: - const std::string kModuleName = "ADD_ON_CONTENT_META_EXTENDED_HEADER"; - - // binary blob - fnd::Vec mRawBinary; - - // variables - uint64_t mApplicationId; - uint32_t mRequiredApplicationVersion; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/AesKeygen.h b/lib/libhac/include/nn/hac/AesKeygen.h deleted file mode 100644 index e3caef6..0000000 --- a/lib/libhac/include/nn/hac/AesKeygen.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class AesKeygen - { - public: - - // 1 stage key generation dst = src_key.decrypt(src) - static void generateKey(byte_t* dst, const byte_t* src, const byte_t* src_key); - // 2 stage key generation dst = (src1_key.decrypt(src1)).decrypt(src2) - static void generateKey(byte_t* dst, const byte_t* src1, const byte_t* src2, const byte_t* src1_key); - // 3 stage key generation dst = ((src1_key.decrypt(src1)).decrypt(src2)).decrypt(src3) - static void generateKey(byte_t* dst, const byte_t* src1, const byte_t* src2, const byte_t* src3, const byte_t* src1_key); - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/ApplicationControlProperty.h b/lib/libhac/include/nn/hac/ApplicationControlProperty.h deleted file mode 100644 index 339811b..0000000 --- a/lib/libhac/include/nn/hac/ApplicationControlProperty.h +++ /dev/null @@ -1,272 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class ApplicationControlProperty : - public fnd::IByteModel - { - public: - struct sTitle - { - nacp::Language language; - std::string name; - std::string publisher; - - void operator=(const sTitle& other) - { - language = other.language; - name = other.name; - publisher = other.publisher; - } - - bool operator==(const sTitle& other) const - { - return (language == other.language) \ - && (name == other.name) \ - && (publisher == other.publisher); - } - - bool operator!=(const sTitle& other) const - { - return !operator==(other); - } - }; - - struct sRating - { - nacp::Organisation organisation; - int8_t age; - - void operator=(const sRating& other) - { - organisation = other.organisation; - age = other.age; - } - - bool operator==(const sRating& other) const - { - return (organisation == other.organisation) \ - && (age == other.age); - } - - bool operator!=(const sRating& other) const - { - return !operator==(other); - } - }; - - struct sStorageSize - { - int64_t size; - int64_t journal_size; - - void operator=(const sStorageSize& other) - { - size = other.size; - journal_size = other.journal_size; - } - - bool operator==(const sStorageSize& other) const - { - return (size == other.size) \ - && (journal_size == other.journal_size); - } - - bool operator!=(const sStorageSize& other) const - { - return !operator==(other); - } - }; - - ApplicationControlProperty(); - ApplicationControlProperty(const ApplicationControlProperty& other); - - void operator=(const ApplicationControlProperty& other); - bool operator==(const ApplicationControlProperty& other) const; - bool operator!=(const ApplicationControlProperty& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* bytes, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - const fnd::List& getTitle() const; - void setTitle(const fnd::List& title); - - const std::string& getIsbn() const; - void setIsbn(const std::string& isbn); - - nacp::StartupUserAccount getStartupUserAccount() const; - void setStartupUserAccount(nacp::StartupUserAccount var); - - nacp::UserAccountSwitchLockValue getUserAccountSwitchLockValue() const; - void setUserAccountSwitchLockValue(nacp::UserAccountSwitchLockValue var); - - nacp::AocRegistrationType getAocRegistrationType() const; - void setAocRegistrationType(nacp::AocRegistrationType var); - - nacp::AttributeFlag getAttributeFlag() const; - void setAttributeFlag(nacp::AttributeFlag var); - - const fnd::List& getSupportedLanguages() const; - void setSupportedLanguages(const fnd::List& var); - - nacp::ParentalControlFlag getParentalControlFlag() const; - void setParentalControlFlag(nacp::ParentalControlFlag var); - - nacp::ScreenshotMode getScreenshotMode() const; - void setScreenshotMode(nacp::ScreenshotMode var); - - nacp::VideoCaptureMode getVideoCaptureMode() const; - void setVideoCaptureMode(nacp::VideoCaptureMode var); - - nacp::DataLossConfirmation getDataLossConfirmation() const; - void setDataLossConfirmation(nacp::DataLossConfirmation var); - - nacp::PlayLogPolicy getPlayLogPolicy() const; - void setPlayLogPolicy(nacp::PlayLogPolicy var); - - uint64_t getPresenceGroupId() const; - void setPresenceGroupId(uint64_t var); - - const fnd::List& getRatingAge() const; - void setRatingAge(const fnd::List& var); - - const std::string& getDisplayVersion() const; - void setDisplayVersion(const std::string& var); - - uint64_t getAocBaseId() const; - void setAocBaseId(uint64_t var); - - uint64_t getSaveDatawOwnerId() const; - void setSaveDatawOwnerId(uint64_t var); - - const sStorageSize& getUserAccountSaveDataSize() const; - void setUserAccountSaveDataSize(const sStorageSize& var); - - const sStorageSize& getDeviceSaveDataSize() const; - void setDeviceSaveDataSize(const sStorageSize& var); - - int64_t getBcatDeliveryCacheStorageSize() const; - void setBcatDeliveryCacheStorageSize(int64_t var); - - const std::string& getApplicationErrorCodeCategory() const; - void setApplicationErrorCodeCategory(const std::string& var); - - const fnd::List& getLocalCommunicationId() const; - void setLocalCommunicationId(const fnd::List& var); - - nacp::LogoType getLogoType() const; - void setLogoType(nacp::LogoType var); - - nacp::LogoHandling getLogoHandling() const; - void setLogoHandling(nacp::LogoHandling var); - - nacp::RuntimeAocInstallMode getRuntimeAocInstallMode() const; - void setRuntimeAocInstallMode(nacp::RuntimeAocInstallMode var); - - nacp::CrashReportMode getCrashReportMode() const; - void setCrashReportMode(nacp::CrashReportMode var); - - nacp::Hdcp getHdcp() const; - void setHdcp(nacp::Hdcp var); - - uint64_t getSeedForPsuedoDeviceId() const; - void setSeedForPsuedoDeviceId(uint64_t var); - - const std::string& getBcatPassphase() const; - void setBcatPassphase(const std::string& var); - - const sStorageSize& getUserAccountSaveDataMax() const; - void setUserAccountSaveDataMax(const sStorageSize& var); - - const sStorageSize& getDeviceSaveDataMax() const; - void setDeviceSaveDataMax(const sStorageSize& var); - - int64_t getTemporaryStorageSize() const; - void setTemporaryStorageSize(int64_t var); - - const sStorageSize& getCacheStorageSize() const; - void setCacheStorageSize(const sStorageSize& var); - - int64_t getCacheStorageDataAndJournalSizeMax() const; - void setCacheStorageDataAndJournalSizeMax(int64_t var); - - uint16_t getCacheStorageIndexMax() const; - void setCacheStorageIndexMax(uint16_t var); - - const fnd::List& getPlayLogQueryableApplicationId() const; - void setPlayLogQueryableApplicationId(const fnd::List& var); - - nacp::PlayLogQueryCapability getPlayLogQueryCapability() const; - void setPlayLogQueryCapability(nacp::PlayLogQueryCapability var); - - nacp::RepairFlag getRepairFlag() const; - void setRepairFlag(nacp::RepairFlag var); - - byte_t getProgramIndex() const; - void setProgramIndex(byte_t var); - - nacp::RequiredNetworkServiceLicenseOnLaunchValue getRequiredNetworkServiceLicenseOnLaunchValue() const; - void setRequiredNetworkServiceLicenseOnLaunchValue(nacp::RequiredNetworkServiceLicenseOnLaunchValue var); - - private: - const std::string kModuleName = "APPLICATION_CONTROL_PROPERTY"; - - // raw data - fnd::Vec mRawBinary; - - // variables - fnd::List mTitle; - std::string mIsbn; - nacp::StartupUserAccount mStartupUserAccount; - nacp::UserAccountSwitchLockValue mUserAccountSwitchLockValue; - nacp::AocRegistrationType mAocRegistrationType; - nacp::AttributeFlag mAttributeFlag; - fnd::List mSupportedLanguages; - nacp::ParentalControlFlag mParentalControlFlag; - nacp::ScreenshotMode mScreenshotMode; - nacp::VideoCaptureMode mVideoCaptureMode; - nacp::DataLossConfirmation mDataLossConfirmation; - nacp::PlayLogPolicy mPlayLogPolicy; - uint64_t mPresenceGroupId; - fnd::List mRatingAge; - std::string mDisplayVersion; - uint64_t mAocBaseId; - uint64_t mSaveDatawOwnerId; - sStorageSize mUserAccountSaveDataSize; - sStorageSize mDeviceSaveDataSize; - int64_t mBcatDeliveryCacheStorageSize; - std::string mApplicationErrorCodeCategory; - fnd::List mLocalCommunicationId; - nacp::LogoType mLogoType; - nacp::LogoHandling mLogoHandling; - nacp::RuntimeAocInstallMode mRuntimeAocInstallMode; - nacp::CrashReportMode mCrashReportMode; - nacp::Hdcp mHdcp; - uint64_t mSeedForPsuedoDeviceId; - std::string mBcatPassphase; - sStorageSize mUserAccountSaveDataMax; - sStorageSize mDeviceSaveDataMax; - int64_t mTemporaryStorageSize; - sStorageSize mCacheStorageSize; - int64_t mCacheStorageDataAndJournalSizeMax; - uint16_t mCacheStorageIndexMax; - fnd::List mPlayLogQueryableApplicationId; - nacp::PlayLogQueryCapability mPlayLogQueryCapability; - nacp::RepairFlag mRepairFlag; - byte_t mProgramIndex; - nacp::RequiredNetworkServiceLicenseOnLaunchValue mRequiredNetworkServiceLicenseOnLaunchValue; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/ApplicationControlPropertyUtils.h b/lib/libhac/include/nn/hac/ApplicationControlPropertyUtils.h deleted file mode 100644 index feeb666..0000000 --- a/lib/libhac/include/nn/hac/ApplicationControlPropertyUtils.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once -#include - -namespace nn -{ -namespace hac -{ - class ApplicationControlPropertyUtils - { - public: - static bool validateSaveDataSizeMax(int64_t size, int64_t alignment); - static bool validateSaveDataSize(int64_t size); - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/ApplicationMetaExtendedHeader.h b/lib/libhac/include/nn/hac/ApplicationMetaExtendedHeader.h deleted file mode 100644 index 498567a..0000000 --- a/lib/libhac/include/nn/hac/ApplicationMetaExtendedHeader.h +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once -#include -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class ApplicationMetaExtendedHeader : - public fnd::IByteModel - { - public: - ApplicationMetaExtendedHeader(); - ApplicationMetaExtendedHeader(const ApplicationMetaExtendedHeader& other); - - void operator=(const ApplicationMetaExtendedHeader& other); - bool operator==(const ApplicationMetaExtendedHeader& other) const; - bool operator!=(const ApplicationMetaExtendedHeader& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* bytes, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - uint64_t getPatchId() const; - void setPatchId(uint64_t patch_id); - - uint32_t getRequiredSystemVersion() const; - void setRequiredSystemVersion(uint32_t sys_ver); - private: - const std::string kModuleName = "APPLICATION_META_EXTENDED_HEADER"; - - // binary blob - fnd::Vec mRawBinary; - - // variables - uint64_t mPatchId; - uint32_t mRequiredSystemVersion; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/ContentArchiveHeader.h b/lib/libhac/include/nn/hac/ContentArchiveHeader.h deleted file mode 100644 index fe2c399..0000000 --- a/lib/libhac/include/nn/hac/ContentArchiveHeader.h +++ /dev/null @@ -1,121 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class ContentArchiveHeader : - public fnd::IByteModel - { - public: - struct sPartitionEntry - { - byte_t header_index; - uint64_t offset; - uint64_t size; - fnd::sha::sSha256Hash fs_header_hash; - - const sPartitionEntry& operator=(const sPartitionEntry& other) - { - header_index = other.header_index; - offset = other.offset; - size = other.size; - fs_header_hash = other.fs_header_hash; - - return *this; - } - - bool operator==(const sPartitionEntry& other) const - { - return (header_index == other.header_index) \ - && (offset == other.offset) \ - && (size == other.size) \ - && (fs_header_hash == other.fs_header_hash); - } - - bool operator!=(const sPartitionEntry& other) const - { - return !operator==(other); - } - }; - - ContentArchiveHeader(); - ContentArchiveHeader(const ContentArchiveHeader& other); - - void operator=(const ContentArchiveHeader& other); - bool operator==(const ContentArchiveHeader& other) const; - bool operator!=(const ContentArchiveHeader& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* bytes, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - byte_t getFormatVersion() const; - void setFormatVersion(byte_t ver); - - nca::DistributionType getDistributionType() const; - void setDistributionType(nca::DistributionType type); - - nca::ContentType getContentType() const; - void setContentType(nca::ContentType type); - - byte_t getKeyGeneration() const; - void setKeyGeneration(byte_t gen); - - byte_t getKeyAreaEncryptionKeyIndex() const; - void setKeyAreaEncryptionKeyIndex(byte_t index); - - uint64_t getContentSize() const; - void setContentSize(uint64_t size); - - uint64_t getProgramId() const; - void setProgramId(uint64_t program_id); - - uint32_t getContentIndex() const; - void setContentIndex(uint32_t index); - - uint32_t getSdkAddonVersion() const; - void setSdkAddonVersion(uint32_t version); - - bool hasRightsId() const; - const byte_t* getRightsId() const; - void setRightsId(const byte_t* rights_id); - - const fnd::List& getPartitionEntryList() const; - void setPartitionEntryList(const fnd::List& partition_entry_list); - - const byte_t* getKeyArea() const; - void setKeyArea(const byte_t* key_area); - - private: - const std::string kModuleName = "CONTENT_ARCHIVE_HEADER"; - - // binary - fnd::Vec mRawBinary; - - // data - byte_t mFormatVersion; - nca::DistributionType mDistributionType; - nca::ContentType mContentType; - byte_t mKeyGeneration; - byte_t mKaekIndex; - uint64_t mContentSize; - uint64_t mProgramId; - uint32_t mContentIndex; - uint32_t mSdkAddonVersion; - fnd::Vec mRightsId; - fnd::List mPartitionEntryList; - fnd::Vec mKeyArea; - - uint64_t blockNumToSize(uint32_t block_num) const; - uint32_t sizeToBlockNum(uint64_t real_size) const; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/ContentArchiveUtils.h b/lib/libhac/include/nn/hac/ContentArchiveUtils.h deleted file mode 100644 index 62315d8..0000000 --- a/lib/libhac/include/nn/hac/ContentArchiveUtils.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once -#include - -namespace nn -{ -namespace hac -{ - class ContentArchiveUtils - { - public: - static inline size_t sectorToOffset(size_t sector_index) { return sector_index * nn::hac::nca::kSectorSize; } - static void decryptContentArchiveHeader(const byte_t* src, byte_t* dst, const fnd::aes::sAesXts128Key& key); - static byte_t getMasterKeyRevisionFromKeyGeneration(byte_t key_generation); - static void getNcaPartitionAesCtr(const nn::hac::sNcaFsHeader* hdr, byte_t* ctr); - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/ContentInfo.h b/lib/libhac/include/nn/hac/ContentInfo.h deleted file mode 100644 index eb644c5..0000000 --- a/lib/libhac/include/nn/hac/ContentInfo.h +++ /dev/null @@ -1,59 +0,0 @@ -#pragma once -#include -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class ContentInfo : - public fnd::IByteModel - { - public: - ContentInfo(); - ContentInfo(const ContentInfo& other); - - void operator=(const ContentInfo& other); - bool operator==(const ContentInfo& other) const; - bool operator!=(const ContentInfo& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* bytes, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - const fnd::sha::sSha256Hash& getContentHash() const; - void setContentHash(const fnd::sha::sSha256Hash& hash); - - const cnmt::sContentId& getContentId() const; - void setContentId(const cnmt::sContentId& content_id); - - size_t getContentSize() const; - void setContentSize(size_t size); - - cnmt::ContentType getContentType() const; - void setContentType(cnmt::ContentType type); - - byte_t getIdOffset() const; - void setIdOffset(byte_t id_offset); - - private: - const std::string kModuleName = "CONTENT_INFO"; - - // binary blob - fnd::Vec mRawBinary; - - // variables - fnd::sha::sSha256Hash mHash; - cnmt::sContentId mContentId; - size_t mSize; - cnmt::ContentType mType; - byte_t mIdOffset; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/ContentMeta.h b/lib/libhac/include/nn/hac/ContentMeta.h deleted file mode 100644 index f7c0765..0000000 --- a/lib/libhac/include/nn/hac/ContentMeta.h +++ /dev/null @@ -1,113 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class ContentMeta : - public fnd::IByteModel - { - public: - ContentMeta(); - ContentMeta(const ContentMeta& other); - - void operator=(const ContentMeta& other); - bool operator==(const ContentMeta& other) const; - bool operator!=(const ContentMeta& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* bytes, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - uint64_t getTitleId() const; - void setTitleId(uint64_t title_id); - - uint32_t getTitleVersion() const; - void setTitleVersion(uint32_t version); - - cnmt::ContentMetaType getContentMetaType() const; - void setContentMetaType(cnmt::ContentMetaType type); - - byte_t getAttributes() const; - void setAttributes(byte_t attributes); - - uint32_t getRequiredDownloadSystemVersion() const; - void setRequiredDownloadSystemVersion(uint32_t version); - - const ApplicationMetaExtendedHeader& getApplicationMetaExtendedHeader() const; - void setApplicationMetaExtendedHeader(const ApplicationMetaExtendedHeader& exhdr); - - const PatchMetaExtendedHeader& getPatchMetaExtendedHeader() const; - void setPatchMetaExtendedHeader(const PatchMetaExtendedHeader& exhdr); - - const AddOnContentMetaExtendedHeader& getAddOnContentMetaExtendedHeader() const; - void setAddOnContentMetaExtendedHeader(const AddOnContentMetaExtendedHeader& exhdr); - - const DeltaMetaExtendedHeader& getDeltaMetaExtendedHeader() const; - void setDeltaMetaExtendedHeader(const DeltaMetaExtendedHeader& exhdr); - - const fnd::List& getContentInfo() const; - void setContentInfo(const fnd::List& info); - - const fnd::List& getContentMetaInfo() const; - void setContentMetaInfo(const fnd::List& info); - - const fnd::Vec& getExtendedData() const; - void setExtendedData(const fnd::Vec& data); - - const cnmt::sDigest& getDigest() const; - void setDigest(const cnmt::sDigest& digest); - - - private: - const std::string kModuleName = "CONTENT_META"; - - // binary blob - fnd::Vec mRawBinary; - - // variables - uint64_t mTitleId; - uint32_t mTitleVersion; - cnmt::ContentMetaType mType; - byte_t mAttributes; - uint32_t mRequiredDownloadSystemVersion; - fnd::Vec mExtendedHeader; - - ApplicationMetaExtendedHeader mApplicationMetaExtendedHeader; - PatchMetaExtendedHeader mPatchMetaExtendedHeader; - AddOnContentMetaExtendedHeader mAddOnContentMetaExtendedHeader; - DeltaMetaExtendedHeader mDeltaMetaExtendedHeader; - - fnd::List mContentInfo; - fnd::List mContentMetaInfo; - fnd::Vec mExtendedData; - cnmt::sDigest mDigest; - - inline size_t getExtendedHeaderOffset() const { return sizeof(sContentMetaHeader); } - inline size_t getContentInfoOffset(size_t exhdrSize) const { return getExtendedHeaderOffset() + exhdrSize; } - inline size_t getContentMetaInfoOffset(size_t exhdrSize, size_t contentInfoNum) const { return getContentInfoOffset(exhdrSize) + contentInfoNum * sizeof(sContentInfo); } - inline size_t getExtendedDataOffset(size_t exhdrSize, size_t contentInfoNum, size_t contentMetaNum) const { return getContentMetaInfoOffset(exhdrSize, contentInfoNum) + contentMetaNum * sizeof(sContentMetaInfo); } - inline size_t getDigestOffset(size_t exhdrSize, size_t contentInfoNum, size_t contentMetaNum, size_t exdataSize) const { return getExtendedDataOffset(exhdrSize, contentInfoNum, contentMetaNum) + exdataSize; } - inline size_t getTotalSize(size_t exhdrSize, size_t contentInfoNum, size_t contentMetaNum, size_t exdataSize) const { return getDigestOffset(exhdrSize, contentInfoNum, contentMetaNum, exdataSize) + cnmt::kDigestLen; } - - bool validateExtendedHeaderSize(cnmt::ContentMetaType type, size_t exhdrSize) const; - size_t getExtendedDataSize(cnmt::ContentMetaType type, const byte_t* data) const; - void validateBinary(const byte_t* bytes, size_t len) const; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/ContentMetaInfo.h b/lib/libhac/include/nn/hac/ContentMetaInfo.h deleted file mode 100644 index f6a680e..0000000 --- a/lib/libhac/include/nn/hac/ContentMetaInfo.h +++ /dev/null @@ -1,55 +0,0 @@ -#pragma once -#include -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class ContentMetaInfo : - public fnd::IByteModel - { - public: - ContentMetaInfo(); - ContentMetaInfo(const ContentMetaInfo& other); - - void operator=(const ContentMetaInfo& other); - bool operator==(const ContentMetaInfo& other) const; - bool operator!=(const ContentMetaInfo& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* bytes, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - uint64_t getTitleId() const; - void setTitleId(uint64_t title_id); - - uint32_t getTitleVersion() const; - void setTitleVersion(uint32_t ver); - - cnmt::ContentMetaType getContentMetaType() const; - void setContentMetaType(cnmt::ContentMetaType type); - - byte_t getAttributes() const; - void setAttributes(byte_t attr); - - private: - const std::string kModuleName = "CONTENT_META_INFO"; - - // byte model - fnd::Vec mRawBinary; - - // variables - uint64_t mTitleId; - uint32_t mTitleVersion; - cnmt::ContentMetaType mType; - byte_t mAttributes; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/DeltaMetaExtendedHeader.h b/lib/libhac/include/nn/hac/DeltaMetaExtendedHeader.h deleted file mode 100644 index de12ad5..0000000 --- a/lib/libhac/include/nn/hac/DeltaMetaExtendedHeader.h +++ /dev/null @@ -1,47 +0,0 @@ -#pragma once -#include -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class DeltaMetaExtendedHeader : - public fnd::IByteModel - { - public: - DeltaMetaExtendedHeader(); - DeltaMetaExtendedHeader(const DeltaMetaExtendedHeader& other); - - void operator=(const DeltaMetaExtendedHeader& other); - bool operator==(const DeltaMetaExtendedHeader& other) const; - bool operator!=(const DeltaMetaExtendedHeader& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* bytes, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - uint64_t getApplicationId() const; - void setApplicationId(uint64_t application_id); - - uint32_t getExtendedDataSize() const; - void setExtendedDataSize(uint32_t size); - - private: - const std::string kModuleName = "DELTA_META_EXTENDED_HEADER"; - - // binary blob - fnd::Vec mRawBinary; - - // variables - uint64_t mApplicationId; - uint32_t mExtendedDataSize; - }; -} -} diff --git a/lib/libhac/include/nn/hac/FileSystemAccessControl.h b/lib/libhac/include/nn/hac/FileSystemAccessControl.h deleted file mode 100644 index c39303c..0000000 --- a/lib/libhac/include/nn/hac/FileSystemAccessControl.h +++ /dev/null @@ -1,78 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class FileSystemAccessControl : - public fnd::IByteModel - { - public: - struct sSaveDataOwnerId - { - nn::hac::fac::SaveDataOwnerIdAccessType access_type; - uint64_t id; - - void operator=(const sSaveDataOwnerId& other) - { - access_type = other.access_type; - id = other.id; - } - - bool operator==(const sSaveDataOwnerId& other) const - { - return (access_type == other.access_type) \ - && (id == other.id); - } - - bool operator!=(const sSaveDataOwnerId& other) const - { - return !(*this == other); - } - }; - - FileSystemAccessControl(); - FileSystemAccessControl(const FileSystemAccessControl& other); - - void operator=(const FileSystemAccessControl& other); - bool operator==(const FileSystemAccessControl& other) const; - bool operator!=(const FileSystemAccessControl& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* data, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - uint32_t getFormatVersion() const; - void setFormatVersion(uint32_t version); - - const fnd::List& getFsaRightsList() const; - void setFsaRightsList(const fnd::List& list); - - const fnd::List& getContentOwnerIdList() const; - void setContentOwnerIdList(const fnd::List& list); - - const fnd::List& getSaveDataOwnerIdList() const; - void setSaveDataOwnerIdList(const fnd::List& list); - private: - const std::string kModuleName = "FILE_SYSTEM_ACCESS_CONTROL"; - - // raw data - fnd::Vec mRawBinary; - - // variables - uint32_t mVersion; - fnd::List mFsaRights; - fnd::List mContentOwnerIdList; - fnd::List mSaveDataOwnerIdList; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/GameCardHeader.h b/lib/libhac/include/nn/hac/GameCardHeader.h deleted file mode 100644 index 416afa7..0000000 --- a/lib/libhac/include/nn/hac/GameCardHeader.h +++ /dev/null @@ -1,127 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class GameCardHeader : - public fnd::IByteModel - { - public: - GameCardHeader(); - GameCardHeader(const GameCardHeader& other); - - void operator=(const GameCardHeader& other); - bool operator==(const GameCardHeader& other) const; - bool operator!=(const GameCardHeader& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* bytes, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - uint32_t getRomAreaStartPage() const; - void setRomAreaStartPage(uint32_t startPage); - uint32_t getBackupAreaStartPage() const; - void setBackupAreaStartPage(uint32_t startPage); - byte_t getKekIndex() const; - void setKekIndex(byte_t kekIndex); - byte_t getTitleKeyDecIndex() const; - void setTitleKeyDecIndex(byte_t index); - byte_t getRomSizeType() const; - void setRomSizeType(byte_t romSizeType); - byte_t getCardHeaderVersion() const; - void setCardHeaderVersion(byte_t version); - byte_t getFlags() const; - void setFlags(byte_t flags); - uint64_t getPackageId() const; - void setPackageId(uint64_t id); - uint32_t getValidDataEndPage() const; - void setValidDataEndPage(uint32_t page); - const fnd::aes::sAesIvCtr& getAesCbcIv() const; - void setAesCbcIv(const fnd::aes::sAesIvCtr& iv); - uint64_t getPartitionFsAddress() const; - void setPartitionFsAddress(uint64_t address); - uint64_t getPartitionFsSize() const; - void setPartitionFsSize(uint64_t size); - const fnd::sha::sSha256Hash& getPartitionFsHash() const; - void setPartitionFsHash(const fnd::sha::sSha256Hash& hash); - const fnd::sha::sSha256Hash& getInitialDataHash() const; - void setInitialDataHash(const fnd::sha::sSha256Hash& hash); - uint32_t getSelSec() const; - void setSelSec(uint32_t sel_sec); - uint32_t getSelT1Key() const; - void setSelT1Key(uint32_t sel_t1_key); - uint32_t getSelKey() const; - void setSelKey(uint32_t sel_key); - uint32_t getLimAreaPage() const; - void setLimAreaPage(uint32_t page); - - uint32_t getFwVerMajor() const; - void setFwVerMajor(uint32_t ver); - uint32_t getFwVerMinor() const; - void setFwVerMinor(uint32_t ver); - uint32_t getAccCtrl1() const; - void setAccCtrl1(uint32_t acc_ctrl_1); - uint32_t getWait1TimeRead() const; - void setWait1TimeRead(uint32_t seconds); - uint32_t getWait2TimeRead() const; - void setWait2TimeRead(uint32_t seconds); - uint32_t getWait1TimeWrite() const; - void setWait1TimeWrite(uint32_t seconds); - uint32_t getWait2TimeWrite() const; - void setWait2TimeWrite(uint32_t seconds); - uint32_t getFwMode() const; - void setFwMode(uint32_t fw_mode); - uint32_t getUppVersion() const; - void setUppVersion(uint32_t version); - const byte_t* getUppHash() const; - void setUppHash(const byte_t* hash); - uint64_t getUppId() const; - void setUppId(uint64_t id); - - private: - const std::string kModuleName = "GAMECARD_HEADER"; - - // binary - fnd::Vec mRawBinary; - - // data - uint32_t mRomAreaStartPage; - uint32_t mBackupAreaStartPage; - byte_t mKekIndex; - byte_t mTitleKeyDecIndex; - byte_t mRomSize; - byte_t mCardHeaderVersion; - byte_t mFlags; - uint64_t mPackageId; - uint32_t mValidDataEndPage; - fnd::aes::sAesIvCtr mAesCbcIv; - uint64_t mPartitionFsHeaderAddress; - uint64_t mPartitionFsHeaderSize; - fnd::sha::sSha256Hash mPartitionFsHeaderHash; - fnd::sha::sSha256Hash mInitialDataHash; - uint32_t mSelSec; - uint32_t mSelT1Key; - uint32_t mSelKey; - uint32_t mLimAreaPage; - - // Encrypted/Extended Data - uint32_t mFwVersion[2]; - uint32_t mAccCtrl1; - uint32_t mWait1TimeRead; - uint32_t mWait2TimeRead; - uint32_t mWait1TimeWrite; - uint32_t mWait2TimeWrite; - uint32_t mFwMode; - uint32_t mUppVersion; - byte_t mUppHash[8]; - uint64_t mUppId; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/GameCardUtils.h b/lib/libhac/include/nn/hac/GameCardUtils.h deleted file mode 100644 index fd6f400..0000000 --- a/lib/libhac/include/nn/hac/GameCardUtils.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once -#include - -namespace nn -{ -namespace hac -{ - class GameCardUtils - { - public: - static inline uint64_t blockToAddr(uint32_t block) { return ((uint64_t)block) << 9; } - static void getXciHeaderAesIv(const nn::hac::sGcHeader* hdr, byte_t* iv); - static void decryptXciHeader(const byte_t* src, byte_t* dst, const byte_t* key); - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/HandleTableSizeEntry.h b/lib/libhac/include/nn/hac/HandleTableSizeEntry.h deleted file mode 100644 index 5ef89df..0000000 --- a/lib/libhac/include/nn/hac/HandleTableSizeEntry.h +++ /dev/null @@ -1,50 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class HandleTableSizeEntry - { - public: - HandleTableSizeEntry(); - HandleTableSizeEntry(const KernelCapabilityEntry& kernel_cap); - HandleTableSizeEntry(uint16_t size); - - void operator=(const HandleTableSizeEntry& other); - bool operator==(const HandleTableSizeEntry& other) const; - bool operator!=(const HandleTableSizeEntry& other) const; - - // kernel capability - const KernelCapabilityEntry& getKernelCapability() const; - void setKernelCapability(const KernelCapabilityEntry& kernel_cap); - - // variables - uint16_t getHandleTableSize() const; - void setHandleTableSize(uint16_t size); - private: - const std::string kModuleName = "HANDLE_TABLE_SIZE_ENTRY"; - static const kc::KernelCapId kCapId = kc::KC_HANDLE_TABLE_SIZE; - static const uint16_t kValBits = 10; - static const uint16_t kMaxHandleTableSize = BIT(kValBits) - 1; - - KernelCapabilityEntry mCap; - uint16_t mHandleTableSize; - - inline void updateCapField() - { - uint32_t field = mHandleTableSize & kMaxHandleTableSize; - mCap.setField(field); - } - - inline void processCapField() - { - uint32_t field = mCap.getField(); - mHandleTableSize = field & kMaxHandleTableSize; - } - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/HandleTableSizeHandler.h b/lib/libhac/include/nn/hac/HandleTableSizeHandler.h deleted file mode 100644 index 200036d..0000000 --- a/lib/libhac/include/nn/hac/HandleTableSizeHandler.h +++ /dev/null @@ -1,37 +0,0 @@ -#pragma once -#include -#include - -namespace nn -{ -namespace hac -{ - class HandleTableSizeHandler : - public IKernelCapabilityHandler - { - public: - HandleTableSizeHandler(); - - void operator=(const HandleTableSizeHandler& other); - bool operator==(const HandleTableSizeHandler& other) const; - bool operator!=(const HandleTableSizeHandler& other) const; - - // kernel capabilty list in/out - void importKernelCapabilityList(const fnd::List& caps); - void exportKernelCapabilityList(fnd::List& caps) const; - void clear(); - bool isSet() const; - - // variables - uint16_t getHandleTableSize() const; - void setHandleTableSize(uint16_t size); - - private: - const std::string kModuleName = "HANDLE_TABLE_SIZE_HANDLER"; - static const size_t kMaxKernelCapNum = 1; - - bool mIsSet; - HandleTableSizeEntry mEntry; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/HierarchicalIntegrityHeader.h b/lib/libhac/include/nn/hac/HierarchicalIntegrityHeader.h deleted file mode 100644 index 5f4d312..0000000 --- a/lib/libhac/include/nn/hac/HierarchicalIntegrityHeader.h +++ /dev/null @@ -1,70 +0,0 @@ -#pragma once -#include -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class HierarchicalIntegrityHeader : - public fnd::IByteModel - { - public: - struct sLayer - { - size_t offset; - size_t size; - size_t block_size; - - void operator=(const sLayer& other) - { - offset = other.offset; - size = other.size; - block_size = other.block_size; - } - - bool operator==(const sLayer& other) const - { - return (offset == other.offset && size == other.size && block_size == other.block_size); - } - - bool operator!=(const sLayer& other) const - { - return !(*this == other); - } - }; - - HierarchicalIntegrityHeader(); - HierarchicalIntegrityHeader(const HierarchicalIntegrityHeader& other); - - void operator=(const HierarchicalIntegrityHeader& other); - bool operator==(const HierarchicalIntegrityHeader& other) const; - bool operator!=(const HierarchicalIntegrityHeader& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* bytes, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - const fnd::List& getLayerInfo() const; - void setLayerInfo(const fnd::List& layer_info); - - const fnd::List& getMasterHashList() const; - void setMasterHashList(const fnd::List& master_hash_list); - private: - const std::string kModuleName = "HIERARCHICAL_INTEGRITY_HEADER"; - - // binary - fnd::Vec mRawBinary; - - // data - fnd::List mLayerInfo; - fnd::List mMasterHashList; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/HierarchicalSha256Header.h b/lib/libhac/include/nn/hac/HierarchicalSha256Header.h deleted file mode 100644 index 0ec96ae..0000000 --- a/lib/libhac/include/nn/hac/HierarchicalSha256Header.h +++ /dev/null @@ -1,71 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class HierarchicalSha256Header : - public fnd::IByteModel - { - public: - struct sLayer - { - size_t offset; - size_t size; - - void operator=(const sLayer& other) - { - offset = other.offset; - size = other.size; - } - - bool operator==(const sLayer& other) const - { - return (offset == other.offset && size == other.size); - } - - bool operator!=(const sLayer& other) const - { - return !(*this == other); - } - }; - - HierarchicalSha256Header(); - HierarchicalSha256Header(const HierarchicalSha256Header& other); - - void operator=(const HierarchicalSha256Header& other); - bool operator==(const HierarchicalSha256Header& other) const; - bool operator!=(const HierarchicalSha256Header& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* bytes, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - const fnd::sha::sSha256Hash& getMasterHash() const; - void setMasterHash(const fnd::sha::sSha256Hash& master_hash); - - size_t getHashBlockSize() const; - void setHashBlockSize(size_t hash_block_size); - - const fnd::List& getLayerInfo() const; - void setLayerInfo(const fnd::List& layer_info); - private: - const std::string kModuleName = "HIERARCHICAL_SHA256_HEADER"; - - // binary - fnd::Vec mRawBinary; - - // data - fnd::sha::sSha256Hash mMasterHash; - size_t mHashBlockSize; - fnd::List mLayerInfo; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/IKernelCapabilityHandler.h b/lib/libhac/include/nn/hac/IKernelCapabilityHandler.h deleted file mode 100644 index 7437465..0000000 --- a/lib/libhac/include/nn/hac/IKernelCapabilityHandler.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class IKernelCapabilityHandler - { - public: - virtual void importKernelCapabilityList(const fnd::List& caps) = 0; - virtual void exportKernelCapabilityList(fnd::List& caps) const = 0; - virtual void clear() = 0; - virtual bool isSet() const = 0; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/IdConverter.h b/lib/libhac/include/nn/hac/IdConverter.h deleted file mode 100644 index 40702ea..0000000 --- a/lib/libhac/include/nn/hac/IdConverter.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once -#include - -namespace nn -{ -namespace hac -{ - class IdConverter - { - public: - static uint64_t convertToAocBaseId(uint64_t application_id); - static uint64_t convertToDeltaId(uint64_t application_id); - static uint64_t convertToPatchId(uint64_t application_id); - - private: - static const uint64_t kAocBaseId = 0x1000; - static const uint64_t kDeltaId = 0xc00; - static const uint64_t kPatchId = 0x800; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/IniHeader.h b/lib/libhac/include/nn/hac/IniHeader.h deleted file mode 100644 index 4463397..0000000 --- a/lib/libhac/include/nn/hac/IniHeader.h +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once -#include -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class IniHeader : - public fnd::IByteModel - { - public: - IniHeader(); - IniHeader(const IniHeader& other); - - void operator=(const IniHeader& other); - bool operator==(const IniHeader& other) const; - bool operator!=(const IniHeader& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* data, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - uint32_t getSize() const; - void setSize(uint32_t size); - - uint32_t getKipNum() const; - void setKipNum(uint32_t num); - private: - const std::string kModuleName = "INI_HEADER"; - - // raw binary - fnd::Vec mRawBinary; - - // variables - uint32_t mSize; - uint32_t mKipNum; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/InteruptEntry.h b/lib/libhac/include/nn/hac/InteruptEntry.h deleted file mode 100644 index 9998fb6..0000000 --- a/lib/libhac/include/nn/hac/InteruptEntry.h +++ /dev/null @@ -1,58 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class InteruptEntry - { - public: - static const uint32_t kInteruptBits = 10; - static const uint32_t kInteruptMax = BIT(kInteruptBits) - 1; - static const uint32_t kInteruptNum = 2; - - InteruptEntry(); - InteruptEntry(const KernelCapabilityEntry& kernel_cap); - InteruptEntry(uint32_t interupt0, uint32_t interupt1); - - void operator=(const InteruptEntry& other); - bool operator==(const InteruptEntry& other) const; - bool operator!=(const InteruptEntry& other) const; - - // kernel capability - const KernelCapabilityEntry& getKernelCapability() const; - void setKernelCapability(const KernelCapabilityEntry& kernel_cap); - - // variables - uint32_t operator[](size_t index) const; - - uint32_t getInterupt(size_t index) const; - void setInterupt(size_t index, uint32_t interupt); - - private: - const std::string kModuleName = "INTERUPT_ENTRY"; - static const kc::KernelCapId kCapId = kc::KC_ENABLE_INTERUPTS; - - KernelCapabilityEntry mCap; - uint32_t mInterupt[kInteruptNum]; - - inline void updateCapField() - { - uint32_t field = 0; - field |= (uint32_t)(mInterupt[0] & kInteruptMax) << 0; - field |= (uint32_t)(mInterupt[1] & kInteruptMax) << kInteruptBits; - mCap.setField(field); - } - - inline void processCapField() - { - uint32_t field = mCap.getField(); - mInterupt[0] = (field >> 0) & kInteruptMax; - mInterupt[1] = (field >> kInteruptBits) & kInteruptMax; - } - }; -} -} diff --git a/lib/libhac/include/nn/hac/InteruptHandler.h b/lib/libhac/include/nn/hac/InteruptHandler.h deleted file mode 100644 index 156b992..0000000 --- a/lib/libhac/include/nn/hac/InteruptHandler.h +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once -#include -#include - -namespace nn -{ -namespace hac -{ - class InteruptHandler : - public IKernelCapabilityHandler - { - public: - InteruptHandler(); - - void operator=(const InteruptHandler& other); - bool operator==(const InteruptHandler& other) const; - bool operator!=(const InteruptHandler& other) const; - - // kernel capabilty list in/out - void importKernelCapabilityList(const fnd::List& caps); - void exportKernelCapabilityList(fnd::List& caps) const; - void clear(); - bool isSet() const; - - // variables - const fnd::List& getInteruptList() const; - void setInteruptList(const fnd::List& interupts); - - private: - const std::string kModuleName = "INTERUPT_HANDLER"; - - bool mIsSet; - fnd::List mInterupts; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/KernelCapabilityControl.h b/lib/libhac/include/nn/hac/KernelCapabilityControl.h deleted file mode 100644 index 475c2c2..0000000 --- a/lib/libhac/include/nn/hac/KernelCapabilityControl.h +++ /dev/null @@ -1,78 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class KernelCapabilityControl : - public fnd::IByteModel - { - public: - KernelCapabilityControl(); - KernelCapabilityControl(const KernelCapabilityControl& other); - - void operator=(const KernelCapabilityControl& other); - bool operator==(const KernelCapabilityControl& other) const; - bool operator!=(const KernelCapabilityControl& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* bytes, size_t len); - virtual const fnd::Vec& getBytes() const; - - // variables (consider further abstraction?) - void clear(); - const ThreadInfoHandler& getThreadInfo() const; - ThreadInfoHandler& getThreadInfo(); - - const SystemCallHandler& getSystemCalls() const; - SystemCallHandler& getSystemCalls(); - - const MemoryMappingHandler& getMemoryMaps() const; - MemoryMappingHandler& getMemoryMaps(); - - const InteruptHandler& getInterupts() const; - InteruptHandler& getInterupts(); - - const MiscParamsHandler& getMiscParams() const; - MiscParamsHandler& getMiscParams(); - - const KernelVersionHandler& getKernelVersion() const; - KernelVersionHandler& getKernelVersion(); - - const HandleTableSizeHandler& getHandleTableSize() const; - HandleTableSizeHandler& getHandleTableSize(); - - const MiscFlagsHandler& getMiscFlags() const; - MiscFlagsHandler& getMiscFlags(); - - private: - const std::string kModuleName = "KERNEL_CAPABILITY_CONTROL"; - - // raw binary - fnd::Vec mRawBinary; - - // variables - ThreadInfoHandler mThreadInfo; - SystemCallHandler mSystemCalls; - MemoryMappingHandler mMemoryMap; - InteruptHandler mInterupts; - MiscParamsHandler mMiscParams; - KernelVersionHandler mKernelVersion; - HandleTableSizeHandler mHandleTableSize; - MiscFlagsHandler mMiscFlags; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/KernelCapabilityEntry.h b/lib/libhac/include/nn/hac/KernelCapabilityEntry.h deleted file mode 100644 index 2df6ef3..0000000 --- a/lib/libhac/include/nn/hac/KernelCapabilityEntry.h +++ /dev/null @@ -1,57 +0,0 @@ -#pragma once -#include -#include - -namespace nn -{ -namespace hac -{ - class KernelCapabilityEntry - { - public: - - KernelCapabilityEntry(); - KernelCapabilityEntry(kc::KernelCapId type); - KernelCapabilityEntry(kc::KernelCapId type, uint32_t field); - - void operator=(const KernelCapabilityEntry& other); - bool operator==(const KernelCapabilityEntry& other) const; - bool operator!=(const KernelCapabilityEntry& other) const; - - uint32_t getCap() const; - void setCap(uint32_t cap); - - kc::KernelCapId getType() const; - void setType(kc::KernelCapId type); - - uint32_t getField() const; - void setField(uint32_t field); - - private: - kc::KernelCapId mType; - uint32_t mField; - - inline uint32_t getFieldShift() const { return mType + 1; } - inline uint32_t getFieldMask() const { return BIT(31 - mType) - 1; } - inline uint32_t getCapMask() const { return BIT(mType) - 1; } - inline kc::KernelCapId getCapId(uint32_t cap) const - { - kc::KernelCapId id = kc::KC_INVALID; - - for (byte_t tmp = 0; tmp < 31; tmp++) - { - if (((cap >> tmp) & 1) == 0) - { - id = (kc::KernelCapId)tmp; - break; - } - } - - if (id == kc::KC_INVALID && cap == (uint32_t)0xffffffff) - id = kc::KC_STUB; - - return id; - } - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/KernelInitialProcessHeader.h b/lib/libhac/include/nn/hac/KernelInitialProcessHeader.h deleted file mode 100644 index cf476a6..0000000 --- a/lib/libhac/include/nn/hac/KernelInitialProcessHeader.h +++ /dev/null @@ -1,137 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class KernelInitialProcessHeader : - public fnd::IByteModel - { - public: - struct sLayout - { - uint32_t offset; - uint32_t size; - - void operator=(const sLayout& other) - { - offset = other.offset; - size = other.size; - } - - bool operator==(const sLayout& other) const - { - return (offset == other.offset) \ - && (size == other.size); - } - - bool operator!=(const sLayout& other) const - { - return !(*this == other); - } - }; - - struct sCodeSegment - { - sLayout file_layout; - sLayout memory_layout; - bool is_compressed; - - void operator=(const sCodeSegment& other) - { - file_layout = other.file_layout; - memory_layout = other.memory_layout; - is_compressed = other.is_compressed; - } - - bool operator==(const sCodeSegment& other) const - { - return (file_layout == other.file_layout) \ - && (memory_layout == other.memory_layout) \ - && (is_compressed == other.is_compressed); - } - - bool operator!=(const sCodeSegment& other) const - { - return !(*this == other); - } - }; - - KernelInitialProcessHeader(); - KernelInitialProcessHeader(const KernelInitialProcessHeader& other); - - void operator=(const KernelInitialProcessHeader& other); - bool operator==(const KernelInitialProcessHeader& other) const; - bool operator!=(const KernelInitialProcessHeader& other) const; - - // export/import binary - void toBytes(); - void fromBytes(const byte_t* data, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - const std::string& getName() const; - void setName(const std::string& name); - - uint64_t getTitleId() const; - void setTitleId(uint64_t title_id); - - kip::ProcessCategory getProcessCategory() const; - void setProcessCategory(kip::ProcessCategory cat); - - const fnd::List& getFlagList() const; - void setFlagList(const fnd::List& flags); - - byte_t getMainThreadPriority() const; - void setMainThreadPriority(byte_t priority); - - byte_t getMainThreadCpuId() const; - void setMainThreadCpuId(byte_t cpu_id); - - uint32_t getMainThreadStackSize() const; - void setMainThreadStackSize(uint32_t size); - - const sCodeSegment& getTextSegmentInfo() const; - void setTextSegmentInfo(const sCodeSegment& info); - - const sCodeSegment& getRoSegmentInfo() const; - void setRoSegmentInfo(const sCodeSegment& info); - - const sCodeSegment& getDataSegmentInfo() const; - void setDataSegmentInfo(const sCodeSegment& info); - - uint32_t getBssSize() const; - void setBssSize(uint32_t size); - - const nn::hac::KernelCapabilityControl& getKernelCapabilities() const; - void setKernelCapabilities(const KernelCapabilityControl& kc); - - private: - const std::string kModuleName = "KERNEL_INITIAL_PROCESS_HEADER"; - - // raw binary - fnd::Vec mRawBinary; - - // variables - std::string mName; - uint64_t mTitleId; - kip::ProcessCategory mProcessCategory; - fnd::List mFlagList; - byte_t mMainThreadPriority; - byte_t mMainThreadCpuId; - uint32_t mMainThreadStackSize; - sCodeSegment mTextInfo; - sCodeSegment mRoInfo; - sCodeSegment mDataInfo; - uint32_t mBssSize; - nn::hac::KernelCapabilityControl mKernelCapabilities; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/KernelVersionEntry.h b/lib/libhac/include/nn/hac/KernelVersionEntry.h deleted file mode 100644 index ed52714..0000000 --- a/lib/libhac/include/nn/hac/KernelVersionEntry.h +++ /dev/null @@ -1,58 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class KernelVersionEntry - { - public: - KernelVersionEntry(); - KernelVersionEntry(const KernelCapabilityEntry& kernel_cap); - KernelVersionEntry(uint16_t major, uint8_t minor); - - void operator=(const KernelVersionEntry& other); - bool operator==(const KernelVersionEntry& other) const; - bool operator!=(const KernelVersionEntry& other) const; - - // kernel capability - const KernelCapabilityEntry& getKernelCapability() const; - void setKernelCapability(const KernelCapabilityEntry& kernel_cap); - - // variables - uint16_t getVerMajor() const; - void setVerMajor(uint16_t major); - uint8_t getVerMinor() const; - void setVerMinor(uint8_t minor); - private: - const std::string kModuleName = "KERNEL_VERSION_ENTRY"; - static const kc::KernelCapId kCapId = kc::KC_KERNEL_VERSION; - static const uint32_t kVerMajorBits = 13; - static const uint32_t kVerMajorMax = BIT(kVerMajorBits) - 1; - static const uint32_t kVerMinorBits = 4; - static const uint32_t kVerMinorMax = BIT(kVerMinorBits) - 1; - - KernelCapabilityEntry mCap; - uint16_t mVerMajor; - uint8_t mVerMinor; - - inline void updateCapField() - { - uint32_t field = 0; - field |= (uint32_t)(mVerMinor & kVerMinorMax) << 0; - field |= (uint32_t)(mVerMajor & kVerMajorMax) << kVerMinorBits; - mCap.setField(field); - } - - inline void processCapField() - { - uint32_t field = mCap.getField(); - mVerMinor = (field >> 0) & kVerMinorMax; - mVerMajor = (field >> kVerMinorBits) & kVerMajorMax; - } - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/KernelVersionHandler.h b/lib/libhac/include/nn/hac/KernelVersionHandler.h deleted file mode 100644 index fe43226..0000000 --- a/lib/libhac/include/nn/hac/KernelVersionHandler.h +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once -#include -#include - -namespace nn -{ -namespace hac -{ - class KernelVersionHandler : - public IKernelCapabilityHandler - { - public: - KernelVersionHandler(); - - void operator=(const KernelVersionHandler& other); - bool operator==(const KernelVersionHandler& other) const; - bool operator!=(const KernelVersionHandler& other) const; - - // kernel capabilty list in/out - void importKernelCapabilityList(const fnd::List& caps); - void exportKernelCapabilityList(fnd::List& caps) const; - void clear(); - bool isSet() const; - - // variables - uint16_t getVerMajor() const; - void setVerMajor(uint16_t major); - uint8_t getVerMinor() const; - void setVerMinor(uint8_t minor); - - private: - const std::string kModuleName = "KERNEL_VERSION_HANDLER"; - static const size_t kMaxKernelCapNum = 1; - - bool mIsSet; - KernelVersionEntry mEntry; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/MemoryMappingHandler.h b/lib/libhac/include/nn/hac/MemoryMappingHandler.h deleted file mode 100644 index d4d73d7..0000000 --- a/lib/libhac/include/nn/hac/MemoryMappingHandler.h +++ /dev/null @@ -1,80 +0,0 @@ -#pragma once -#include - -namespace nn -{ -namespace hac -{ - class MemoryMappingHandler : - public IKernelCapabilityHandler - { - public: - enum MemoryPerm - { - MEM_RW, - MEM_RO - }; - - enum MappingType - { - MAP_IO, - MAP_STATIC - }; - - struct sMemoryMapping - { - uint32_t addr; // page index - uint32_t size; // page num - MemoryPerm perm; - MappingType type; - - bool operator==(const sMemoryMapping& other) const - { - return (addr == other.addr) \ - && (size == other.size) \ - && (perm == other.perm) \ - && (type == other.type); - } - - bool operator!=(const sMemoryMapping& other) const - { - return !operator==(other); - } - - const sMemoryMapping& operator=(const sMemoryMapping& other) - { - addr = other.addr; - size = other.size; - perm = other.perm; - type = other.type; - - return *this; - } - }; - - MemoryMappingHandler(); - - void operator=(const MemoryMappingHandler& other); - bool operator==(const MemoryMappingHandler& other) const; - bool operator!=(const MemoryMappingHandler& other) const; - - // kernel capabilty list in/out - void importKernelCapabilityList(const fnd::List& caps); - void exportKernelCapabilityList(fnd::List& caps) const; - void clear(); - bool isSet() const; - - const fnd::List& getMemoryMaps() const; - const fnd::List& getIoMemoryMaps() const; - - private: - const std::string kModuleName = "MEMORY_MAPPING_HANDLER"; - static const uint32_t kMaxPageAddr = BIT(24) - 1; - static const uint32_t kMaxPageNum = BIT(20) - 1; - - bool mIsSet; - fnd::List mMemRange; - fnd::List mMemPage; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/MemoryPageEntry.h b/lib/libhac/include/nn/hac/MemoryPageEntry.h deleted file mode 100644 index 368b233..0000000 --- a/lib/libhac/include/nn/hac/MemoryPageEntry.h +++ /dev/null @@ -1,62 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class MemoryPageEntry - { - public: - MemoryPageEntry(); - MemoryPageEntry(const KernelCapabilityEntry& kernel_cap); - MemoryPageEntry(uint32_t page); - MemoryPageEntry(uint32_t page, bool flag); - - void operator=(const MemoryPageEntry& other); - bool operator==(const MemoryPageEntry& other) const; - bool operator!=(const MemoryPageEntry& other) const; - - // kernel capability - const KernelCapabilityEntry& getKernelCapability() const; - void setKernelCapability(const KernelCapabilityEntry& kernel_cap); - - // variables - uint32_t getPage() const; - void setPage(uint32_t page); - bool getFlag() const; - void setFlag(bool flag); - - bool isMultiplePages() const; - void setMapMultiplePages(bool useFlag); - private: - const std::string kModuleName = "MEMORY_PAGE_ENTRY"; - static const uint32_t kPageBits = 24; - static const uint32_t kMaxPage = BIT(kPageBits) - 1; - - KernelCapabilityEntry mCap; - uint32_t mPage; - bool mFlag; - bool mUseFlag; - - inline void updateCapField() - { - uint32_t field = 0; - field |= (uint32_t)(mPage & kMaxPage) << 0; - field |= (uint32_t)(mFlag) << kPageBits; - mCap.setField(field); - mCap.setType(mUseFlag ? kc::KC_MEMORY_MAP : kc::KC_IO_MEMORY_MAP); - } - - inline void processCapField() - { - uint32_t field = mCap.getField(); - mPage = (field >> 0) & kMaxPage; - mFlag = (field >> kPageBits); - mUseFlag = mCap.getType() == kc::KC_MEMORY_MAP; - } - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/Meta.h b/lib/libhac/include/nn/hac/Meta.h deleted file mode 100644 index 40a6905..0000000 --- a/lib/libhac/include/nn/hac/Meta.h +++ /dev/null @@ -1,80 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class Meta : - public fnd::IByteModel - { - public: - Meta(); - Meta(const Meta& other); - - void operator=(const Meta& other); - bool operator==(const Meta& other) const; - bool operator!=(const Meta& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* bytes, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - meta::InstructionType getInstructionType() const; - void setInstructionType(meta::InstructionType type); - - meta::ProcAddrSpaceType getProcAddressSpaceType() const; - void setProcAddressSpaceType(meta::ProcAddrSpaceType type); - - byte_t getMainThreadPriority() const; - void setMainThreadPriority(byte_t priority); - - byte_t getMainThreadCpuId() const; - void setMainThreadCpuId(byte_t cpu_id); - - uint32_t getVersion() const; - void setVersion(uint32_t version); - - uint32_t getMainThreadStackSize() const; - void setMainThreadStackSize(uint32_t size); - - const std::string& getName() const; - void setName(const std::string& name); - - const std::string& getProductCode() const; - void setProductCode(const std::string& product_code); - - const AccessControlInfo& getAci() const; - void setAci(const AccessControlInfo& aci); - - const AccessControlInfoDesc& getAcid() const; - void setAcid(const AccessControlInfoDesc& acid); - private: - const std::string kModuleName = "META"; - - // raw binary - fnd::Vec mRawBinary; - - // variables - meta::InstructionType mInstructionType; - meta::ProcAddrSpaceType mProcAddressSpaceType; - byte_t mMainThreadPriority; - byte_t mMainThreadCpuId; - uint32_t mVersion; - uint32_t mMainThreadStackSize; - std::string mName; - std::string mProductCode; - AccessControlInfo mAci; - AccessControlInfoDesc mAcid; - }; -} -} diff --git a/lib/libhac/include/nn/hac/MiscFlagsEntry.h b/lib/libhac/include/nn/hac/MiscFlagsEntry.h deleted file mode 100644 index 359589c..0000000 --- a/lib/libhac/include/nn/hac/MiscFlagsEntry.h +++ /dev/null @@ -1,50 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class MiscFlagsEntry - { - public: - MiscFlagsEntry(); - MiscFlagsEntry(const KernelCapabilityEntry& kernel_cap); - MiscFlagsEntry(uint32_t flags); - - void operator=(const MiscFlagsEntry& other); - bool operator==(const MiscFlagsEntry& other) const; - bool operator!=(const MiscFlagsEntry& other) const; - - // kernel capability - const KernelCapabilityEntry& getKernelCapability() const; - void setKernelCapability(const KernelCapabilityEntry& kernel_cap); - - // variables - uint32_t getFlags() const; - void setFlags(uint32_t flags); - private: - const std::string kModuleName = "MISC_FLAG_ENTRY"; - static const kc::KernelCapId kCapId = kc::KC_MISC_FLAGS; - static const uint32_t kValueBits = 15; - static const uint32_t kMaxVal = BIT(kValueBits)-1; - - KernelCapabilityEntry mCap; - uint32_t mFlags; - - inline void updateCapField() - { - uint32_t field = mFlags & kMaxVal; - mCap.setField(field); - } - - inline void processCapField() - { - uint32_t field = mCap.getField(); - mFlags = field & kMaxVal; - } - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/MiscFlagsHandler.h b/lib/libhac/include/nn/hac/MiscFlagsHandler.h deleted file mode 100644 index 8351120..0000000 --- a/lib/libhac/include/nn/hac/MiscFlagsHandler.h +++ /dev/null @@ -1,57 +0,0 @@ -#pragma once -#include -#include - -namespace nn -{ -namespace hac -{ - class MiscFlagsHandler : - public IKernelCapabilityHandler - { - public: - enum Flags - { - FLAG_ENABLE_DEBUG, - FLAG_FORCE_DEBUG, - FLAG_UNK02, - FLAG_UNK03, - FLAG_UNK04, - FLAG_UNK05, - FLAG_UNK06, - FLAG_UNK07, - FLAG_UNK08, - FLAG_UNK09, - FLAG_UNK10, - FLAG_UNK11, - FLAG_UNK12, - FLAG_UNK13, - FLAG_UNK14, - FLAG_NUM - }; - - MiscFlagsHandler(); - - void operator=(const MiscFlagsHandler& other); - bool operator==(const MiscFlagsHandler& other) const; - bool operator!=(const MiscFlagsHandler& other) const; - - // kernel capabilty list in/out - void importKernelCapabilityList(const fnd::List& caps); - void exportKernelCapabilityList(fnd::List& caps) const; - void clear(); - bool isSet() const; - - // variables - const fnd::List& getFlagList() const; - void setFlagList(fnd::List flags); - - private: - const std::string kModuleName = "MISC_FLAGS_HANDLER"; - static const size_t kMaxKernelCapNum = 1; - - bool mIsSet; - fnd::List mFlags; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/MiscParamsEntry.h b/lib/libhac/include/nn/hac/MiscParamsEntry.h deleted file mode 100644 index 0925d16..0000000 --- a/lib/libhac/include/nn/hac/MiscParamsEntry.h +++ /dev/null @@ -1,50 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class MiscParamsEntry - { - public: - MiscParamsEntry(); - MiscParamsEntry(const KernelCapabilityEntry& kernel_cap); - MiscParamsEntry(byte_t program_type); - - void operator=(const MiscParamsEntry& other); - bool operator==(const MiscParamsEntry& other) const; - bool operator!=(const MiscParamsEntry& other) const; - - // kernel capability - const KernelCapabilityEntry& getKernelCapability() const; - void setKernelCapability(const KernelCapabilityEntry& kernel_cap); - - // variables - byte_t getProgramType() const; - void setProgramType(byte_t type); - private: - const std::string kModuleName = "MISC_PARAMS_ENTRY"; - static const kc::KernelCapId kCapId = kc::KC_MISC_PARAMS; - static const byte_t kValBits = 3; - static const byte_t kMaxProgramType = BIT(kValBits)-1; - - KernelCapabilityEntry mCap; - byte_t mProgramType; - - inline void updateCapField() - { - uint32_t field = mProgramType & kMaxProgramType; - mCap.setField(field); - } - - inline void processCapField() - { - uint32_t field = mCap.getField(); - mProgramType = field & kMaxProgramType; - } - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/MiscParamsHandler.h b/lib/libhac/include/nn/hac/MiscParamsHandler.h deleted file mode 100644 index 063a22c..0000000 --- a/lib/libhac/include/nn/hac/MiscParamsHandler.h +++ /dev/null @@ -1,37 +0,0 @@ -#pragma once -#include -#include - -namespace nn -{ -namespace hac -{ - class MiscParamsHandler : - public IKernelCapabilityHandler - { - public: - MiscParamsHandler(); - - void operator=(const MiscParamsHandler& other); - bool operator==(const MiscParamsHandler& other) const; - bool operator!=(const MiscParamsHandler& other) const; - - // kernel capabilty list in/out - void importKernelCapabilityList(const fnd::List& caps); - void exportKernelCapabilityList(fnd::List& caps) const; - void clear(); - bool isSet() const; - - // variables - byte_t getProgramType() const; - void setProgramType(byte_t type); - - private: - const std::string kModuleName = "MISC_PARAMS_HANDLER"; - static const size_t kMaxKernelCapNum = 1; - - bool mIsSet; - MiscParamsEntry mEntry; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/NroHeader.h b/lib/libhac/include/nn/hac/NroHeader.h deleted file mode 100644 index 9f8fff1..0000000 --- a/lib/libhac/include/nn/hac/NroHeader.h +++ /dev/null @@ -1,141 +0,0 @@ -#pragma once -#include -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class NroHeader : - public fnd::IByteModel - { - public: - struct sRoCrt - { - byte_t data[nro::kRoCrtSize]; - - void operator=(const sRoCrt& other) - { - memcpy(data, other.data, nro::kRoCrtSize); - } - - bool operator==(const sRoCrt& other) const - { - return memcmp(data, other.data, nro::kRoCrtSize) == 0; - } - - bool operator!=(const sRoCrt& other) const - { - return !(*this == other); - } - }; - - struct sModuleId - { - byte_t data[nro::kModuleIdSize]; - - void operator=(const sModuleId& other) - { - memcpy(data, other.data, nro::kModuleIdSize); - } - - bool operator==(const sModuleId& other) const - { - return memcmp(data, other.data, nro::kModuleIdSize) == 0; - } - - bool operator!=(const sModuleId& other) const - { - return !(*this == other); - } - }; - - struct sSection - { - uint32_t memory_offset; - uint32_t size; - - void operator=(const sSection& other) - { - memory_offset = other.memory_offset; - size = other.size; - } - - bool operator==(const sSection& other) const - { - return (memory_offset == other.memory_offset) \ - && (size == other.size); - } - - bool operator!=(const sSection& other) const - { - return !(*this == other); - } - }; - - NroHeader(); - NroHeader(const NroHeader& other); - - void operator=(const NroHeader& other); - bool operator==(const NroHeader& other) const; - bool operator!=(const NroHeader& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* bytes, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - const sRoCrt& getRoCrt() const; - void setRoCrt(const sRoCrt& ro_crt); - - uint32_t getNroSize() const; - void setNroSize(uint32_t size); - - const sSection& getTextInfo() const; - void setTextInfo(const sSection& info); - - const sSection& getRoInfo() const; - void setRoInfo(const sSection& info); - - const sSection& getDataInfo() const; - void setDataInfo(const sSection& info); - - uint32_t getBssSize() const; - void setBssSize(uint32_t size); - - const sModuleId& getModuleId() const; - void setModuleId(const sModuleId& id); - - const sSection& getRoEmbeddedInfo() const; - void setRoEmbeddedInfo(const sSection& info); - - const sSection& getRoDynStrInfo() const; - void setRoDynStrInfo(const sSection& info); - - const sSection& getRoDynSymInfo() const; - void setRoDynSymInfo(const sSection& info); - private: - const std::string kModuleName = "NRO_HEADER"; - - // binary - fnd::Vec mRawBinary; - - // data - sRoCrt mRoCrt; - uint32_t mNroSize; - sSection mTextInfo; - sSection mRoInfo; - sSection mDataInfo; - uint32_t mBssSize; - sModuleId mModuleId; - sSection mRoEmbeddedInfo; - sSection mRoDynStrInfo; - sSection mRoDynSymInfo; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/NsoHeader.h b/lib/libhac/include/nn/hac/NsoHeader.h deleted file mode 100644 index 5fc4706..0000000 --- a/lib/libhac/include/nn/hac/NsoHeader.h +++ /dev/null @@ -1,149 +0,0 @@ -#pragma once -#include -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class NsoHeader : - public fnd::IByteModel - { - public: - struct sModuleId - { - byte_t data[nso::kModuleIdSize]; - - void operator=(const sModuleId& other) - { - memcpy(data, other.data, nso::kModuleIdSize); - } - - bool operator==(const sModuleId& other) const - { - return memcmp(data, other.data, nso::kModuleIdSize) == 0; - } - - bool operator!=(const sModuleId& other) const - { - return !(*this == other); - } - }; - - struct sLayout - { - uint32_t offset; - uint32_t size; - - void operator=(const sLayout& other) - { - offset = other.offset; - size = other.size; - } - - bool operator==(const sLayout& other) const - { - return (offset == other.offset) \ - && (size == other.size); - } - - bool operator!=(const sLayout& other) const - { - return !(*this == other); - } - }; - - struct sCodeSegment - { - sLayout file_layout; - sLayout memory_layout; - bool is_compressed; - bool is_hashed; - fnd::sha::sSha256Hash hash; - - void operator=(const sCodeSegment& other) - { - file_layout = other.file_layout; - memory_layout = other.memory_layout; - is_compressed = other.is_compressed; - is_hashed = other.is_hashed; - hash = other.hash; - } - - bool operator==(const sCodeSegment& other) const - { - return (file_layout == other.file_layout) \ - && (memory_layout == other.memory_layout) \ - && (is_compressed == other.is_compressed) \ - && (is_hashed == other.is_hashed) \ - && (hash == other.hash); - } - - bool operator!=(const sCodeSegment& other) const - { - return !(*this == other); - } - }; - - NsoHeader(); - NsoHeader(const NsoHeader& other); - - void operator=(const NsoHeader& other); - bool operator==(const NsoHeader& other) const; - bool operator!=(const NsoHeader& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* bytes, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - const sModuleId& getModuleId() const; - void setModuleId(const sModuleId& id); - - uint32_t getBssSize() const; - void setBssSize(uint32_t size); - - const sCodeSegment& getTextSegmentInfo() const; - void setTextSegmentInfo(const sCodeSegment& info); - - const sCodeSegment& getRoSegmentInfo() const; - void setRoSegmentInfo(const sCodeSegment& info); - - const sCodeSegment& getDataSegmentInfo() const; - void setDataSegmentInfo(const sCodeSegment& info); - - const sLayout& getModuleNameInfo() const; - void setModuleNameInfo(const sLayout& info); - - const sLayout& getRoEmbeddedInfo() const; - void setRoEmbeddedInfo(const sLayout& info); - - const sLayout& getRoDynStrInfo() const; - void setRoDynStrInfo(const sLayout& info); - - const sLayout& getRoDynSymInfo() const; - void setRoDynSymInfo(const sLayout& info); - private: - const std::string kModuleName = "NSO_HEADER"; - - // binary - fnd::Vec mRawBinary; - - // data - sModuleId mModuleId; - uint32_t mBssSize; - sCodeSegment mTextSegmentInfo; - sCodeSegment mRoSegmentInfo; - sCodeSegment mDataSegmentInfo; - sLayout mModuleNameInfo; - sLayout mRoEmbeddedInfo; - sLayout mRoDynStrInfo; - sLayout mRoDynSymInfo; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/PartitionFsHeader.h b/lib/libhac/include/nn/hac/PartitionFsHeader.h deleted file mode 100644 index 7c33f6d..0000000 --- a/lib/libhac/include/nn/hac/PartitionFsHeader.h +++ /dev/null @@ -1,100 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class PartitionFsHeader : - public fnd::IByteModel - { - public: - enum FsType - { - TYPE_PFS0, - TYPE_HFS0 - }; - - struct sFile - { - std::string name; - size_t offset; - size_t size; - size_t hash_protected_size; - fnd::sha::sSha256Hash hash; - - sFile& operator=(const sFile& other) - { - name = other.name; - offset = other.offset; - size = other.size; - hash_protected_size = other.hash_protected_size; - hash = other.hash; - return *this; - } - - bool operator==(const sFile& other) const - { - return (name == other.name) \ - && (offset == other.offset) \ - && (size == other.size) \ - && (hash_protected_size == other.hash_protected_size) \ - && (hash == other.hash); - } - - bool operator!=(const sFile& other) const - { - return !operator==(other); - } - - bool operator==(const std::string& other) const - { - return (name == other); - } - - bool operator!=(const std::string& other) const - { - return !operator==(other); - } - }; - - PartitionFsHeader(); - PartitionFsHeader(const PartitionFsHeader& other); - - void operator=(const PartitionFsHeader& other); - bool operator==(const PartitionFsHeader& other) const; - bool operator!=(const PartitionFsHeader& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* bytes, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - FsType getFsType() const; - void setFsType(FsType type); - const fnd::List& getFileList() const; - void addFile(const std::string& name, size_t size); - void addFile(const std::string& name, size_t size, size_t hash_protected_size, const fnd::sha::sSha256Hash& hash); - - private: - const std::string kModuleName = "PARTITIONFS_HEADER"; - - // binary blob - fnd::Vec mRawBinary; - - // variables - FsType mFsType; - fnd::List mFileList; - - size_t getFileEntrySize(FsType fs_type); - void calculateOffsets(size_t data_offset); - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/PatchMetaExtendedHeader.h b/lib/libhac/include/nn/hac/PatchMetaExtendedHeader.h deleted file mode 100644 index da1aa9b..0000000 --- a/lib/libhac/include/nn/hac/PatchMetaExtendedHeader.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once -#include -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class PatchMetaExtendedHeader : - public fnd::IByteModel - { - public: - PatchMetaExtendedHeader(); - PatchMetaExtendedHeader(const PatchMetaExtendedHeader& other); - - void operator=(const PatchMetaExtendedHeader& other); - bool operator==(const PatchMetaExtendedHeader& other) const; - bool operator!=(const PatchMetaExtendedHeader& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* bytes, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - uint64_t getApplicationId() const; - void setApplicationId(uint64_t application_id); - - uint32_t getRequiredSystemVersion() const; - void setRequiredSystemVersion(uint32_t sys_ver); - - uint32_t getExtendedDataSize() const; - void setExtendedDataSize(uint32_t size); - - private: - const std::string kModuleName = "PATCH_META_EXTENDED_HEADER"; - - // binary blob - fnd::Vec mRawBinary; - - // variables - uint64_t mApplicationId; - uint32_t mRequiredSystemVersion; - uint32_t mExtendedDataSize; - }; -} -} diff --git a/lib/libhac/include/nn/hac/Result.h b/lib/libhac/include/nn/hac/Result.h deleted file mode 100644 index f13587a..0000000 --- a/lib/libhac/include/nn/hac/Result.h +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once -#include - -namespace nn -{ -namespace hac -{ - class Result - { - public: - Result(); - Result(uint32_t result); - Result(uint32_t module_num, uint32_t desc, uint32_t sub_desc); - - void operator=(const Result& other); - bool operator==(const Result& other) const; - bool operator!=(const Result& other) const; - - bool isSuccess() const; - bool isFailure() const; - - uint32_t getInnerValue() const; - uint32_t getModuleNum() const; - uint32_t getDescription() const; - uint32_t getSubDescription() const; - - private: - static const uint32_t kModuleNumBitWidth = 9; - static const uint32_t kModuleNumBitPos = 0; - static const uint32_t kDescriptionBitWidth = 13; - static const uint32_t kDescriptionBitPos = 9; - static const uint32_t kSubDescriptionBitWidth = 10; - static const uint32_t kSubDescriptionBitPos = 22; - inline uint32_t bitWidthToMask(uint32_t bit_width) const { return _BIT(bit_width) - 1; } - - uint32_t mResult; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/ServiceAccessControl.h b/lib/libhac/include/nn/hac/ServiceAccessControl.h deleted file mode 100644 index e808276..0000000 --- a/lib/libhac/include/nn/hac/ServiceAccessControl.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class ServiceAccessControl : - public fnd::IByteModel - { - public: - ServiceAccessControl(); - ServiceAccessControl(const ServiceAccessControl& other); - - void operator=(const ServiceAccessControl& other); - bool operator==(const ServiceAccessControl& other) const; - bool operator!=(const ServiceAccessControl& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* bytes, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - const fnd::List& getServiceList() const; - void setServiceList(const fnd::List& list); - private: - const std::string kModuleName = "SERVICE_ACCESS_CONTROL"; - - // raw binary - fnd::Vec mRawBinary; - - // variables - fnd::List mServices; - }; -} -} diff --git a/lib/libhac/include/nn/hac/ServiceAccessControlEntry.h b/lib/libhac/include/nn/hac/ServiceAccessControlEntry.h deleted file mode 100644 index 441682e..0000000 --- a/lib/libhac/include/nn/hac/ServiceAccessControlEntry.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class ServiceAccessControlEntry : - public fnd::IByteModel - { - public: - ServiceAccessControlEntry(); - ServiceAccessControlEntry(const std::string& name, bool isServer); - ServiceAccessControlEntry(const ServiceAccessControlEntry& other); - - void operator=(const ServiceAccessControlEntry& other); - bool operator==(const ServiceAccessControlEntry& other) const; - bool operator!=(const ServiceAccessControlEntry& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* bytes, size_t len); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - bool isServer() const; - void setIsServer(bool isServer); - const std::string& getName() const; - void setName(const std::string& name); - private: - const std::string kModuleName = "SERVICE_ACCESS_CONTROL_ENTRY"; - static const size_t kMaxServiceNameLen = 8; - - enum ServiceAccessControlEntryFlag - { - SAC_IS_SERVER = _BIT(7), - SAC_NAME_LEN_MASK = _BIT(7) - 1 - }; - - // raw binary - fnd::Vec mRawBinary; - - // variables - bool mIsServer; - std::string mName; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/SystemCallEntry.h b/lib/libhac/include/nn/hac/SystemCallEntry.h deleted file mode 100644 index 3eb0b0a..0000000 --- a/lib/libhac/include/nn/hac/SystemCallEntry.h +++ /dev/null @@ -1,59 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class SystemCallEntry - { - public: - SystemCallEntry(); - SystemCallEntry(const KernelCapabilityEntry& kernel_cap); - SystemCallEntry(uint32_t upper_bits, uint32_t lower_bits); - - void operator=(const SystemCallEntry& other); - bool operator==(const SystemCallEntry& other) const; - bool operator!=(const SystemCallEntry& other) const; - - // kernel capability - const KernelCapabilityEntry& getKernelCapability() const; - void setKernelCapability(const KernelCapabilityEntry& kernel_cap); - - // variables - uint32_t getSystemCallUpperBits() const; - void setSystemCallUpperBits(uint32_t upper_bits); - uint32_t getSystemCallLowerBits() const; - void setSystemCallLowerBits(uint32_t lower_bits); - - private: - const std::string kModuleName = "SYSTEM_CALL_ENTRY"; - static const kc::KernelCapId kCapId = kc::KC_ENABLE_SYSTEM_CALLS; - static const uint32_t kSysCallUpperBits = 3; - static const uint32_t kSysCallLowerBits = 24; - static const uint32_t kSysCallUpperMax = BIT(kSysCallUpperBits) - 1; - static const uint32_t kSysCallLowerMax = BIT(kSysCallLowerBits) - 1; - - KernelCapabilityEntry mCap; - uint32_t mSystemCallUpper; - uint32_t mSystemCallLower; - - inline void updateCapField() - { - uint32_t field = 0; - field |= (uint32_t)(mSystemCallLower & kSysCallLowerMax) << 0; - field |= (uint32_t)(mSystemCallUpper & kSysCallUpperMax) << kSysCallLowerBits; - mCap.setField(field); - } - - inline void processCapField() - { - uint32_t field = mCap.getField(); - mSystemCallLower = (field >> 0) & kSysCallLowerMax; - mSystemCallUpper = (field >> kSysCallLowerBits) & kSysCallUpperMax; - } - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/SystemCallHandler.h b/lib/libhac/include/nn/hac/SystemCallHandler.h deleted file mode 100644 index d726d7c..0000000 --- a/lib/libhac/include/nn/hac/SystemCallHandler.h +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once -#include - -namespace nn -{ -namespace hac -{ - class SystemCallHandler : - public IKernelCapabilityHandler - { - public: - static const uint32_t kMaxSystemCall = (BIT(3) * 24) - 1; - - SystemCallHandler(); - - void operator=(const SystemCallHandler& other); - bool operator==(const SystemCallHandler& other) const; - bool operator!=(const SystemCallHandler& other) const; - - // kernel capabilty list in/out - void importKernelCapabilityList(const fnd::List& caps); - void exportKernelCapabilityList(fnd::List& caps) const; - void clear(); - bool isSet() const; - - // variables - const fnd::List& getSystemCalls() const; - void setSystemCallList(const fnd::List& calls); - - private: - const std::string kModuleName = "SYSTEM_CALL_HANDLER"; - static const size_t kSyscallTotalEntryNum = (kMaxSystemCall / 24) + 1; - - bool mIsSet; - fnd::List mSystemCalls; - }; -} -} diff --git a/lib/libhac/include/nn/hac/ThreadInfoEntry.h b/lib/libhac/include/nn/hac/ThreadInfoEntry.h deleted file mode 100644 index 07a3e93..0000000 --- a/lib/libhac/include/nn/hac/ThreadInfoEntry.h +++ /dev/null @@ -1,69 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace hac -{ - class ThreadInfoEntry - { - public: - ThreadInfoEntry(); - ThreadInfoEntry(const KernelCapabilityEntry& kernel_cap); - ThreadInfoEntry(uint8_t min_priority, uint8_t max_priority, uint8_t min_cpu_id, uint8_t max_cpu_id); - - void operator=(const ThreadInfoEntry& other); - bool operator==(const ThreadInfoEntry& other) const; - bool operator!=(const ThreadInfoEntry& other) const; - - // kernel capability - const KernelCapabilityEntry& getKernelCapability() const; - void setKernelCapability(const KernelCapabilityEntry& kernel_cap); - - // variables - uint8_t getMinPriority() const; - void setMinPriority(uint8_t priority); - uint8_t getMaxPriority() const; - void setMaxPriority(uint8_t priority); - uint8_t getMinCpuId() const; - void setMinCpuId(uint8_t cpu_id); - uint8_t getMaxCpuId() const; - void setMaxCpuId(uint8_t cpu_id); - - private: - const std::string kModuleName = "THREAD_INFO_ENTRY"; - static const kc::KernelCapId kCapId = kc::KC_THREAD_INFO; - static const uint8_t kValBits = 6; - static const uint8_t kMaxVal = BIT(kValBits)-1; - static const uint8_t kDefaultPriority = 6; - static const uint8_t kDefaultCpuId = 8; - - KernelCapabilityEntry mCap; - uint8_t mMinPriority; - uint8_t mMaxPriority; - uint8_t mMinCpuId; - uint8_t mMaxCpuId; - - inline void updateCapField() - { - uint32_t field = 0; - field |= (uint32_t)(mMinPriority & kMaxVal) << (kValBits * 0); - field |= (uint32_t)(mMaxPriority & kMaxVal) << (kValBits * 1); - field |= (uint32_t)(mMinCpuId & kMaxVal) << (kValBits * 2); - field |= (uint32_t)(mMaxCpuId & kMaxVal) << (kValBits * 3); - mCap.setField(field); - } - - inline void processCapField() - { - uint32_t field = mCap.getField(); - mMinPriority = (field >> (kValBits * 0)) & kMaxVal; - mMaxPriority = (field >> (kValBits * 1)) & kMaxVal; - mMinCpuId = (field >> (kValBits * 2)) & kMaxVal; - mMaxCpuId = (field >> (kValBits * 3)) & kMaxVal; - } - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/ThreadInfoHandler.h b/lib/libhac/include/nn/hac/ThreadInfoHandler.h deleted file mode 100644 index f7301f6..0000000 --- a/lib/libhac/include/nn/hac/ThreadInfoHandler.h +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once -#include -#include - -namespace nn -{ -namespace hac -{ - class ThreadInfoHandler : - public IKernelCapabilityHandler - { - public: - ThreadInfoHandler(); - - void operator=(const ThreadInfoHandler& other); - bool operator==(const ThreadInfoHandler& other) const; - bool operator!=(const ThreadInfoHandler& other) const; - - // kernel capabilty list in/out - void importKernelCapabilityList(const fnd::List& caps); - void exportKernelCapabilityList(fnd::List& caps) const; - void clear(); - bool isSet() const; - - // variables - uint8_t getMinPriority() const; - void setMinPriority(uint8_t priority); - uint8_t getMaxPriority() const; - void setMaxPriority(uint8_t priority); - uint8_t getMinCpuId() const; - void setMinCpuId(uint8_t core_num); - uint8_t getMaxCpuId() const; - void setMaxCpuId(uint8_t core_num); - - private: - const std::string kModuleName = "THREAD_INFO_HANDLER"; - static const size_t kMaxKernelCapNum = 1; - - bool mIsSet; - ThreadInfoEntry mEntry; - }; -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/define/aci.h b/lib/libhac/include/nn/hac/define/aci.h deleted file mode 100644 index 56bb2d3..0000000 --- a/lib/libhac/include/nn/hac/define/aci.h +++ /dev/null @@ -1,56 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace hac -{ - namespace aci - { - static const uint32_t kAciStructMagic = _MAKE_STRUCT_MAGIC_U32("ACI0"); - static const uint32_t kAciDescStructMagic = _MAKE_STRUCT_MAGIC_U32("ACID"); - static const size_t kSectionAlignSize = 0x10; - - enum Flag - { - FLAG_PRODUCTION, - FLAG_UNQUALIFIED_APPROVAL - }; - } -#pragma pack(push,1) - struct sAciSection - { - le_uint32_t offset; - le_uint32_t size; - }; - - struct sAciHeader - { - le_uint32_t st_magic; - byte_t reserved_00[0xC]; - le_uint64_t program_id; - byte_t reserved_01[0x8]; - sAciSection fac; - sAciSection sac; - sAciSection kc; - }; - - struct sAciDescHeader - { - byte_t signature[fnd::rsa::kRsa2048Size]; - byte_t nca_rsa_signature2_modulus[fnd::rsa::kRsa2048Size]; - le_uint32_t st_magic; - le_uint32_t signed_size; - byte_t reserved_00[0x4]; - le_uint32_t flags; - le_uint64_t program_id_min; - le_uint64_t program_id_max; - sAciSection fac; - sAciSection sac; - sAciSection kc; - }; -#pragma pack(pop) -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/define/cnmt.h b/lib/libhac/include/nn/hac/define/cnmt.h deleted file mode 100644 index 6dc9316..0000000 --- a/lib/libhac/include/nn/hac/define/cnmt.h +++ /dev/null @@ -1,181 +0,0 @@ -#pragma once -#include -#include - -namespace nn -{ -namespace hac -{ - namespace cnmt - { - enum ContentType - { - TYPE_META = 0, - TYPE_PROGRAM, - TYPE_DATA, - TYPE_CONTROL, - TYPE_HTML_DOCUMENT, - TYPE_LEGAL_INFORMATION, - TYPE_DELTA_FRAGMENT - }; - - enum ContentMetaType - { - METATYPE_SYSTEM_PROGRAM = 1, - METATYPE_SYSTEM_DATA, - METATYPE_SYSTEM_UPDATE, - METATYPE_BOOT_IMAGE_PACKAGE, - METATYPE_BOOT_IMAGE_PACKAGE_SAFE, - - METATYPE_APPLICATION = 0x80, - METATYPE_PATCH, // can have extended data - METATYPE_ADD_ON_CONTENT, - METATYPE_DELTA // can have extended data - }; - - enum UpdateType - { - UPDATETYPE_APPLY_AS_DELTA, - UPDATETYPE_OVERWRITE, - UPDATETYPE_CREATE - }; - - enum ContentMetaAttribute - { - ATTRIBUTE_INCLUDES_EX_FAT_DRIVER, - ATTRIBUTE_REBOOTLESS - }; - - static const size_t kContentIdLen = 0x10; - static const size_t kDigestLen = 0x20; - - struct sContentId - { - byte_t data[kContentIdLen]; - - void set(const byte_t content_id[kContentIdLen]) - { - memcpy(this->data, content_id, kContentIdLen); - } - - void operator=(const sContentId& other) - { - set(other.data); - } - - bool operator==(const sContentId& other) const - { - return memcmp(this->data, other.data, kContentIdLen) == 0; - } - - bool operator!=(const sContentId& other) const - { - return !(*this == other); - } - }; - - struct sDigest - { - byte_t data[kDigestLen]; - - void set(const byte_t digest[kDigestLen]) - { - memcpy(this->data, digest, kDigestLen); - } - - void operator=(const sDigest& other) - { - set(other.data); - } - - bool operator==(const sDigest& other) const - { - return memcmp(this->data, other.data, kDigestLen) == 0; - } - - bool operator!=(const sDigest& other) const - { - return !(*this == other); - } - }; - } - - -#pragma pack(push,1) - /* - struct sContentMeta - { - sContentMetaHeader hdr; - byte_t exhdr[]; // optional - sContentInfo info[]; - sContentMetaInfo meta[]; - byte_t extdata[]; - byte_t digest[32] - }; - */ - - struct sContentMetaHeader - { - le_uint64_t id; - le_uint32_t version; - byte_t type; - byte_t reserved_0; - le_uint16_t exhdr_size; - le_uint16_t content_count; - le_uint16_t content_meta_count; - byte_t attributes; - byte_t reserved_1[3]; - le_uint32_t required_download_system_version; - byte_t reserved_2[4]; - }; - - struct sContentInfo - { - fnd::sha::sSha256Hash content_hash; - cnmt::sContentId content_id; - le_uint32_t size_lower; - le_uint16_t size_higher; - byte_t content_type; - byte_t id_offset; - }; - - struct sContentMetaInfo - { - le_uint64_t id; - le_uint32_t version; - byte_t type; - byte_t attributes; - byte_t reserved[2]; - }; - - struct sApplicationMetaExtendedHeader - { - le_uint64_t patch_id; - le_uint32_t required_system_version; - byte_t reserved[4]; - }; - - struct sPatchMetaExtendedHeader - { - le_uint64_t application_id; - le_uint32_t required_system_version; - le_uint32_t extended_data_size; - byte_t reserved[8]; - }; - - struct sAddOnContentMetaExtendedHeader - { - le_uint64_t application_id; - le_uint32_t required_application_version; - byte_t reserved[4]; - }; - - struct sDeltaMetaExtendedHeader - { - le_uint64_t application_id; - le_uint32_t extended_data_size; - byte_t reserved[4]; - }; -#pragma pack(pop) -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/define/delta.h b/lib/libhac/include/nn/hac/define/delta.h deleted file mode 100644 index b0d4d2c..0000000 --- a/lib/libhac/include/nn/hac/define/delta.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once -#include -#include - -namespace nn -{ -namespace hac -{ - namespace delta - { - static const uint32_t kDeltaStructMagic = _MAKE_STRUCT_MAGIC_U32("NDV0"); - } -#pragma pack(push,1) - struct sDeltaHeader - { - le_uint32_t st_magic; - byte_t reserved_00[4]; - le_uint64_t source_size; - le_uint64_t destination_size; - le_uint64_t header_size; - le_uint64_t body_size; - byte_t reserved_01[0x18]; - }; -#pragma pack(pop) -} -} diff --git a/lib/libhac/include/nn/hac/define/fac.h b/lib/libhac/include/nn/hac/define/fac.h deleted file mode 100644 index 80bc206..0000000 --- a/lib/libhac/include/nn/hac/define/fac.h +++ /dev/null @@ -1,60 +0,0 @@ -#pragma once -#include - -namespace nn -{ -namespace hac -{ - namespace fac - { - static const uint32_t kFacFormatVersion = 1; - static const size_t kSectionAlignSize = 4; - - enum FsAccessFlag - { - FSA_APPLICATION_INFO, - FSA_BOOT_MODE_CONTROL, - FSA_CALIBRATION, - FSA_SYSTEM_SAVE_DATA, - FSA_GAME_CARD, - FSA_SAVE_DATA_BACKUP, - FSA_SAVE_DATA_MANAGEMENT, - FSA_BIS_ALL_RAW, - FSA_GAME_CARD_RAW, - FSA_GAME_CARD_PRIVATE, - FSA_SET_TIME, - FSA_CONTENT_MANAGER, - FSA_IMAGE_MANAGER, - FSA_CREATE_SAVE_DATA, - FSA_SYSTEM_SAVE_DATA_MANAGEMENT, - FSA_BIS_FILE_SYSTEM, - FSA_SYSTEM_UPDATE, - FSA_SAVE_DATA_META, - FSA_DEVICE_SAVE_CONTROL, - FSA_SETTINGS_CONTROL, - FSA_DEBUG = 62, - FSA_FULL_PERMISSION = 63, - }; - - enum SaveDataOwnerIdAccessType - { - SDO_READ = 1, - SDO_WRITE, - SDO_READWRITE - }; - } - -#pragma pack(push,1) - struct sFacHeader - { - le_uint32_t version; // default 1 - le_uint64_t fac_flags; - struct sFacSection - { - le_uint32_t offset; - le_uint32_t size; - } content_owner_ids, save_data_owner_ids; // the data for these follow later in binary. start/end relative to base of FacData instance - }; -#pragma pack(pop) -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/define/gc.h b/lib/libhac/include/nn/hac/define/gc.h deleted file mode 100644 index 4c3098b..0000000 --- a/lib/libhac/include/nn/hac/define/gc.h +++ /dev/null @@ -1,133 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include -#include - -namespace nn -{ -namespace hac -{ - namespace gc - { - static const uint32_t kGcHeaderStructMagic = _MAKE_STRUCT_MAGIC_U32("HEAD"); - static const uint32_t kHeaderEncOffset = 0x90; - static const uint32_t kHeaderEncSize = 0x70; - static const uint32_t kPageSize = 0x200; - static const uint32_t kUppHashLen = 8; - /* - static const uint32_t kCardKeyAreaPageCount = 8; - static const uint32_t kCardHeaderPageCount = 1; - static const uint32_t kReservedAreaPageCount = 55; - static const uint32_t kCertAreaStartPageAddress = kCardHeaderPageCount + kReservedAreaPageCount + kCardKeyAreaPageCount; - static const uint32_t kCertAreaPageCount = 64; - static const uint32_t kNormalAreaStartPageAddress = kReservedAreaPageCount + kCertAreaPageCount + kCardHeaderPageCount + kCardKeyAreaPageCount; - */ - - const std::string kUpdatePartitionStr = "update"; - const std::string kLogoPartitionStr = "logo"; - const std::string kNormalPartitionStr = "normal"; - const std::string kSecurePartitionStr = "secure"; - - enum KekIndex - { - KEK_XCIE, - KEK_XCIR - }; - - enum RomSize - { - ROM_SIZE_1GB = 0xFA, - ROM_SIZE_2GB = 0xF8, - ROM_SIZE_4GB = 0xF0, - ROM_SIZE_8GB = 0xE0, - ROM_SIZE_16GB = 0xE1, - ROM_SIZE_32GB = 0xE2 - }; - - enum HeaderFlags - { - FLAG_AUTOBOOT, - FLAG_HISTORY_ERASE, - FLAG_REPAIR_TOOL - }; - - enum FwVersionIndex - { - FWVER_MINOR, - FWVER_MAJOR - }; - - enum CardClockRate - { - CLOCK_RATE_25 = 10551312, - CLOCK_RATE_50 = 10551313, - }; - } - -#pragma pack(push,1) - struct sGcHeader - { - le_uint32_t st_magic; - le_uint32_t rom_area_start_page; - le_uint32_t backup_area_start_page; - byte_t key_flag; - byte_t rom_size; - byte_t card_header_version; - byte_t flags; - le_uint64_t package_id; - le_uint32_t valid_data_end_page; - byte_t reserved_00[4]; - fnd::aes::sAesIvCtr aescbc_iv; - le_uint64_t partition_fs_header_address; - le_uint64_t partition_fs_header_size; - fnd::sha::sSha256Hash partition_fs_header_hash; - fnd::sha::sSha256Hash initial_data_hash; - le_uint32_t sel_sec; - le_uint32_t sel_t1_key; - le_uint32_t sel_key; - le_uint32_t lim_area; - // START ENCRYPTION - le_uint32_t fw_version[2]; - le_uint32_t acc_ctrl_1; - le_uint32_t wait_1_time_read; - le_uint32_t wait_2_time_read; - le_uint32_t wait_1_time_write; - le_uint32_t wait_2_time_write; - le_uint32_t fw_mode; - le_uint32_t upp_version; - byte_t reserved_01[0x4]; - byte_t upp_hash[gc::kUppHashLen]; - le_uint64_t upp_id; - byte_t reserved_02[0x38]; - // END ENCRYPTION - }; - - struct sGcHeaderPage - { - byte_t signature[fnd::rsa::kRsa2048Size]; - sGcHeader header; - }; // sizeof() = 512 (1 page) - - struct sInitialData - { - byte_t key_source[16]; // { package_id[8], zeros[8]} - byte_t title_key_enc[16]; - byte_t ccm_mac[16]; - byte_t ccm_nonce[12]; - byte_t reserved[0x1c4]; - }; // sizeof() = 512 (1 page) - - struct sKeyDataArea - { - sInitialData initial_data; // AES128-CCM encrypted {titlekey[16]} - byte_t encrypted_00[gc::kPageSize * 6]; // AES128-CTR encrypted {titlekey[16]} - byte_t encrypted_00_aesctr_data[fnd::rsa::kRsa2048Size]; // RSA2048-OAEP-SHA256 encrypted AES-CTR data used for encrypted_00 {key[16],iv[16]} - byte_t reserved[gc::kPageSize - fnd::rsa::kRsa2048Size]; - }; // sizeof() = 512*8 (8 pages) - -#pragma pack(pop) -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/define/hierarchicalintegrity.h b/lib/libhac/include/nn/hac/define/hierarchicalintegrity.h deleted file mode 100644 index 7e5eaa6..0000000 --- a/lib/libhac/include/nn/hac/define/hierarchicalintegrity.h +++ /dev/null @@ -1,35 +0,0 @@ -#pragma once -#include -#include - -namespace nn -{ -namespace hac -{ - namespace hierarchicalintegrity - { - static const uint32_t kStructMagic = _MAKE_STRUCT_MAGIC_U32("IVFC"); - static const uint32_t kRomfsTypeId = 0x20000; - static const size_t kDefaultLayerNum = 6; - static const size_t kHeaderAlignLen = 0x20; - } - -#pragma pack(push,1) - struct sHierarchicalIntegrityHeader - { - le_uint32_t st_magic; - le_uint32_t type_id; - le_uint32_t master_hash_size; - le_uint32_t layer_num; - }; - - struct sHierarchicalIntegrityLayerInfo // sizeof(0x18) - { - le_uint64_t offset; - le_uint64_t size; - le_uint32_t block_size; - byte_t reserved[4]; - }; -#pragma pack(pop) -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/define/hierarchicalsha256.h b/lib/libhac/include/nn/hac/define/hierarchicalsha256.h deleted file mode 100644 index bb720cc..0000000 --- a/lib/libhac/include/nn/hac/define/hierarchicalsha256.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once -#include -#include - -namespace nn -{ -namespace hac -{ - namespace hierarchicalsha256 - { - static const size_t kDefaultLayerNum = 2; - static const size_t kMaxLayerNum = 2; - } - -#pragma pack(push,1) - struct sHierarchicalSha256Header - { - fnd::sha::sSha256Hash master_hash; - le_uint32_t hash_block_size; - le_uint32_t layer_num; - struct sLayer - { - le_uint64_t offset; - le_uint64_t size; - } layer[hierarchicalsha256::kMaxLayerNum]; - }; -#pragma pack(pop) -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/define/ini.h b/lib/libhac/include/nn/hac/define/ini.h deleted file mode 100644 index d51a3aa..0000000 --- a/lib/libhac/include/nn/hac/define/ini.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace hac -{ - namespace ini - { - static const uint32_t kIniStructMagic = _MAKE_STRUCT_MAGIC_U32("INI1"); - static const size_t kMaxKipNum = 0x50; - } - -#pragma pack(push,1) - struct sIniHeader - { - le_uint32_t st_magic; - le_uint32_t size; - le_uint32_t kip_num; - byte_t reserved_01[0x4]; - }; -#pragma pack(pop) -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/define/kc.h b/lib/libhac/include/nn/hac/define/kc.h deleted file mode 100644 index 4716a9f..0000000 --- a/lib/libhac/include/nn/hac/define/kc.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace hac -{ - namespace kc - { - enum KernelCapId - { - KC_INVALID = 0, - KC_THREAD_INFO = 3, - KC_ENABLE_SYSTEM_CALLS = 4, - KC_MEMORY_MAP = 6, - KC_IO_MEMORY_MAP = 7, - KC_ENABLE_INTERUPTS = 11, - KC_MISC_PARAMS = 13, - KC_KERNEL_VERSION = 14, - KC_HANDLE_TABLE_SIZE = 15, - KC_MISC_FLAGS = 16, - KC_STUB = 32 - }; - } -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/define/kip.h b/lib/libhac/include/nn/hac/define/kip.h deleted file mode 100644 index c1a9360..0000000 --- a/lib/libhac/include/nn/hac/define/kip.h +++ /dev/null @@ -1,65 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace hac -{ - namespace kip - { - static const uint32_t kKipStructMagic = _MAKE_STRUCT_MAGIC_U32("KIP1"); - static const size_t kNameMaxLen = 0xC; - static const size_t kKernCapabilityNum = 0x20; - static const size_t kKernCapabilitySize = kKernCapabilityNum * sizeof(uint32_t); - - enum ProcessCategory - { - PROCCAT_REGULAR, - PROCCAT_KERNAL_KIP - }; - - enum HeaderFlags - { - FLAG_TEXT_COMPRESS, - FLAG_RO_COMPRESS, - FLAG_DATA_COMPRESS, - FLAG_INSTRUCTION_64BIT, - FLAG_ADDR_SPACE_64BIT, - FLAG_USE_SYSTEM_POOL_PARTITION - }; - } - -#pragma pack(push,1) - struct sKipCodeSegment - { - le_uint32_t memory_offset; - le_uint32_t memory_size; - le_uint32_t file_size; - }; - - struct sKipHeader - { - le_uint32_t st_magic; - char name[kip::kNameMaxLen]; - le_uint64_t title_id; - le_uint32_t process_category; - byte_t main_thread_priority; - byte_t main_thread_cpu_id; - byte_t reserved_01; - byte_t flags; - sKipCodeSegment text; - byte_t reserved_02[4]; - sKipCodeSegment ro; - le_uint32_t main_thread_stack_size; - sKipCodeSegment data; - byte_t reserved_03[4]; - sKipCodeSegment bss; - byte_t reserved_04[4]; - byte_t reserved_05[0x20]; - byte_t capabilities[kip::kKernCapabilitySize]; - }; -#pragma pack(pop) -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/define/macro.h b/lib/libhac/include/nn/hac/define/macro.h deleted file mode 100644 index 8e021c3..0000000 --- a/lib/libhac/include/nn/hac/define/macro.h +++ /dev/null @@ -1,5 +0,0 @@ -#pragma once -#include - -#define _MAKE_STRUCT_MAGIC_U32(x) ((uint32_t)(x[3]) << 24 | (uint32_t)(x[2]) << 16 | (uint32_t)(x[1]) << 8 | (uint32_t)(x[0])) -#define _MAKE_STRUCT_MAGIC_U64(x) ((uint64_t)(x[7]) << 56 | (uint64_t)(x[6]) << 48 | (uint64_t)(x[5]) << 40 | (uint64_t)(x[4]) << 32 | (uint64_t)(x[3]) << 24 | (uint64_t)(x[2]) << 16 | (uint64_t)(x[1]) << 8 | (uint64_t)(x[0])) diff --git a/lib/libhac/include/nn/hac/define/meta.h b/lib/libhac/include/nn/hac/define/meta.h deleted file mode 100644 index ea1c10f..0000000 --- a/lib/libhac/include/nn/hac/define/meta.h +++ /dev/null @@ -1,58 +0,0 @@ -#pragma once -#include -#include - -namespace nn -{ -namespace hac -{ - namespace meta - { - static const uint32_t kMetaStructMagic = _MAKE_STRUCT_MAGIC_U32("META"); - static const size_t kNameMaxLen = 0x10; - static const size_t kProductCodeMaxLen = 0x10; - static const uint32_t kMaxPriority = BIT(6) - 1; - static const size_t kSectionAlignSize = 0x10; - static const uint32_t kDefaultMainThreadStackSize = 4096; - - enum InstructionType - { - INSTR_32BIT, - INSTR_64BIT, - }; - - enum ProcAddrSpaceType - { - ADDR_SPACE_64BIT = 1, - ADDR_SPACE_32BIT, - ADDR_SPACE_32BIT_NO_RESERVED, - }; - } -#pragma pack(push,1) - struct sMetaSection - { - le_uint32_t offset; - le_uint32_t size; - }; - - struct sMetaHeader - { - le_uint32_t st_magic; - byte_t reserved_0[8]; - byte_t flags; - byte_t reserved_1; - byte_t main_thread_priority; - byte_t main_thread_cpu_id; - byte_t reserved_2[8]; - le_uint32_t version; - le_uint32_t main_thread_stack_size; - char name[meta::kNameMaxLen]; // important - char product_code[meta::kProductCodeMaxLen]; // can be empty - byte_t reserved_3[48]; - sMetaSection aci; - sMetaSection acid; - }; - -#pragma pack(pop) -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/define/nacp.h b/lib/libhac/include/nn/hac/define/nacp.h deleted file mode 100644 index 5d551d8..0000000 --- a/lib/libhac/include/nn/hac/define/nacp.h +++ /dev/null @@ -1,289 +0,0 @@ -#pragma once -#include - -namespace nn -{ -namespace hac -{ - namespace nacp - { - static const size_t kNameLength = 0x200; - static const size_t kPublisherLength = 0x100; - static const size_t kMaxLanguageCount = 16; - static const size_t kIsbnLength = 37; - static const size_t kRatingAgeCount = 32; - static const size_t kDisplayVersionLength = 16; - static const size_t kApplicationErrorCodeCategoryLength = 8; - static const size_t kLocalCommunicationIdCount = 8; - static const size_t kBcatPassphraseLength = 65; - static const size_t kPlayLogQueryableApplicationIdCount = 16; - static const int8_t kUnusedAgeRating = -1; - - enum AocRegistrationType - { - AOC_AllOnLaunch, - AOC_OnDemand - }; - - enum AttributeFlag - { - ATTR_None, - ATTR_Demo, - ATTR_RetailInteractiveDisplay - }; - - enum CrashReportMode - { - CREP_Deny, - CREP_Allow - }; - - enum DataLossConfirmation - { - DLOSS_None, - DLOSS_Required - }; - - enum Hdcp - { - HDCP_None, - HDCP_Required - }; - - enum Language - { - LANG_AmericanEnglish, - LANG_BritishEnglish, - LANG_Japanese, - LANG_French, - LANG_German, - LANG_LatinAmericanSpanish, - LANG_Spanish, - LANG_Italian, - LANG_Dutch, - LANG_CanadianFrench, - LANG_Portuguese, - LANG_Russian, - LANG_Korean, - LANG_TraditionalChinese, - LANG_SimplifiedChinese - }; - - enum LogoHandling - { - LHND_Auto, - LHND_None - }; - - enum LogoType - { - LOGO_LicensedByNintendo, - LOGO_DistributedByNintendo, - LOGO_Nintendo - }; - - enum Organisation - { - ORGN_CERO, - ORGN_GRACGCRB, - ORGN_GSRMR, - ORGN_ESRB, - ORGN_ClassInd, - ORGN_USK, - ORGN_PEGI, - ORGN_PEGIPortugal, - ORGN_PEGIBBFC, - ORGN_Russian, - ORGN_ACB, - ORGN_OFLC - }; - - enum ParentalControlFlag - { - PC_None, - PC_FreeCommunication - }; - - enum PlayLogPolicy - { - PLP_All, - PLP_LogOnly, - PLP_None - }; - - enum PlayLogQueryCapability - { - PLQC_None, - PLQC_Whitelist, - PLQC_All - }; - - enum RepairFlag - { - REPF_None, - REPF_SuppressGameCardAccess - }; - - enum RequiredNetworkServiceLicenseOnLaunchValue - { - REQNETLIC_None, - REQNETLIC_Common - }; - - enum RuntimeAocInstallMode - { - RTAOC_Deny, - RTAOC_AllowAppend - }; - - enum ScreenshotMode - { - SCRN_Allow, - SCRN_Deny - }; - - enum StartupUserAccount - { - USER_None, - USER_Required, - USER_RequiredWithNetworkServiceAccountAvailable - }; - - enum TouchScreenUsageMode - { - TOUCH_None, - TOUCH_Supported, - TOUCH_Required, - }; - - enum UserAccountSwitchLockValue - { - UASL_Disable, - UASL_Enable - }; - - enum VideoCaptureMode - { - VCAP_Disable, - VCAP_Manual, - VCAP_Enable - }; - } - - -#pragma pack(push,1) - struct sApplicationTitle - { - char name[nacp::kNameLength]; - char publisher[nacp::kPublisherLength]; - }; - - struct sApplicationControlProperty - { - sApplicationTitle title[nacp::kMaxLanguageCount]; - char isbn[nacp::kIsbnLength]; - byte_t startup_user_account; - byte_t user_account_switch_lock; - byte_t add_on_content_registration_type; - le_uint32_t attribute_flag; - le_uint32_t supported_language_flag; - le_uint32_t parental_control_flag; - byte_t screenshot; - byte_t video_capture; - byte_t data_loss_confirmation; - byte_t play_log_policy; - le_uint64_t presence_group_id; - int8_t rating_age[nacp::kRatingAgeCount]; - char display_version[nacp::kDisplayVersionLength]; - le_uint64_t add_on_content_base_id; - le_uint64_t save_data_owner_id; - le_uint64_t user_account_save_data_size; - le_uint64_t user_account_save_data_journal_size; - le_uint64_t device_save_data_size; - le_uint64_t device_save_data_journal_size; - le_uint64_t bcat_delivery_cache_storage_size; - char application_error_code_category[nacp::kApplicationErrorCodeCategoryLength]; - le_uint64_t local_communication_id[nacp::kLocalCommunicationIdCount]; - byte_t logo_type; - byte_t logo_handling; - byte_t runtime_add_on_content_install; - byte_t reserved_00[3]; - byte_t crash_report; - byte_t hdcp; - le_uint64_t seed_for_pseudo_device_id; - char bcat_passphrase[nacp::kBcatPassphraseLength]; - byte_t reserved_01; - byte_t reserved_02[6]; //reserved_for_user_account_save_data_operation - le_uint64_t user_account_save_data_size_max; - le_uint64_t user_account_save_data_journal_size_max; - le_uint64_t device_save_data_size_max; - le_uint64_t device_save_data_journal_size_max; - le_uint64_t temporary_storage_size; - le_uint64_t cache_storage_size; - le_uint64_t cache_storage_journal_size; - le_uint64_t cache_storage_data_and_journal_size_max; - le_uint16_t cache_storage_index_max; - byte_t reserved_03[6]; - le_uint64_t play_log_queryable_application_id[nacp::kPlayLogQueryableApplicationIdCount]; - byte_t play_log_query_capability; - byte_t repair_flag; - byte_t program_index; - byte_t required_network_service_license_on_launch_flag; - byte_t reserved_04[0xDEC]; - }; - - struct sApplicationControlProperty_v0 - { - sApplicationTitle title[nacp::kMaxLanguageCount]; - char isbn[nacp::kIsbnLength]; - byte_t startup_user_account; - byte_t touch_screen_usage; - byte_t add_on_content_registration_type; - le_uint32_t attribute_flag; - le_uint32_t supported_language_flag; - le_uint32_t parental_control_flag; - byte_t screenshot; - byte_t video_capture; - byte_t data_loss_confirmation; - byte_t play_log_policy; - le_uint64_t presence_group_id; - int8_t rating_age[nacp::kRatingAgeCount]; - char display_version[nacp::kDisplayVersionLength]; - le_uint64_t add_on_content_base_id; - le_uint64_t save_data_owner_id; - le_uint64_t user_account_save_data_size; - le_uint64_t user_account_save_data_journal_size; - le_uint64_t device_save_data_size; - le_uint64_t device_save_data_journal_size; - le_uint64_t bcat_delivery_cache_storage_size; - char application_error_code_category[nacp::kApplicationErrorCodeCategoryLength]; - le_uint64_t local_communication_id[nacp::kLocalCommunicationIdCount]; - byte_t logo_type; - byte_t logo_handling; - byte_t runtime_add_on_content_install; - byte_t reserved_00[3]; - byte_t crash_report; - byte_t hdcp; - le_uint64_t seed_for_pseudo_device_id; - char bcat_passphrase[nacp::kBcatPassphraseLength]; - byte_t reserved_01; - byte_t reserved_02[6]; //reserved_for_user_account_save_data_operation - le_uint64_t user_account_save_data_size_max; - le_uint64_t user_account_save_data_journal_size_max; - le_uint64_t device_save_data_size_max; - le_uint64_t device_save_data_journal_size_max; - le_uint64_t temporary_storage_size; - le_uint64_t cache_storage_size; - le_uint64_t cache_storage_journal_size; - le_uint64_t cache_storage_data_and_journal_size_max; - le_uint16_t cache_storage_index_max; - byte_t reserved_03[6]; - le_uint64_t play_log_queryable_application_id[nacp::kPlayLogQueryableApplicationIdCount]; - byte_t play_log_query_capability; - byte_t repair_flag; - byte_t program_index; - byte_t reserved_04[0xDED]; - }; -#pragma pack(pop) -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/define/nca.h b/lib/libhac/include/nn/hac/define/nca.h deleted file mode 100644 index 95fae55..0000000 --- a/lib/libhac/include/nn/hac/define/nca.h +++ /dev/null @@ -1,144 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include - -namespace nn -{ -namespace hac -{ - namespace nca - { - static const uint32_t kNca2StructMagic = _MAKE_STRUCT_MAGIC_U32("NCA2"); - static const uint32_t kNca3StructMagic = _MAKE_STRUCT_MAGIC_U32("NCA3"); - static const size_t kSectorSize = 0x200; - static const size_t kPartitionNum = 4; - static const size_t kHeaderSectorNum = 6; - static const size_t kHeaderSize = kSectorSize * kHeaderSectorNum; - static const size_t kRightsIdLen = 0x10; - static const size_t kKeyAreaSize = 0x100; - static const size_t kKeyAreaKeyNum = kKeyAreaSize / fnd::aes::kAes128KeySize; - static const size_t kKeyAreaEncryptionKeyNum = 3; - static const size_t kFsHeaderHashSuperblockLen = 0x138; - static const uint16_t kDefaultFsHeaderVersion = 2; - - enum HeaderFormatVersion - { - FORMAT_NCA2 = 2, - FORMAT_NCA3 = 3 - }; - - enum ProgramContentPartitionIndex - { - PARTITION_CODE = 0, - PARTITION_DATA = 1, - PARTITION_LOGO = 2, - }; - - enum DistributionType - { - DIST_DOWNLOAD, - DIST_GAME_CARD - }; - - enum ContentType - { - TYPE_PROGRAM, - TYPE_META, - TYPE_CONTROL, - TYPE_MANUAL, - TYPE_DATA, - TYPE_PUBLIC_DATA - }; - - enum KeyBankIndex - { - KEY_AESXTS_0, - KEY_AESXTS_1, - KEY_AESCTR, - KEY_UNUSED_3, - KEY_AESCTR_HW - }; - - enum KeyAreaEncryptionKeyIndex - { - KAEK_IDX_APPLICATION, - KAEK_IDX_OCEAN, - KAEK_IDX_SYSTEM - }; - - enum FormatType - { - FORMAT_ROMFS, - FORMAT_PFS0 - }; - - enum HashType - { - HASH_AUTO, - HASH_NONE, - HASH_HIERARCHICAL_SHA256, - HASH_HIERARCHICAL_INTERGRITY // IVFC - }; - - enum EncryptionType - { - CRYPT_AUTO, - CRYPT_NONE, - CRYPT_AESXTS, - CRYPT_AESCTR, - CRYPT_AESCTREX - }; - } - -#pragma pack(push,1) - struct sContentArchiveHeader - { - le_uint32_t st_magic; - byte_t distribution_type; - byte_t content_type; - byte_t key_generation; - byte_t key_area_encryption_key_index; - le_uint64_t content_size; - le_uint64_t program_id; - le_uint32_t content_index; - le_uint32_t sdk_addon_version; - byte_t key_generation_2; - byte_t reserved_2[0xf]; - byte_t rights_id[nca::kRightsIdLen]; - struct sPartitionEntry - { - le_uint32_t start_blk; // block units - le_uint32_t end_blk; // block units - byte_t enabled; - byte_t reserved[7]; - } partition_entry[nca::kPartitionNum]; - fnd::sha::sSha256Hash fs_header_hash[nca::kPartitionNum]; - byte_t key_area[nca::kKeyAreaSize]; - }; - - struct sNcaFsHeader - { - le_uint16_t version; - byte_t format_type; - byte_t hash_type; - byte_t encryption_type; - byte_t reserved_0[3]; - byte_t hash_superblock[nca::kFsHeaderHashSuperblockLen]; - byte_t aes_ctr_upper[8]; - byte_t reserved_1[0xB8]; - }; - - struct sContentArchiveHeaderBlock - { - byte_t signature_main[fnd::rsa::kRsa2048Size]; - byte_t signature_acid[fnd::rsa::kRsa2048Size]; - sContentArchiveHeader header; - sNcaFsHeader fs_header[nn::hac::nca::kPartitionNum]; - }; - -#pragma pack(pop) -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/define/nro.h b/lib/libhac/include/nn/hac/define/nro.h deleted file mode 100644 index 6ab147f..0000000 --- a/lib/libhac/include/nn/hac/define/nro.h +++ /dev/null @@ -1,45 +0,0 @@ -#pragma once -#include -#include - -namespace nn -{ -namespace hac -{ - namespace nro - { - static const uint32_t kNroStructMagic = _MAKE_STRUCT_MAGIC_U32("NRO0"); - static const uint32_t kDefaultFormatVersion = 0; - static const size_t kRoCrtSize = 8; - static const size_t kModuleIdSize = 32; - } - -#pragma pack(push,1) - struct sNroSection - { - le_uint32_t memory_offset; - le_uint32_t size; - }; - - struct sNroHeader - { - byte_t ro_crt[nro::kRoCrtSize]; - byte_t reserved_0[8]; - le_uint32_t st_magic; - le_uint32_t format_version; - le_uint32_t size; - le_uint32_t flags; - sNroSection text; - sNroSection ro; - sNroSection data; - le_uint32_t bss_size; - byte_t reserved_1[4]; - byte_t module_id[nro::kModuleIdSize]; - byte_t reserved_2[8]; - sNroSection embedded; - sNroSection dyn_str; - sNroSection dyn_sym; - }; -#pragma pack(pop) -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/define/nrr.h b/lib/libhac/include/nn/hac/define/nrr.h deleted file mode 100644 index 275e5f9..0000000 --- a/lib/libhac/include/nn/hac/define/nrr.h +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace hac -{ - namespace nrr - { - static const uint32_t kNrrStructMagic = _MAKE_STRUCT_MAGIC_U32("NRR0"); - } - -#pragma pack(push,1) - struct sNrrCertificate - { - le_uint64_t application_id_mask; - le_uint64_t application_id_pattern; - byte_t nrr_body_modulus[fnd::rsa::kRsa2048Size]; - byte_t nrr_cert_signature[fnd::rsa::kRsa2048Size]; - }; - - struct sNrrHeader - { - le_uint32_t st_magic; - byte_t reserved_0[28]; - sNrrCertificate certificate; - byte_t nrr_body_signature[fnd::rsa::kRsa2048Size]; - le_uint64_t application_id; - le_uint32_t size; - byte_t reserved_1[4]; - le_uint32_t hash_offset; - le_uint32_t hash_count; - byte_t reserved_2[8]; - }; -#pragma pack(pop) -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/define/nso.h b/lib/libhac/include/nn/hac/define/nso.h deleted file mode 100644 index 8d842a5..0000000 --- a/lib/libhac/include/nn/hac/define/nso.h +++ /dev/null @@ -1,68 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace hac -{ - namespace nso - { - static const uint32_t kNsoStructMagic = _MAKE_STRUCT_MAGIC_U32("NSO0"); - static const uint32_t kDefaultFormatVersion = 0; - static const size_t kModuleIdSize = 32; - - enum HeaderFlags - { - FLAG_TEXT_COMPRESS, - FLAG_RO_COMPRESS, - FLAG_DATA_COMPRESS, - FLAG_TEXT_HASH, - FLAG_RO_HASH, - FLAG_DATA_HASH - }; - } - -#pragma pack(push,1) - struct sNsoCodeSegment - { - le_uint32_t file_offset; - le_uint32_t memory_offset; - le_uint32_t size; - }; - - struct sNsoSection - { - le_uint32_t offset; - le_uint32_t size; - }; - - struct sNsoHeader - { - le_uint32_t st_magic; - le_uint32_t format_version; - byte_t reserved_1[4]; - le_uint32_t flags; - sNsoCodeSegment text; - le_uint32_t module_name_offset; - sNsoCodeSegment ro; - le_uint32_t module_name_size; - sNsoCodeSegment data; - le_uint32_t bss_size; - byte_t module_id[nso::kModuleIdSize]; - le_uint32_t text_file_size; - le_uint32_t ro_file_size; - le_uint32_t data_file_size; - byte_t reserved_2[28]; - sNsoSection embedded; - sNsoSection dyn_str; - sNsoSection dyn_sym; - fnd::sha::sSha256Hash text_hash; - fnd::sha::sSha256Hash ro_hash; - fnd::sha::sSha256Hash data_hash; - }; - -#pragma pack(pop) -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/define/pfs.h b/lib/libhac/include/nn/hac/define/pfs.h deleted file mode 100644 index 6f78d38..0000000 --- a/lib/libhac/include/nn/hac/define/pfs.h +++ /dev/null @@ -1,45 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace hac -{ - namespace pfs - { - static const uint32_t kPfsStructMagic = _MAKE_STRUCT_MAGIC_U32("PFS0"); - static const uint32_t kHashedPfsStructMagic = _MAKE_STRUCT_MAGIC_U32("HFS0"); - static const size_t kHeaderAlign = 64; - } - -#pragma pack(push,1) - struct sPfsHeader - { - le_uint32_t st_magic; - le_uint32_t file_num; - le_uint32_t name_table_size; - byte_t padding[4]; - }; - - struct sPfsFile - { - le_uint64_t data_offset; - le_uint64_t size; - le_uint32_t name_offset; - byte_t padding[4]; - }; // sizeof(0x18) - - struct sHashedPfsFile - { - le_uint64_t data_offset; - le_uint64_t size; - le_uint32_t name_offset; - le_uint32_t hash_protected_size; - byte_t padding[8]; - fnd::sha::sSha256Hash hash; - }; // sizeof(0x40) -#pragma pack(pop) -} -} \ No newline at end of file diff --git a/lib/libhac/include/nn/hac/define/romfs.h b/lib/libhac/include/nn/hac/define/romfs.h deleted file mode 100644 index bc346d6..0000000 --- a/lib/libhac/include/nn/hac/define/romfs.h +++ /dev/null @@ -1,60 +0,0 @@ -#pragma once -#include - -namespace nn -{ -namespace hac -{ - namespace romfs - { - static const uint64_t kRomfsHeaderAlign = 0x200; - static const uint32_t kInvalidAddr = 0xffffffff; - - enum HeaderSectionIndex - { - DIR_HASHMAP_TABLE, - DIR_NODE_TABLE, - FILE_HASHMAP_TABLE, - FILE_NODE_TABLE, - SECTION_NUM - }; - } - -#pragma pack(push,1) - struct sRomfsHeader - { - le_uint64_t header_size; - struct sSection - { - le_uint64_t offset; - le_uint64_t size; - } sections[romfs::SECTION_NUM]; - le_uint64_t data_offset; - }; - - struct sRomfsDirEntry - { - le_uint32_t parent; - le_uint32_t sibling; - le_uint32_t child; - le_uint32_t file; - le_uint32_t hash; - le_uint32_t name_size; - char* name() { return ((char*)(this)) + sizeof(sRomfsDirEntry); } - const char* name() const { return ((char*)(this)) + sizeof(sRomfsDirEntry); } - }; - - struct sRomfsFileEntry - { - le_uint32_t parent; - le_uint32_t sibling; - le_uint64_t offset; - le_uint64_t size; - le_uint32_t hash; - le_uint32_t name_size; - char* name() { return ((char*)(this)) + sizeof(sRomfsFileEntry); } - const char* name() const { return ((char*)(this)) + sizeof(sRomfsFileEntry); } - }; -#pragma pack(pop) -} -} \ No newline at end of file diff --git a/lib/libhac/libhac.vcxproj b/lib/libhac/libhac.vcxproj deleted file mode 100644 index 4a89383..0000000 --- a/lib/libhac/libhac.vcxproj +++ /dev/null @@ -1,246 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 15.0 - {91BA9E79-8242-4F7D-B997-0DFEC95EA22B} - hac - 10.0.16299.0 - libhac - - - - StaticLibrary - true - v141 - MultiByte - - - StaticLibrary - false - v141 - true - MultiByte - - - StaticLibrary - true - v141 - MultiByte - - - StaticLibrary - false - v141 - true - MultiByte - - - - - - - - - - - - - - - - - - - - - - - Level3 - Disabled - true - ..\libfnd\include;..\libhac\include; - _MBCS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - - - Level3 - Disabled - true - ..\libfnd\include;..\libhac\include; - _MBCS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - - - Level3 - MaxSpeed - true - true - true - ..\libfnd\include;..\libhac\include; - _MBCS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - true - true - - - - - Level3 - MaxSpeed - true - true - true - ..\libfnd\include;..\libhac\include; - _MBCS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - true - true - - - - - - \ No newline at end of file diff --git a/lib/libhac/libhac.vcxproj.filters b/lib/libhac/libhac.vcxproj.filters deleted file mode 100644 index ab4e0f4..0000000 --- a/lib/libhac/libhac.vcxproj.filters +++ /dev/null @@ -1,363 +0,0 @@ - - - - - - - - {040358e3-f1c5-4875-b34f-23607459567c} - - - {1c33ce2b-25c4-4857-966c-9dc24daf3f61} - - - {a9fd54c0-9fd8-46a1-978e-fb531bf3ee1c} - - - - - Header Files\define - - - Header Files\define - - - Header Files\define - - - Header Files\define - - - Header Files\define - - - Header Files\define - - - Header Files\define - - - Header Files\define - - - Header Files\define - - - Header Files\define - - - Header Files\define - - - Header Files\define - - - Header Files\define - - - Header Files\define - - - Header Files\define - - - Header Files\define - - - Header Files\define - - - Header Files\define - - - Header Files\define - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - \ No newline at end of file diff --git a/lib/libhac/libhac.vcxproj.user b/lib/libhac/libhac.vcxproj.user deleted file mode 100644 index be25078..0000000 --- a/lib/libhac/libhac.vcxproj.user +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/lib/libhac/makefile b/lib/libhac/makefile deleted file mode 100644 index d8a204a..0000000 --- a/lib/libhac/makefile +++ /dev/null @@ -1,46 +0,0 @@ -# Sources -SRC_DIR = source -OBJS = $(foreach dir,$(SRC_DIR),$(subst .cpp,.o,$(wildcard $(dir)/*.cpp))) $(foreach dir,$(SRC_DIR),$(subst .c,.o,$(wildcard $(dir)/*.c))) - -# External dependencies -DEPENDS = fnd crypto -LIB_DIR = .. -INCS = -I"include" $(foreach dep,$(DEPENDS), -I"$(LIB_DIR)/lib$(dep)/include") - -# Compiler Settings -CXXFLAGS = -std=c++11 $(INCS) -D__STDC_FORMAT_MACROS -Wall -Wno-unused-value -CFLAGS = -std=c11 $(INCS) -Wall -Wno-unused-value -ARFLAGS = cr -o -ifeq ($(OS),Windows_NT) - # Windows Only Flags/Libs - CC = x86_64-w64-mingw32-gcc - CXX = x86_64-w64-mingw32-g++ - CFLAGS += -Wno-unused-but-set-variable - CXXFLAGS += -Wno-unused-but-set-variable -else - UNAME = $(shell uname -s) - ifeq ($(UNAME), Darwin) - # MacOS Only Flags/Libs - CFLAGS += -Wno-unused-private-field - CXXFLAGS += -Wno-unused-private-field - ARFLAGS = rc - else - # *nix Only Flags/Libs - CFLAGS += -Wno-unused-but-set-variable - CXXFLAGS += -Wno-unused-but-set-variable - endif - -endif - -# Output -OUTPUT = $(shell basename "$(CURDIR)").a - -main: build - -rebuild: clean build - -build: $(OBJS) - ar $(ARFLAGS) $(OUTPUT) $(OBJS) - -clean: - rm -rf $(OUTPUT) $(OBJS) \ No newline at end of file diff --git a/lib/libhac/source/AccessControlInfo.cpp b/lib/libhac/source/AccessControlInfo.cpp deleted file mode 100644 index 438b648..0000000 --- a/lib/libhac/source/AccessControlInfo.cpp +++ /dev/null @@ -1,173 +0,0 @@ -#include - -nn::hac::AccessControlInfo::AccessControlInfo() -{ - clear(); -} - -nn::hac::AccessControlInfo::AccessControlInfo(const AccessControlInfo & other) -{ - *this = other; -} - -void nn::hac::AccessControlInfo::operator=(const AccessControlInfo & other) -{ - mRawBinary = other.mRawBinary; - mProgramId = other.mProgramId; - mFileSystemAccessControl = other.mFileSystemAccessControl; - mServiceAccessControl = other.mServiceAccessControl; - mKernelCapabilities = other.mKernelCapabilities; -} - -bool nn::hac::AccessControlInfo::operator==(const AccessControlInfo & other) const -{ - return (mProgramId == other.mProgramId) \ - && (mFileSystemAccessControl == other.mFileSystemAccessControl) \ - && (mServiceAccessControl == other.mServiceAccessControl) \ - && (mKernelCapabilities == other.mKernelCapabilities); -} - -bool nn::hac::AccessControlInfo::operator!=(const AccessControlInfo & other) const -{ - return !(*this == other); -} - -void nn::hac::AccessControlInfo::toBytes() -{ - // serialise the sections - mFileSystemAccessControl.toBytes(); - mServiceAccessControl.toBytes(); - mKernelCapabilities.toBytes(); - - // determine section layout - struct sLayout { - uint32_t offset, size; - } fac, sac, kc; - - fac.offset = (uint32_t)align(sizeof(sAciHeader), aci::kSectionAlignSize); - fac.size = (uint32_t)mFileSystemAccessControl.getBytes().size(); - sac.offset = (uint32_t)align(fac.offset + fac.size, aci::kSectionAlignSize); - sac.size = (uint32_t)mServiceAccessControl.getBytes().size(); - kc.offset = (uint32_t)align(sac.offset + sac.size, aci::kSectionAlignSize); - kc.size = (uint32_t)mKernelCapabilities.getBytes().size(); - - // get total size - size_t total_size = _MAX(_MAX(fac.offset + fac.size, sac.offset + sac.size), kc.offset + kc.size); - - mRawBinary.alloc(total_size); - sAciHeader* hdr = (sAciHeader*)mRawBinary.data(); - - // set type - hdr->st_magic = aci::kAciStructMagic; - - // set program id - hdr->program_id = mProgramId; - - // set offset/size - hdr->fac.offset = fac.offset; - hdr->fac.size = fac.size; - hdr->sac.offset = sac.offset; - hdr->sac.size = sac.size; - hdr->kc.offset = kc.offset; - hdr->kc.size = kc.size; - - // write data - memcpy(mRawBinary.data() + fac.offset, mFileSystemAccessControl.getBytes().data(), fac.size); - memcpy(mRawBinary.data() + sac.offset, mServiceAccessControl.getBytes().data(), sac.size); - memcpy(mRawBinary.data() + kc.offset, mKernelCapabilities.getBytes().data(), kc.size); -} - -void nn::hac::AccessControlInfo::fromBytes(const byte_t* data, size_t len) -{ - // check size - if (len < sizeof(sAciHeader)) - { - throw fnd::Exception(kModuleName, "AccessControlInfo binary is too small"); - } - - // clear variables - clear(); - - // save a copy of the header - sAciHeader hdr; - memcpy((void*)&hdr, data, sizeof(sAciHeader)); - - // check magic - if (hdr.st_magic.get() != aci::kAciStructMagic) - { - throw fnd::Exception(kModuleName, "AccessControlInfo header corrupt"); - } - - // get total size - size_t total_size = _MAX(_MAX(hdr.fac.offset.get() + hdr.fac.size.get(), hdr.sac.offset.get() + hdr.sac.size.get()), hdr.kc.offset.get() + hdr.kc.size.get()); - - // validate binary size - if (len < total_size) - { - throw fnd::Exception(kModuleName, "AccessControlInfo binary is too small"); - } - - // allocate memory for header - mRawBinary.alloc(total_size); - memcpy(mRawBinary.data(), data, mRawBinary.size()); - - // save variables - mProgramId = hdr.program_id.get(); - mFileSystemAccessControl.fromBytes(mRawBinary.data() + hdr.fac.offset.get(), hdr.fac.size.get()); - mServiceAccessControl.fromBytes(mRawBinary.data() + hdr.sac.offset.get(), hdr.sac.size.get()); - mKernelCapabilities.fromBytes(mRawBinary.data() + hdr.kc.offset.get(), hdr.kc.size.get()); -} - -const fnd::Vec& nn::hac::AccessControlInfo::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::AccessControlInfo::clear() -{ - mRawBinary.clear(); - mProgramId = 0; - mFileSystemAccessControl.clear(); - mServiceAccessControl.clear(); - mKernelCapabilities.clear(); -} - -uint64_t nn::hac::AccessControlInfo::getProgramId() const -{ - return mProgramId; -} - -void nn::hac::AccessControlInfo::setProgramId(uint64_t program_id) -{ - mProgramId = program_id; -} - -const nn::hac::FileSystemAccessControl& nn::hac::AccessControlInfo::getFileSystemAccessControl() const -{ - return mFileSystemAccessControl; -} - -void nn::hac::AccessControlInfo::setFileSystemAccessControl(const nn::hac::FileSystemAccessControl& fac) -{ - mFileSystemAccessControl = fac; -} - -const nn::hac::ServiceAccessControl& nn::hac::AccessControlInfo::getServiceAccessControl() const -{ - return mServiceAccessControl; -} - -void nn::hac::AccessControlInfo::setServiceAccessControl(const nn::hac::ServiceAccessControl& sac) -{ - mServiceAccessControl = sac; -} - -const nn::hac::KernelCapabilityControl& nn::hac::AccessControlInfo::getKernelCapabilities() const -{ - return mKernelCapabilities; -} - -void nn::hac::AccessControlInfo::setKernelCapabilities(const nn::hac::KernelCapabilityControl& kc) -{ - mKernelCapabilities = kc; -} \ No newline at end of file diff --git a/lib/libhac/source/AccessControlInfoDesc.cpp b/lib/libhac/source/AccessControlInfoDesc.cpp deleted file mode 100644 index fa6fff7..0000000 --- a/lib/libhac/source/AccessControlInfoDesc.cpp +++ /dev/null @@ -1,251 +0,0 @@ -#include - -nn::hac::AccessControlInfoDesc::AccessControlInfoDesc() -{ - clear(); -} - -nn::hac::AccessControlInfoDesc::AccessControlInfoDesc(const AccessControlInfoDesc & other) -{ - *this = other; -} - -void nn::hac::AccessControlInfoDesc::operator=(const AccessControlInfoDesc & other) -{ - mRawBinary = other.mRawBinary; - mContentArchiveHeaderSignature2Key = other.mContentArchiveHeaderSignature2Key; - mFlags = other.mFlags; - mProgramIdRestrict = other.mProgramIdRestrict; - mFileSystemAccessControl = other.mFileSystemAccessControl; - mServiceAccessControl = other.mServiceAccessControl; - mKernelCapabilities = other.mKernelCapabilities; -} - -bool nn::hac::AccessControlInfoDesc::operator==(const AccessControlInfoDesc & other) const -{ - return (mContentArchiveHeaderSignature2Key == other.mContentArchiveHeaderSignature2Key) \ - && (mFlags == other.mFlags) \ - && (mProgramIdRestrict == other.mProgramIdRestrict) \ - && (mFileSystemAccessControl == other.mFileSystemAccessControl) \ - && (mServiceAccessControl == other.mServiceAccessControl) \ - && (mKernelCapabilities == other.mKernelCapabilities); -} - -bool nn::hac::AccessControlInfoDesc::operator!=(const AccessControlInfoDesc & other) const -{ - return !(*this == other); -} - -void nn::hac::AccessControlInfoDesc::toBytes() -{ - // serialise the sections - mFileSystemAccessControl.toBytes(); - mServiceAccessControl.toBytes(); - mKernelCapabilities.toBytes(); - - // determine section layout - struct sLayout { - uint32_t offset, size; - } fac, sac, kc; - - fac.offset = (uint32_t)align(sizeof(sAciDescHeader), aci::kSectionAlignSize); - fac.size = (uint32_t)mFileSystemAccessControl.getBytes().size(); - sac.offset = (uint32_t)align(fac.offset + fac.size, aci::kSectionAlignSize); - sac.size = (uint32_t)mServiceAccessControl.getBytes().size(); - kc.offset = (uint32_t)align(sac.offset + sac.size, aci::kSectionAlignSize); - kc.size = (uint32_t)mKernelCapabilities.getBytes().size(); - - // get total size - size_t total_size = _MAX(_MAX(fac.offset + fac.size, sac.offset + sac.size), kc.offset + kc.size); - - mRawBinary.alloc(total_size); - sAciDescHeader* hdr = (sAciDescHeader*)mRawBinary.data(); - - // set rsa modulus - memcpy(hdr->nca_rsa_signature2_modulus, mContentArchiveHeaderSignature2Key.modulus, fnd::rsa::kRsa2048Size); - - // set type - hdr->st_magic = aci::kAciDescStructMagic; - - // set "acid size" - hdr->signed_size = (uint32_t)(total_size - fnd::rsa::kRsa2048Size); - - // set flags - uint32_t flags = 0; - for (size_t i = 0; i < mFlags.size(); i++) - flags |= _BIT(mFlags[i]); - hdr->flags = flags; - - // set program id restrict settings - hdr->program_id_min = mProgramIdRestrict.min; - hdr->program_id_max = mProgramIdRestrict.max; - - // set offset/size - hdr->fac.offset = fac.offset; - hdr->fac.size = fac.size; - hdr->sac.offset = sac.offset; - hdr->sac.size = sac.size; - hdr->kc.offset = kc.offset; - hdr->kc.size = kc.size; - - // write data - memcpy(mRawBinary.data() + fac.offset, mFileSystemAccessControl.getBytes().data(), fac.size); - memcpy(mRawBinary.data() + sac.offset, mServiceAccessControl.getBytes().data(), sac.size); - memcpy(mRawBinary.data() + kc.offset, mKernelCapabilities.getBytes().data(), kc.size); -} - -void nn::hac::AccessControlInfoDesc::fromBytes(const byte_t* data, size_t len) -{ - // check size - if (len < sizeof(sAciDescHeader)) - { - throw fnd::Exception(kModuleName, "AccessControlInfoDesc binary is too small"); - } - - // clear variables - clear(); - - // save a copy of the header - sAciDescHeader hdr; - memcpy((void*)&hdr, data, sizeof(sAciDescHeader)); - - // check magic - if (hdr.st_magic.get() != aci::kAciDescStructMagic) - { - throw fnd::Exception(kModuleName, "AccessControlInfoDesc header corrupt"); - } - - // get total size - size_t total_size = _MAX(_MAX(hdr.fac.offset.get() + hdr.fac.size.get(), hdr.sac.offset.get() + hdr.sac.size.get()), hdr.kc.offset.get() + hdr.kc.size.get()); - - // validate binary size - if (len < total_size) - { - throw fnd::Exception(kModuleName, "AccessControlInfoDesc binary is too small"); - } - - // allocate memory for header - mRawBinary.alloc(total_size); - memcpy(mRawBinary.data(), data, mRawBinary.size()); - - // save variables - memcpy(mContentArchiveHeaderSignature2Key.modulus, hdr.nca_rsa_signature2_modulus, fnd::rsa::kRsa2048Size); - - for (size_t i = 0; i < 32; i++) - { - if (_HAS_BIT(hdr.flags.get(), i)) - mFlags.addElement((aci::Flag)i); - } - - mProgramIdRestrict.min = hdr.program_id_min.get(); - mProgramIdRestrict.max = hdr.program_id_max.get(); - - mFileSystemAccessControl.fromBytes(mRawBinary.data() + hdr.fac.offset.get(), hdr.fac.size.get()); - mServiceAccessControl.fromBytes(mRawBinary.data() + hdr.sac.offset.get(), hdr.sac.size.get()); - mKernelCapabilities.fromBytes(mRawBinary.data() + hdr.kc.offset.get(), hdr.kc.size.get()); -} - -const fnd::Vec& nn::hac::AccessControlInfoDesc::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::AccessControlInfoDesc::generateSignature(const fnd::rsa::sRsa2048Key& key) -{ - if (mRawBinary.size() == 0) - toBytes(); - - byte_t hash[fnd::sha::kSha256HashLen]; - fnd::sha::Sha256(mRawBinary.data() + fnd::rsa::kRsa2048Size, mRawBinary.size() - fnd::rsa::kRsa2048Size, hash); - - if (fnd::rsa::pss::rsaSign(key, fnd::sha::HASH_SHA256, hash, mRawBinary.data()) != 0) - { - throw fnd::Exception(kModuleName, "Failed to sign Access Control Info Desc"); - } -} - -void nn::hac::AccessControlInfoDesc::validateSignature(const fnd::rsa::sRsa2048Key& key) const -{ - if (mRawBinary.size() == 0) - throw fnd::Exception(kModuleName, "No Access Control Info Desc binary exists to verify"); - - byte_t hash[fnd::sha::kSha256HashLen]; - fnd::sha::Sha256(mRawBinary.data() + fnd::rsa::kRsa2048Size, mRawBinary.size() - fnd::rsa::kRsa2048Size, hash); - - if (fnd::rsa::pss::rsaVerify(key, fnd::sha::HASH_SHA256, hash, mRawBinary.data()) != 0) - { - throw fnd::Exception(kModuleName, "Failed to verify Access Control Info Desc"); - } -} - -void nn::hac::AccessControlInfoDesc::clear() -{ - mRawBinary.clear(); - memset((void*)&mContentArchiveHeaderSignature2Key, 0, sizeof(mContentArchiveHeaderSignature2Key)); - mFlags.clear(); - mProgramIdRestrict.min = 0; - mProgramIdRestrict.max = 0; - mFileSystemAccessControl.clear(); - mServiceAccessControl.clear(); - mKernelCapabilities.clear(); -} - -const fnd::rsa::sRsa2048Key& nn::hac::AccessControlInfoDesc::getContentArchiveHeaderSignature2Key() const -{ - return mContentArchiveHeaderSignature2Key; -} - -void nn::hac::AccessControlInfoDesc::setContentArchiveHeaderSignature2Key(const fnd::rsa::sRsa2048Key& key) -{ - mContentArchiveHeaderSignature2Key = key; -} - -const fnd::List& nn::hac::AccessControlInfoDesc::getFlagList() const -{ - return mFlags; -} - -void nn::hac::AccessControlInfoDesc::setFlagList(const fnd::List& flags) -{ - mFlags = flags; -} - -const nn::hac::AccessControlInfoDesc::sProgramIdRestrict& nn::hac::AccessControlInfoDesc::getProgramIdRestrict() const -{ - return mProgramIdRestrict; -} - -void nn::hac::AccessControlInfoDesc::setProgramIdRestrict(const sProgramIdRestrict& pid_restrict) -{ - mProgramIdRestrict = pid_restrict; -} - -const nn::hac::FileSystemAccessControl& nn::hac::AccessControlInfoDesc::getFileSystemAccessControl() const -{ - return mFileSystemAccessControl; -} - -void nn::hac::AccessControlInfoDesc::setFileSystemAccessControl(const nn::hac::FileSystemAccessControl& fac) -{ - mFileSystemAccessControl = fac; -} - -const nn::hac::ServiceAccessControl& nn::hac::AccessControlInfoDesc::getServiceAccessControl() const -{ - return mServiceAccessControl; -} - -void nn::hac::AccessControlInfoDesc::setServiceAccessControl(const nn::hac::ServiceAccessControl& sac) -{ - mServiceAccessControl = sac; -} - -const nn::hac::KernelCapabilityControl& nn::hac::AccessControlInfoDesc::getKernelCapabilities() const -{ - return mKernelCapabilities; -} - -void nn::hac::AccessControlInfoDesc::setKernelCapabilities(const nn::hac::KernelCapabilityControl& kc) -{ - mKernelCapabilities = kc; -} \ No newline at end of file diff --git a/lib/libhac/source/AddOnContentMetaExtendedHeader.cpp b/lib/libhac/source/AddOnContentMetaExtendedHeader.cpp deleted file mode 100644 index 8d3f640..0000000 --- a/lib/libhac/source/AddOnContentMetaExtendedHeader.cpp +++ /dev/null @@ -1,84 +0,0 @@ -#include - -nn::hac::AddOnContentMetaExtendedHeader::AddOnContentMetaExtendedHeader() -{ - clear(); -} - -nn::hac::AddOnContentMetaExtendedHeader::AddOnContentMetaExtendedHeader(const AddOnContentMetaExtendedHeader& other) -{ - *this = other; -} - -void nn::hac::AddOnContentMetaExtendedHeader::operator=(const AddOnContentMetaExtendedHeader& other) -{ - clear(); - mRawBinary = other.mRawBinary; - mApplicationId = other.mApplicationId; - mRequiredApplicationVersion = other.mRequiredApplicationVersion; -} - -bool nn::hac::AddOnContentMetaExtendedHeader::operator==(const AddOnContentMetaExtendedHeader& other) const -{ - return (mApplicationId == other.mApplicationId) \ - && (mRequiredApplicationVersion == other.mRequiredApplicationVersion); -} - -bool nn::hac::AddOnContentMetaExtendedHeader::operator!=(const AddOnContentMetaExtendedHeader& other) const -{ - return !(*this == other); -} - -void nn::hac::AddOnContentMetaExtendedHeader::toBytes() -{ - mRawBinary.alloc(sizeof(sAddOnContentMetaExtendedHeader)); - sAddOnContentMetaExtendedHeader* info = (sAddOnContentMetaExtendedHeader*)mRawBinary.data(); - - info->application_id = mApplicationId; - info->required_application_version = mRequiredApplicationVersion; -} - -void nn::hac::AddOnContentMetaExtendedHeader::fromBytes(const byte_t* bytes, size_t len) -{ - if (len < sizeof(sAddOnContentMetaExtendedHeader)) - { - throw fnd::Exception(kModuleName, "AddOnContentMetaExtendedHeader too small"); - } - - const sAddOnContentMetaExtendedHeader* info = (const sAddOnContentMetaExtendedHeader*)bytes; - - mApplicationId = info->application_id.get(); - mRequiredApplicationVersion = info->required_application_version.get(); -} - -const fnd::Vec& nn::hac::AddOnContentMetaExtendedHeader::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::AddOnContentMetaExtendedHeader::clear() -{ - mRawBinary.clear(); - mApplicationId = 0; - mRequiredApplicationVersion = 0; -} - -uint64_t nn::hac::AddOnContentMetaExtendedHeader::getApplicationId() const -{ - return mApplicationId; -} - -void nn::hac::AddOnContentMetaExtendedHeader::setApplicationId(uint64_t application_id) -{ - mApplicationId = application_id; -} - -uint32_t nn::hac::AddOnContentMetaExtendedHeader::getRequiredApplicationVersion() const -{ - return mRequiredApplicationVersion; -} - -void nn::hac::AddOnContentMetaExtendedHeader::setRequiredApplicationVersion(uint32_t sys_ver) -{ - mRequiredApplicationVersion = sys_ver; -} \ No newline at end of file diff --git a/lib/libhac/source/AesKeygen.cpp b/lib/libhac/source/AesKeygen.cpp deleted file mode 100644 index 12d7878..0000000 --- a/lib/libhac/source/AesKeygen.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include - -void nn::hac::AesKeygen::generateKey(byte_t* dst, const byte_t* src, const byte_t* src_key) -{ - fnd::aes::AesEcbDecrypt(src, sizeof(fnd::aes::sAes128Key), src_key, dst); -} - -void nn::hac::AesKeygen::generateKey(byte_t* dst, const byte_t* src1, const byte_t* src2, const byte_t* src1_key) -{ - fnd::aes::sAes128Key src2_key; - generateKey(src2_key.key, src1, src1_key); - generateKey(dst, src2, src2_key.key); -} -void nn::hac::AesKeygen::generateKey(byte_t* dst, const byte_t* src1, const byte_t* src2, const byte_t* src3, const byte_t* src1_key) -{ - fnd::aes::sAes128Key src3_key; - generateKey(src3_key.key, src1, src2, src1_key); - generateKey(dst, src3, src3_key.key); -} \ No newline at end of file diff --git a/lib/libhac/source/ApplicationControlProperty.cpp b/lib/libhac/source/ApplicationControlProperty.cpp deleted file mode 100644 index 82d94a1..0000000 --- a/lib/libhac/source/ApplicationControlProperty.cpp +++ /dev/null @@ -1,731 +0,0 @@ -#include -#include - -nn::hac::ApplicationControlProperty::ApplicationControlProperty() -{ - clear(); -} - -nn::hac::ApplicationControlProperty::ApplicationControlProperty(const ApplicationControlProperty& other) -{ - *this = other; -} - -void nn::hac::ApplicationControlProperty::operator=(const ApplicationControlProperty& other) -{ - clear(); - mTitle = other.mTitle; - mIsbn = other.mIsbn; - mStartupUserAccount = other.mStartupUserAccount; - mUserAccountSwitchLockValue = other.mUserAccountSwitchLockValue; - mAocRegistrationType = other.mAocRegistrationType; - mAttributeFlag = other.mAttributeFlag; - mSupportedLanguages = other.mSupportedLanguages; - mParentalControlFlag = other.mParentalControlFlag; - mScreenshotMode = other.mScreenshotMode; - mVideoCaptureMode = other.mVideoCaptureMode; - mDataLossConfirmation = other.mDataLossConfirmation; - mPlayLogPolicy = other.mPlayLogPolicy; - mPresenceGroupId = other.mPresenceGroupId; - mRatingAge = other.mRatingAge; - mDisplayVersion = other.mDisplayVersion; - mAocBaseId = other.mAocBaseId; - mSaveDatawOwnerId = other.mSaveDatawOwnerId; - mUserAccountSaveDataSize = other.mUserAccountSaveDataSize; - mDeviceSaveDataSize = other.mDeviceSaveDataSize; - mBcatDeliveryCacheStorageSize = other.mBcatDeliveryCacheStorageSize; - mApplicationErrorCodeCategory = other.mApplicationErrorCodeCategory; - mLocalCommunicationId = other.mLocalCommunicationId; - mLogoType = other.mLogoType; - mLogoHandling = other.mLogoHandling; - mRuntimeAocInstallMode = other.mRuntimeAocInstallMode; - mCrashReportMode = other.mCrashReportMode; - mHdcp = other.mHdcp; - mSeedForPsuedoDeviceId = other.mSeedForPsuedoDeviceId; - mBcatPassphase = other.mBcatPassphase; - mUserAccountSaveDataMax = other.mUserAccountSaveDataMax; - mDeviceSaveDataMax = other.mDeviceSaveDataMax; - mTemporaryStorageSize = other.mTemporaryStorageSize; - mCacheStorageSize = other.mCacheStorageSize; - mCacheStorageDataAndJournalSizeMax = other.mCacheStorageDataAndJournalSizeMax; - mCacheStorageIndexMax = other.mCacheStorageIndexMax; - mPlayLogQueryableApplicationId = other.mPlayLogQueryableApplicationId; - mPlayLogQueryCapability = other.mPlayLogQueryCapability; - mRepairFlag = other.mRepairFlag; - mProgramIndex = other.mProgramIndex; - mRequiredNetworkServiceLicenseOnLaunchValue = other.mRequiredNetworkServiceLicenseOnLaunchValue; -} - -bool nn::hac::ApplicationControlProperty::operator==(const ApplicationControlProperty& other) const -{ - return (mTitle == other.mTitle) \ - && (mIsbn == other.mIsbn) \ - && (mStartupUserAccount == other.mStartupUserAccount) \ - && (mUserAccountSwitchLockValue == other.mUserAccountSwitchLockValue) \ - && (mAocRegistrationType == other.mAocRegistrationType) \ - && (mAttributeFlag == other.mAttributeFlag) \ - && (mSupportedLanguages == other.mSupportedLanguages) \ - && (mParentalControlFlag == other.mParentalControlFlag) \ - && (mScreenshotMode == other.mScreenshotMode) \ - && (mVideoCaptureMode == other.mVideoCaptureMode) \ - && (mDataLossConfirmation == other.mDataLossConfirmation) \ - && (mPlayLogPolicy == other.mPlayLogPolicy) \ - && (mPresenceGroupId == other.mPresenceGroupId) \ - && (mRatingAge == other.mRatingAge) \ - && (mDisplayVersion == other.mDisplayVersion) \ - && (mAocBaseId == other.mAocBaseId) \ - && (mSaveDatawOwnerId == other.mSaveDatawOwnerId) \ - && (mUserAccountSaveDataSize == other.mUserAccountSaveDataSize) \ - && (mDeviceSaveDataSize == other.mDeviceSaveDataSize) \ - && (mBcatDeliveryCacheStorageSize == other.mBcatDeliveryCacheStorageSize) \ - && (mApplicationErrorCodeCategory == other.mApplicationErrorCodeCategory) \ - && (mLocalCommunicationId == other.mLocalCommunicationId) \ - && (mLogoType == other.mLogoType) \ - && (mLogoHandling == other.mLogoHandling) \ - && (mRuntimeAocInstallMode == other.mRuntimeAocInstallMode) \ - && (mCrashReportMode == other.mCrashReportMode) \ - && (mHdcp == other.mHdcp) \ - && (mSeedForPsuedoDeviceId == other.mSeedForPsuedoDeviceId) \ - && (mBcatPassphase == other.mBcatPassphase) \ - && (mUserAccountSaveDataMax == other.mUserAccountSaveDataMax) \ - && (mDeviceSaveDataMax == other.mDeviceSaveDataMax) \ - && (mTemporaryStorageSize == other.mTemporaryStorageSize) \ - && (mCacheStorageSize == other.mCacheStorageSize) \ - && (mCacheStorageDataAndJournalSizeMax == other.mCacheStorageDataAndJournalSizeMax) \ - && (mCacheStorageIndexMax == other.mCacheStorageIndexMax) \ - && (mPlayLogQueryableApplicationId == other.mPlayLogQueryableApplicationId) \ - && (mPlayLogQueryCapability == other.mPlayLogQueryCapability) \ - && (mRepairFlag == other.mRepairFlag) \ - && (mProgramIndex == other.mProgramIndex) \ - && (mRequiredNetworkServiceLicenseOnLaunchValue == other.mRequiredNetworkServiceLicenseOnLaunchValue); -} - -bool nn::hac::ApplicationControlProperty::operator!=(const ApplicationControlProperty& other) const -{ - return !(*this == other); -} - -void nn::hac::ApplicationControlProperty::toBytes() -{ - mRawBinary.alloc(sizeof(nn::hac::sApplicationControlProperty)); - - sApplicationControlProperty* data = (sApplicationControlProperty*)mRawBinary.data(); - - // strings - for (size_t i = 0; i < mTitle.size(); i++) - { - strncpy(data->title[mTitle[i].language].name, mTitle[i].name.c_str(), nacp::kNameLength); - strncpy(data->title[mTitle[i].language].publisher, mTitle[i].publisher.c_str(), nacp::kPublisherLength); - } - - uint32_t supported_langs = 0; - for (size_t i = 0; i < mSupportedLanguages.size(); i++) - { - supported_langs |= _BIT(mSupportedLanguages[i]); - } - data->supported_language_flag = supported_langs; - - strncpy(data->isbn, mIsbn.c_str(), nacp::kIsbnLength); - strncpy(data->display_version, mDisplayVersion.c_str(), nacp::kDisplayVersionLength); - strncpy(data->application_error_code_category, mApplicationErrorCodeCategory.c_str(), nacp::kApplicationErrorCodeCategoryLength); - strncpy(data->bcat_passphrase, mBcatPassphase.c_str(), nacp::kBcatPassphraseLength); - - // enum type casts - data->startup_user_account = mStartupUserAccount; - data->user_account_switch_lock = mUserAccountSwitchLockValue; - data->add_on_content_registration_type = mAocRegistrationType; - data->attribute_flag = mAttributeFlag; - data->parental_control_flag = mParentalControlFlag; - data->screenshot = mScreenshotMode; - data->video_capture = mVideoCaptureMode; - data->data_loss_confirmation = mDataLossConfirmation; - data->play_log_policy = mPlayLogPolicy; - data->logo_type = mLogoType; - data->logo_handling = mLogoHandling; - data->runtime_add_on_content_install = mRuntimeAocInstallMode; - data->crash_report = mCrashReportMode; - data->hdcp = mHdcp; - data->play_log_query_capability = mPlayLogQueryCapability; - data->repair_flag = mRepairFlag; - data->required_network_service_license_on_launch_flag = mRequiredNetworkServiceLicenseOnLaunchValue; - - // misc params - data->presence_group_id = mPresenceGroupId; - memset(data->rating_age, nacp::kUnusedAgeRating, nacp::kRatingAgeCount); // clear ratings - for (size_t i = 0; i < mRatingAge.size(); i++) - { - data->rating_age[mRatingAge[i].organisation] = mRatingAge[i].age; - } - data->add_on_content_base_id = mAocBaseId; - data->save_data_owner_id = mSaveDatawOwnerId; - for (size_t i = 0; i < mLocalCommunicationId.size() && i < nacp::kLocalCommunicationIdCount; i++) - { - data->local_communication_id[i] = mLocalCommunicationId[i]; - } - data->seed_for_pseudo_device_id = mSeedForPsuedoDeviceId; - for (size_t i = 0; i < mPlayLogQueryableApplicationId.size() && i < nacp::kPlayLogQueryableApplicationIdCount; i++) - { - data->play_log_queryable_application_id[i] = mPlayLogQueryableApplicationId[i]; - } - data->cache_storage_index_max = mCacheStorageIndexMax; - data->program_index = mProgramIndex; - - // sizes - data->user_account_save_data_size = mUserAccountSaveDataSize.size; - data->user_account_save_data_journal_size = mUserAccountSaveDataSize.journal_size; - data->device_save_data_size = mDeviceSaveDataSize.size; - data->device_save_data_journal_size = mDeviceSaveDataSize.journal_size; - data->bcat_delivery_cache_storage_size = mBcatDeliveryCacheStorageSize; - data->user_account_save_data_size_max = mUserAccountSaveDataMax.size; - data->user_account_save_data_journal_size_max = mUserAccountSaveDataMax.journal_size; - data->device_save_data_size_max = mDeviceSaveDataMax.size; - data->device_save_data_journal_size_max = mDeviceSaveDataMax.journal_size; - data->temporary_storage_size = mTemporaryStorageSize; - data->cache_storage_size = mCacheStorageSize.size; - data->cache_storage_journal_size = mCacheStorageSize.journal_size; - data->cache_storage_data_and_journal_size_max = mCacheStorageDataAndJournalSizeMax; -} - -void nn::hac::ApplicationControlProperty::fromBytes(const byte_t* bytes, size_t len) -{ - if (len < sizeof(nn::hac::sApplicationControlProperty)) - { - throw fnd::Exception(kModuleName, "NACP too small"); - } - - clear(); - - mRawBinary.alloc(sizeof(nn::hac::sApplicationControlProperty)); - memcpy(mRawBinary.data(), bytes, mRawBinary.size()); - - const sApplicationControlProperty* data = (const sApplicationControlProperty*)mRawBinary.data(); - - // strings - for (size_t i = 0; i < nacp::kMaxLanguageCount; i++) - { - if (_HAS_BIT(data->supported_language_flag.get(), i)) - { - mSupportedLanguages.addElement((nacp::Language)i); - } - if (data->title[i].name[0] != '\0' && data->title[i].publisher[0] != '\0') - { - mTitle.addElement({ (nacp::Language)i, std::string(data->title[i].name, _MIN(strlen(data->title[i].name), nacp::kNameLength)), std::string(data->title[i].publisher, _MIN(strlen(data->title[i].publisher), nacp::kPublisherLength)) }); - } - } - - if (data->isbn[0] != 0) - mIsbn = std::string(data->isbn, _MIN(strlen(data->isbn), nacp::kIsbnLength)); - if (data->display_version[0] != 0) - mDisplayVersion = std::string(data->display_version, _MIN(strlen(data->display_version), nacp::kDisplayVersionLength)); - if (data->application_error_code_category[0] != 0) - mApplicationErrorCodeCategory = std::string(data->application_error_code_category, _MIN(strlen(data->application_error_code_category), nacp::kApplicationErrorCodeCategoryLength)); - if (data->bcat_passphrase[0] != 0) - mBcatPassphase = std::string(data->bcat_passphrase, _MIN(strlen(data->bcat_passphrase), nacp::kBcatPassphraseLength)); - - // enum type casts - mStartupUserAccount = (nacp::StartupUserAccount)data->startup_user_account; - mUserAccountSwitchLockValue = (nacp::UserAccountSwitchLockValue)data->user_account_switch_lock; - mAocRegistrationType = (nacp::AocRegistrationType)data->add_on_content_registration_type; - mAttributeFlag = (nacp::AttributeFlag)data->attribute_flag.get(); - mParentalControlFlag = (nacp::ParentalControlFlag)data->parental_control_flag.get(); - mScreenshotMode = (nacp::ScreenshotMode)data->screenshot; - mVideoCaptureMode = (nacp::VideoCaptureMode)data->video_capture; - mDataLossConfirmation = (nacp::DataLossConfirmation)data->data_loss_confirmation; - mPlayLogPolicy = (nacp::PlayLogPolicy)data->play_log_policy; - mLogoType = (nacp::LogoType)data->logo_type; - mLogoHandling = (nacp::LogoHandling)data->logo_handling; - mRuntimeAocInstallMode = (nacp::RuntimeAocInstallMode)data->runtime_add_on_content_install; - mCrashReportMode = (nacp::CrashReportMode)data->crash_report; - mHdcp = (nacp::Hdcp)data->hdcp; - mPlayLogQueryCapability = (nacp::PlayLogQueryCapability)data->play_log_query_capability; - mRepairFlag = (nacp::RepairFlag)data->repair_flag; - mRequiredNetworkServiceLicenseOnLaunchValue = (nacp::RequiredNetworkServiceLicenseOnLaunchValue)data->required_network_service_license_on_launch_flag; - - // misc params - mPresenceGroupId = data->presence_group_id.get(); - for (size_t i = 0; i < nacp::kRatingAgeCount; i++) - { - if (data->rating_age[i] != nacp::kUnusedAgeRating) - mRatingAge.addElement({(nacp::Organisation)i, data->rating_age[i]}); - } - mAocBaseId = data->add_on_content_base_id.get(); - mSaveDatawOwnerId = data->save_data_owner_id.get(); - for (size_t i = 0; i < nacp::kLocalCommunicationIdCount; i++) - { - if (data->local_communication_id[i].get() != 0) - mLocalCommunicationId.addElement(data->local_communication_id[i].get()); - } - mSeedForPsuedoDeviceId = data->seed_for_pseudo_device_id.get(); - for (size_t i = 0; i < nacp::kPlayLogQueryableApplicationIdCount; i++) - { - if (data->play_log_queryable_application_id[i].get() != 0) - mPlayLogQueryableApplicationId.addElement(data->play_log_queryable_application_id[i].get()); - } - mCacheStorageIndexMax = data->cache_storage_index_max.get(); - mProgramIndex = data->program_index; - - // sizes - mUserAccountSaveDataSize.size = (int64_t)data->user_account_save_data_size.get(); - mUserAccountSaveDataSize.journal_size = (int64_t)data->user_account_save_data_journal_size.get(); - mDeviceSaveDataSize.size = (int64_t)data->device_save_data_size.get(); - mDeviceSaveDataSize.journal_size = (int64_t)data->device_save_data_journal_size.get(); - mBcatDeliveryCacheStorageSize = (int64_t)data->bcat_delivery_cache_storage_size.get(); - mUserAccountSaveDataMax.size = (int64_t)data->user_account_save_data_size_max.get(); - mUserAccountSaveDataMax.journal_size = (int64_t)data->user_account_save_data_journal_size_max.get(); - mDeviceSaveDataMax.size = (int64_t)data->device_save_data_size_max.get(); - mDeviceSaveDataMax.journal_size = (int64_t)data->device_save_data_journal_size_max.get(); - mTemporaryStorageSize = (int64_t)data->temporary_storage_size.get(); - mCacheStorageSize.size = (int64_t)data->cache_storage_size.get(); - mCacheStorageSize.journal_size = (int64_t)data->cache_storage_journal_size.get(); - mCacheStorageDataAndJournalSizeMax = (int64_t)data->cache_storage_data_and_journal_size_max.get(); -} - -const fnd::Vec& nn::hac::ApplicationControlProperty::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::ApplicationControlProperty::clear() -{ - mRawBinary.clear(); - mTitle.clear(); - mIsbn.clear(); - mStartupUserAccount = nacp::USER_None; - mUserAccountSwitchLockValue = nacp::UASL_Disable; - mAocRegistrationType = nacp::AOC_AllOnLaunch; - mAttributeFlag = nacp::ATTR_None; - mSupportedLanguages.clear(); - mParentalControlFlag = nacp::PC_None; - mScreenshotMode = nacp::SCRN_Allow; - mVideoCaptureMode = nacp::VCAP_Disable; - mDataLossConfirmation = nacp::DLOSS_None; - mPlayLogPolicy = nacp::PLP_All; - mPresenceGroupId = 0; - mRatingAge.clear(); - mDisplayVersion.clear(); - mAocBaseId = 0; - mSaveDatawOwnerId = 0; - mUserAccountSaveDataSize = {0, 0}; - mDeviceSaveDataSize = {0, 0}; - mBcatDeliveryCacheStorageSize = 0; - mApplicationErrorCodeCategory.clear(); - mLocalCommunicationId.clear(); - mLogoType = nacp::LOGO_Nintendo; - mLogoHandling = nacp::LHND_Auto; - mRuntimeAocInstallMode = nacp::RTAOC_Deny; - mCrashReportMode = nacp::CREP_Deny; - mHdcp = nacp::HDCP_None; - mSeedForPsuedoDeviceId = 0; - mBcatPassphase.clear(); - mUserAccountSaveDataMax; - mDeviceSaveDataMax = {0, 0}; - mTemporaryStorageSize = 0; - mCacheStorageSize = {0, 0}; - mCacheStorageDataAndJournalSizeMax = 0; - mCacheStorageIndexMax = 0; - mPlayLogQueryableApplicationId.clear(); - mPlayLogQueryCapability = nacp::PLQC_None; - mRepairFlag = nacp::REPF_None; - mProgramIndex = 0; - mRequiredNetworkServiceLicenseOnLaunchValue = nacp::REQNETLIC_None; -} - -const fnd::List& nn::hac::ApplicationControlProperty::getTitle() const -{ - return mTitle; -} - -void nn::hac::ApplicationControlProperty::setTitle(const fnd::List& title) -{ - mTitle = title; -} - -const std::string& nn::hac::ApplicationControlProperty::getIsbn() const -{ - return mIsbn; -} - -void nn::hac::ApplicationControlProperty::setIsbn(const std::string& isbn) -{ - mIsbn = isbn; -} - -nn::hac::nacp::StartupUserAccount nn::hac::ApplicationControlProperty::getStartupUserAccount() const -{ - return mStartupUserAccount; -} - -void nn::hac::ApplicationControlProperty::setStartupUserAccount(nacp::StartupUserAccount var) -{ - mStartupUserAccount = var; -} - -nn::hac::nacp::UserAccountSwitchLockValue nn::hac::ApplicationControlProperty::getUserAccountSwitchLockValue() const -{ - return mUserAccountSwitchLockValue; -} - -void nn::hac::ApplicationControlProperty::setUserAccountSwitchLockValue(nacp::UserAccountSwitchLockValue var) -{ - mUserAccountSwitchLockValue = var; -} - -nn::hac::nacp::AocRegistrationType nn::hac::ApplicationControlProperty::getAocRegistrationType() const -{ - return mAocRegistrationType; -} - -void nn::hac::ApplicationControlProperty::setAocRegistrationType(nacp::AocRegistrationType var) -{ - mAocRegistrationType = var; -} - -nn::hac::nacp::AttributeFlag nn::hac::ApplicationControlProperty::getAttributeFlag() const -{ - return mAttributeFlag; -} - -void nn::hac::ApplicationControlProperty::setAttributeFlag(nacp::AttributeFlag var) -{ - mAttributeFlag = var; -} - -const fnd::List& nn::hac::ApplicationControlProperty::getSupportedLanguages() const -{ - return mSupportedLanguages; -} - -void nn::hac::ApplicationControlProperty::setSupportedLanguages(const fnd::List& var) -{ - mSupportedLanguages = var; -} - -nn::hac::nacp::ParentalControlFlag nn::hac::ApplicationControlProperty::getParentalControlFlag() const -{ - return mParentalControlFlag; -} - -void nn::hac::ApplicationControlProperty::setParentalControlFlag(nacp::ParentalControlFlag var) -{ - mParentalControlFlag = var; -} - -nn::hac::nacp::ScreenshotMode nn::hac::ApplicationControlProperty::getScreenshotMode() const -{ - return mScreenshotMode; -} - -void nn::hac::ApplicationControlProperty::setScreenshotMode(nacp::ScreenshotMode var) -{ - mScreenshotMode = var; -} - -nn::hac::nacp::VideoCaptureMode nn::hac::ApplicationControlProperty::getVideoCaptureMode() const -{ - return mVideoCaptureMode; -} - -void nn::hac::ApplicationControlProperty::setVideoCaptureMode(nacp::VideoCaptureMode var) -{ - mVideoCaptureMode = var; -} - -nn::hac::nacp::DataLossConfirmation nn::hac::ApplicationControlProperty::getDataLossConfirmation() const -{ - return mDataLossConfirmation; -} - -void nn::hac::ApplicationControlProperty::setDataLossConfirmation(nacp::DataLossConfirmation var) -{ - mDataLossConfirmation = var; -} - -nn::hac::nacp::PlayLogPolicy nn::hac::ApplicationControlProperty::getPlayLogPolicy() const -{ - return mPlayLogPolicy; -} - -void nn::hac::ApplicationControlProperty::setPlayLogPolicy(nacp::PlayLogPolicy var) -{ - mPlayLogPolicy = var; -} - -uint64_t nn::hac::ApplicationControlProperty::getPresenceGroupId() const -{ - return mPresenceGroupId; -} - -void nn::hac::ApplicationControlProperty::setPresenceGroupId(uint64_t var) -{ - mPresenceGroupId = var; -} - -const fnd::List& nn::hac::ApplicationControlProperty::getRatingAge() const -{ - return mRatingAge; -} - -void nn::hac::ApplicationControlProperty::setRatingAge(const fnd::List& var) -{ - mRatingAge = var; -} - -const std::string& nn::hac::ApplicationControlProperty::getDisplayVersion() const -{ - return mDisplayVersion; -} - -void nn::hac::ApplicationControlProperty::setDisplayVersion(const std::string& var) -{ - mDisplayVersion = var; -} - -uint64_t nn::hac::ApplicationControlProperty::getAocBaseId() const -{ - return mAocBaseId; -} - -void nn::hac::ApplicationControlProperty::setAocBaseId(uint64_t var) -{ - mAocBaseId = var; -} - -uint64_t nn::hac::ApplicationControlProperty::getSaveDatawOwnerId() const -{ - return mSaveDatawOwnerId; -} - -void nn::hac::ApplicationControlProperty::setSaveDatawOwnerId(uint64_t var) -{ - mSaveDatawOwnerId = var; -} - -const nn::hac::ApplicationControlProperty::sStorageSize& nn::hac::ApplicationControlProperty::getUserAccountSaveDataSize() const -{ - return mUserAccountSaveDataSize; -} - -void nn::hac::ApplicationControlProperty::setUserAccountSaveDataSize(const sStorageSize& var) -{ - mUserAccountSaveDataSize = var; -} - -const nn::hac::ApplicationControlProperty::sStorageSize& nn::hac::ApplicationControlProperty::getDeviceSaveDataSize() const -{ - return mDeviceSaveDataSize; -} - -void nn::hac::ApplicationControlProperty::setDeviceSaveDataSize(const sStorageSize& var) -{ - mDeviceSaveDataSize = var; -} - -int64_t nn::hac::ApplicationControlProperty::getBcatDeliveryCacheStorageSize() const -{ - return mBcatDeliveryCacheStorageSize; -} - -void nn::hac::ApplicationControlProperty::setBcatDeliveryCacheStorageSize(int64_t var) -{ - mBcatDeliveryCacheStorageSize = var; -} - -const std::string& nn::hac::ApplicationControlProperty::getApplicationErrorCodeCategory() const -{ - return mApplicationErrorCodeCategory; -} - -void nn::hac::ApplicationControlProperty::setApplicationErrorCodeCategory(const std::string& var) -{ - mApplicationErrorCodeCategory = var; -} - -const fnd::List& nn::hac::ApplicationControlProperty::getLocalCommunicationId() const -{ - return mLocalCommunicationId; -} - -void nn::hac::ApplicationControlProperty::setLocalCommunicationId(const fnd::List& var) -{ - mLocalCommunicationId = var; -} - -nn::hac::nacp::LogoType nn::hac::ApplicationControlProperty::getLogoType() const -{ - return mLogoType; -} - -void nn::hac::ApplicationControlProperty::setLogoType(nacp::LogoType var) -{ - mLogoType = var; -} - -nn::hac::nacp::LogoHandling nn::hac::ApplicationControlProperty::getLogoHandling() const -{ - return mLogoHandling; -} - -void nn::hac::ApplicationControlProperty::setLogoHandling(nacp::LogoHandling var) -{ - mLogoHandling = var; -} - -nn::hac::nacp::RuntimeAocInstallMode nn::hac::ApplicationControlProperty::getRuntimeAocInstallMode() const -{ - return mRuntimeAocInstallMode; -} - -void nn::hac::ApplicationControlProperty::setRuntimeAocInstallMode(nacp::RuntimeAocInstallMode var) -{ - mRuntimeAocInstallMode = var; -} - -nn::hac::nacp::CrashReportMode nn::hac::ApplicationControlProperty::getCrashReportMode() const -{ - return mCrashReportMode; -} - -void nn::hac::ApplicationControlProperty::setCrashReportMode(nacp::CrashReportMode var) -{ - mCrashReportMode = var; -} - -nn::hac::nacp::Hdcp nn::hac::ApplicationControlProperty::getHdcp() const -{ - return mHdcp; -} - -void nn::hac::ApplicationControlProperty::setHdcp(nacp::Hdcp var) -{ - mHdcp = var; -} - -uint64_t nn::hac::ApplicationControlProperty::getSeedForPsuedoDeviceId() const -{ - return mSeedForPsuedoDeviceId; -} - -void nn::hac::ApplicationControlProperty::setSeedForPsuedoDeviceId(uint64_t var) -{ - mSeedForPsuedoDeviceId = var; -} - -const std::string& nn::hac::ApplicationControlProperty::getBcatPassphase() const -{ - return mBcatPassphase; -} - -void nn::hac::ApplicationControlProperty::setBcatPassphase(const std::string& var) -{ - mBcatPassphase = var; -} - -const nn::hac::ApplicationControlProperty::sStorageSize& nn::hac::ApplicationControlProperty::getUserAccountSaveDataMax() const -{ - return mUserAccountSaveDataMax; -} - -void nn::hac::ApplicationControlProperty::setUserAccountSaveDataMax(const sStorageSize& var) -{ - mUserAccountSaveDataMax = var; -} - -const nn::hac::ApplicationControlProperty::sStorageSize& nn::hac::ApplicationControlProperty::getDeviceSaveDataMax() const -{ - return mDeviceSaveDataMax; -} - -void nn::hac::ApplicationControlProperty::setDeviceSaveDataMax(const sStorageSize& var) -{ - mDeviceSaveDataMax = var; -} - -int64_t nn::hac::ApplicationControlProperty::getTemporaryStorageSize() const -{ - return mTemporaryStorageSize; -} - -void nn::hac::ApplicationControlProperty::setTemporaryStorageSize(int64_t var) -{ - mTemporaryStorageSize = var; -} - -const nn::hac::ApplicationControlProperty::sStorageSize& nn::hac::ApplicationControlProperty::getCacheStorageSize() const -{ - return mCacheStorageSize; -} - -void nn::hac::ApplicationControlProperty::setCacheStorageSize(const sStorageSize& var) -{ - mCacheStorageSize = var; -} - -int64_t nn::hac::ApplicationControlProperty::getCacheStorageDataAndJournalSizeMax() const -{ - return mCacheStorageDataAndJournalSizeMax; -} - -void nn::hac::ApplicationControlProperty::setCacheStorageDataAndJournalSizeMax(int64_t var) -{ - mCacheStorageDataAndJournalSizeMax = var; -} - -uint16_t nn::hac::ApplicationControlProperty::getCacheStorageIndexMax() const -{ - return mCacheStorageIndexMax; -} - -void nn::hac::ApplicationControlProperty::setCacheStorageIndexMax(uint16_t var) -{ - mCacheStorageIndexMax = var; -} - -const fnd::List& nn::hac::ApplicationControlProperty::getPlayLogQueryableApplicationId() const -{ - return mPlayLogQueryableApplicationId; -} - -void nn::hac::ApplicationControlProperty::setPlayLogQueryableApplicationId(const fnd::List& var) -{ - mPlayLogQueryableApplicationId = var; -} - -nn::hac::nacp::PlayLogQueryCapability nn::hac::ApplicationControlProperty::getPlayLogQueryCapability() const -{ - return mPlayLogQueryCapability; -} - -void nn::hac::ApplicationControlProperty::setPlayLogQueryCapability(nacp::PlayLogQueryCapability var) -{ - mPlayLogQueryCapability = var; -} - -nn::hac::nacp::RepairFlag nn::hac::ApplicationControlProperty::getRepairFlag() const -{ - return mRepairFlag; -} - -void nn::hac::ApplicationControlProperty::setRepairFlag(nacp::RepairFlag var) -{ - mRepairFlag = var; -} - -byte_t nn::hac::ApplicationControlProperty::getProgramIndex() const -{ - return mProgramIndex; -} - -void nn::hac::ApplicationControlProperty::setProgramIndex(byte_t var) -{ - mProgramIndex = var; -} - -nn::hac::nacp::RequiredNetworkServiceLicenseOnLaunchValue nn::hac::ApplicationControlProperty::getRequiredNetworkServiceLicenseOnLaunchValue() const -{ - return mRequiredNetworkServiceLicenseOnLaunchValue; -} - -void nn::hac::ApplicationControlProperty::setRequiredNetworkServiceLicenseOnLaunchValue(nacp::RequiredNetworkServiceLicenseOnLaunchValue var) -{ - mRequiredNetworkServiceLicenseOnLaunchValue = var; -} \ No newline at end of file diff --git a/lib/libhac/source/ApplicationControlPropertyUtils.cpp b/lib/libhac/source/ApplicationControlPropertyUtils.cpp deleted file mode 100644 index b0c3e7b..0000000 --- a/lib/libhac/source/ApplicationControlPropertyUtils.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include - -bool nn::hac::ApplicationControlPropertyUtils::validateSaveDataSizeMax(int64_t size, int64_t alignment) -{ - return (alignment != 0 && (size & (alignment - 1)) != 0) == false; -} - -bool nn::hac::ApplicationControlPropertyUtils::validateSaveDataSize(int64_t size) -{ - return (size & 0x3fff) == 0; -} diff --git a/lib/libhac/source/ApplicationMetaExtendedHeader.cpp b/lib/libhac/source/ApplicationMetaExtendedHeader.cpp deleted file mode 100644 index c037cd9..0000000 --- a/lib/libhac/source/ApplicationMetaExtendedHeader.cpp +++ /dev/null @@ -1,84 +0,0 @@ -#include - -nn::hac::ApplicationMetaExtendedHeader::ApplicationMetaExtendedHeader() -{ - clear(); -} - -nn::hac::ApplicationMetaExtendedHeader::ApplicationMetaExtendedHeader(const ApplicationMetaExtendedHeader& other) -{ - *this = other; -} - -void nn::hac::ApplicationMetaExtendedHeader::operator=(const ApplicationMetaExtendedHeader& other) -{ - clear(); - mRawBinary = other.mRawBinary; - mPatchId = other.mPatchId; - mRequiredSystemVersion = other.mRequiredSystemVersion; -} - -bool nn::hac::ApplicationMetaExtendedHeader::operator==(const ApplicationMetaExtendedHeader& other) const -{ - return (mPatchId == other.mPatchId) \ - && (mRequiredSystemVersion == other.mRequiredSystemVersion); -} - -bool nn::hac::ApplicationMetaExtendedHeader::operator!=(const ApplicationMetaExtendedHeader& other) const -{ - return !(*this == other); -} - -void nn::hac::ApplicationMetaExtendedHeader::toBytes() -{ - mRawBinary.alloc(sizeof(sApplicationMetaExtendedHeader)); - sApplicationMetaExtendedHeader* info = (sApplicationMetaExtendedHeader*)mRawBinary.data(); - - info->patch_id = mPatchId; - info->required_system_version = mRequiredSystemVersion; -} - -void nn::hac::ApplicationMetaExtendedHeader::fromBytes(const byte_t* bytes, size_t len) -{ - if (len < sizeof(sApplicationMetaExtendedHeader)) - { - throw fnd::Exception(kModuleName, "ApplicationMetaExtendedHeader too small"); - } - - const sApplicationMetaExtendedHeader* info = (const sApplicationMetaExtendedHeader*)bytes; - - mPatchId = info->patch_id.get(); - mRequiredSystemVersion = info->required_system_version.get(); -} - -const fnd::Vec& nn::hac::ApplicationMetaExtendedHeader::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::ApplicationMetaExtendedHeader::clear() -{ - mRawBinary.clear(); - mPatchId = 0; - mRequiredSystemVersion = 0; -} - -uint64_t nn::hac::ApplicationMetaExtendedHeader::getPatchId() const -{ - return mPatchId; -} - -void nn::hac::ApplicationMetaExtendedHeader::setPatchId(uint64_t application_id) -{ - mPatchId = application_id; -} - -uint32_t nn::hac::ApplicationMetaExtendedHeader::getRequiredSystemVersion() const -{ - return mRequiredSystemVersion; -} - -void nn::hac::ApplicationMetaExtendedHeader::setRequiredSystemVersion(uint32_t sys_ver) -{ - mRequiredSystemVersion = sys_ver; -} \ No newline at end of file diff --git a/lib/libhac/source/ContentArchiveHeader.cpp b/lib/libhac/source/ContentArchiveHeader.cpp deleted file mode 100644 index e5d51b4..0000000 --- a/lib/libhac/source/ContentArchiveHeader.cpp +++ /dev/null @@ -1,334 +0,0 @@ -#include - -nn::hac::ContentArchiveHeader::ContentArchiveHeader() -{ - mRightsId.alloc(nca::kRightsIdLen); - mKeyArea.alloc(nca::kKeyAreaSize); - clear(); -} - -nn::hac::ContentArchiveHeader::ContentArchiveHeader(const ContentArchiveHeader & other) : - ContentArchiveHeader() -{ - *this = other; -} - -bool nn::hac::ContentArchiveHeader::operator==(const ContentArchiveHeader & other) const -{ - return (mFormatVersion == other.mFormatVersion) \ - && (mDistributionType == other.mDistributionType) \ - && (mContentType == other.mContentType) \ - && (mKeyGeneration == other.mKeyGeneration) \ - && (mKaekIndex == other.mKaekIndex) \ - && (mContentSize == other.mContentSize) \ - && (mProgramId == other.mProgramId) \ - && (mContentIndex == other.mContentIndex) \ - && (mSdkAddonVersion == other.mSdkAddonVersion) \ - && (mRightsId == other.mRightsId) \ - && (mPartitionEntryList == other.mPartitionEntryList) \ - && (mKeyArea == other.mKeyArea); -} - -bool nn::hac::ContentArchiveHeader::operator!=(const ContentArchiveHeader & other) const -{ - return !(*this == other); -} - -void nn::hac::ContentArchiveHeader::operator=(const ContentArchiveHeader & other) -{ - mRawBinary = other.mRawBinary; - mDistributionType = other.mDistributionType; - mContentType = other.mContentType; - mKeyGeneration = other.mKeyGeneration; - mKaekIndex = other.mKaekIndex; - mContentSize = other.mContentSize; - mProgramId = other.mProgramId; - mContentIndex = other.mContentIndex; - mSdkAddonVersion = other.mSdkAddonVersion; - mRightsId = other.mRightsId; - mPartitionEntryList = other.mPartitionEntryList; - mKeyArea = other.mKeyArea; -} - -void nn::hac::ContentArchiveHeader::toBytes() -{ - mRawBinary.alloc(sizeof(sContentArchiveHeader)); - sContentArchiveHeader* hdr = (sContentArchiveHeader*)mRawBinary.data(); - - // set header magic - switch(mFormatVersion) - { - case (nca::FORMAT_NCA2): - hdr->st_magic = nca::kNca2StructMagic; - break; - case (nca::FORMAT_NCA3): - hdr->st_magic = nca::kNca3StructMagic; - break; - default: - throw fnd::Exception(kModuleName, "Unsupported format version"); - } - - // set variables - hdr->distribution_type = mDistributionType; - hdr->content_type = mContentType; - if (mKeyGeneration > 2) - { - hdr->key_generation = 2; - hdr->key_generation_2 = mKeyGeneration; - } - else - { - hdr->key_generation = mKeyGeneration; - hdr->key_generation_2 = 0; - } - hdr->key_area_encryption_key_index = mKaekIndex; - hdr->content_size = mContentSize; - hdr->program_id = mProgramId; - hdr->content_index = mContentIndex; - hdr->sdk_addon_version = mSdkAddonVersion; - memcpy(hdr->rights_id, mRightsId.data(), nca::kRightsIdLen); - memcpy(hdr->key_area, mKeyArea.data(), nca::kKeyAreaSize); - - for (size_t i = 0; i < mPartitionEntryList.size(); i++) - { - byte_t index = mPartitionEntryList[i].header_index; - - if (index >= nca::kPartitionNum) continue; - - hdr->partition_entry[index].start_blk = sizeToBlockNum(mPartitionEntryList[index].offset); - hdr->partition_entry[index].end_blk = (sizeToBlockNum(mPartitionEntryList[index].offset) + sizeToBlockNum(mPartitionEntryList[index].size)); - hdr->partition_entry[index].enabled = true; - hdr->fs_header_hash[index] = mPartitionEntryList[i].fs_header_hash; - } -} - -void nn::hac::ContentArchiveHeader::fromBytes(const byte_t * data, size_t len) -{ - if (len < sizeof(sContentArchiveHeader)) - { - throw fnd::Exception(kModuleName, "ContentArchive header size is too small"); - } - - clear(); - - mRawBinary.alloc(sizeof(sContentArchiveHeader)); - memcpy(mRawBinary.data(), data, sizeof(sContentArchiveHeader)); - - sContentArchiveHeader* hdr = (sContentArchiveHeader*)mRawBinary.data(); - - // check magic - switch(hdr->st_magic.get()) - { - case (nca::kNca2StructMagic) : - mFormatVersion = nca::FORMAT_NCA2; - break; - case (nca::kNca3StructMagic) : - mFormatVersion = nca::FORMAT_NCA3; - break; - throw fnd::Exception(kModuleName, "ContentArchive header corrupt (unrecognised header magic)."); - } - - // variables - mDistributionType = (nca::DistributionType)hdr->distribution_type; - mContentType = (nca::ContentType)hdr->content_type; - mKeyGeneration = _MAX(hdr->key_generation, hdr->key_generation_2); - mKaekIndex = hdr->key_area_encryption_key_index; - mContentSize = *hdr->content_size; - mProgramId = *hdr->program_id; - mContentIndex = *hdr->content_index; - mSdkAddonVersion = *hdr->sdk_addon_version; - memcpy(mRightsId.data(), hdr->rights_id, nca::kRightsIdLen); - memcpy(mKeyArea.data(), hdr->key_area, nca::kKeyAreaSize); - - for (size_t i = 0; i < nca::kPartitionNum; i++) - { - if (hdr->partition_entry[i].enabled) - { - mPartitionEntryList.addElement({(byte_t)i, blockNumToSize(hdr->partition_entry[i].start_blk.get()), blockNumToSize(hdr->partition_entry[i].end_blk.get() - hdr->partition_entry[i].start_blk.get()), hdr->fs_header_hash[i] }); - } - } -} - -const fnd::Vec& nn::hac::ContentArchiveHeader::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::ContentArchiveHeader::clear() -{ - mFormatVersion = nca::FORMAT_NCA3; - mDistributionType = nca::DIST_DOWNLOAD; - mContentType = nca::TYPE_PROGRAM; - mKeyGeneration = 0; - mKaekIndex = 0; - mContentSize = 0; - mProgramId = 0; - mContentIndex = 0; - mSdkAddonVersion = 0; - memset(mRightsId.data(), 0, mRightsId.size()); - mPartitionEntryList.clear(); - memset(mKeyArea.data(), 0, mKeyArea.size()); -} - -byte_t nn::hac::ContentArchiveHeader::getFormatVersion() const -{ - return mFormatVersion; -} - -void nn::hac::ContentArchiveHeader::setFormatVersion(byte_t version) -{ - mFormatVersion = version; -} - -nn::hac::nca::DistributionType nn::hac::ContentArchiveHeader::getDistributionType() const -{ - return mDistributionType; -} - -void nn::hac::ContentArchiveHeader::setDistributionType(nca::DistributionType type) -{ - mDistributionType = type; -} - -nn::hac::nca::ContentType nn::hac::ContentArchiveHeader::getContentType() const -{ - return mContentType; -} - -void nn::hac::ContentArchiveHeader::setContentType(nca::ContentType type) -{ - mContentType = type; -} - -byte_t nn::hac::ContentArchiveHeader::getKeyGeneration() const -{ - return mKeyGeneration; -} - -void nn::hac::ContentArchiveHeader::setKeyGeneration(byte_t gen) -{ - mKeyGeneration = gen; -} - -byte_t nn::hac::ContentArchiveHeader::getKeyAreaEncryptionKeyIndex() const -{ - return mKaekIndex; -} - -void nn::hac::ContentArchiveHeader::setKeyAreaEncryptionKeyIndex(byte_t index) -{ - mKaekIndex = index; -} - -uint64_t nn::hac::ContentArchiveHeader::getContentSize() const -{ - return mContentSize; -} - -void nn::hac::ContentArchiveHeader::setContentSize(uint64_t size) -{ - mContentSize = size; -} - -uint64_t nn::hac::ContentArchiveHeader::getProgramId() const -{ - return mProgramId; -} - -void nn::hac::ContentArchiveHeader::setProgramId(uint64_t program_id) -{ - mProgramId = program_id; -} - -uint32_t nn::hac::ContentArchiveHeader::getContentIndex() const -{ - return mContentIndex; -} - -void nn::hac::ContentArchiveHeader::setContentIndex(uint32_t index) -{ - mContentIndex = index; -} - -uint32_t nn::hac::ContentArchiveHeader::getSdkAddonVersion() const -{ - return mSdkAddonVersion; -} - -void nn::hac::ContentArchiveHeader::setSdkAddonVersion(uint32_t version) -{ - mSdkAddonVersion = version; -} - -bool nn::hac::ContentArchiveHeader::hasRightsId() const -{ - bool rightsIdIsSet = false; - - for (size_t i = 0; i < nca::kRightsIdLen; i++) - { - if (mRightsId[i] != 0) - rightsIdIsSet = true; - } - - return rightsIdIsSet; -} - -const byte_t* nn::hac::ContentArchiveHeader::getRightsId() const -{ - return mRightsId.data(); -} - -void nn::hac::ContentArchiveHeader::setRightsId(const byte_t* rights_id) -{ - memcpy(mRightsId.data(), rights_id, nca::kRightsIdLen); -} - -const fnd::List& nn::hac::ContentArchiveHeader::getPartitionEntryList() const -{ - return mPartitionEntryList; -} - -void nn::hac::ContentArchiveHeader::setPartitionEntryList(const fnd::List& partition_entry_list) -{ - mPartitionEntryList = partition_entry_list; - - // sanity check the list - if (mPartitionEntryList.size() >= nca::kPartitionNum) - { - throw fnd::Exception(kModuleName, "Too many partitions"); - } - for (size_t i = 0; i < mPartitionEntryList.size(); i++) - { - if (mPartitionEntryList[i].header_index >= nca::kPartitionNum) - { - throw fnd::Exception(kModuleName, "Illegal partition index"); - } - for (size_t j = i+1; j < mPartitionEntryList.size(); j++) - { - if (mPartitionEntryList[i].header_index == mPartitionEntryList[j].header_index) - { - throw fnd::Exception(kModuleName, "Duplicated partition index"); - } - } - } -} - -const byte_t* nn::hac::ContentArchiveHeader::getKeyArea() const -{ - return mKeyArea.data(); -} - -void nn::hac::ContentArchiveHeader::setKeyArea(const byte_t* key_area) -{ - memcpy(mKeyArea.data(), key_area, nca::kKeyAreaSize); -} - -uint64_t nn::hac::ContentArchiveHeader::blockNumToSize(uint32_t block_num) const -{ - return block_num * nca::kSectorSize; -} - -uint32_t nn::hac::ContentArchiveHeader::sizeToBlockNum(uint64_t real_size) const -{ - return (uint32_t)(align(real_size, nca::kSectorSize) / nca::kSectorSize); -} \ No newline at end of file diff --git a/lib/libhac/source/ContentArchiveUtils.cpp b/lib/libhac/source/ContentArchiveUtils.cpp deleted file mode 100644 index 284bca6..0000000 --- a/lib/libhac/source/ContentArchiveUtils.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include - -void nn::hac::ContentArchiveUtils::decryptContentArchiveHeader(const byte_t* src, byte_t* dst, const fnd::aes::sAesXts128Key& key) -{ - byte_t tweak[fnd::aes::kAesBlockSize]; - - // decrypt main header - byte_t raw_hdr[nn::hac::nca::kSectorSize]; - fnd::aes::AesXtsMakeTweak(tweak, 1); - fnd::aes::AesXtsDecryptSector(src + sectorToOffset(1), nn::hac::nca::kSectorSize, key.key[0], key.key[1], tweak, raw_hdr); - - bool useNca2SectorIndex = ((nn::hac::sContentArchiveHeader*)(raw_hdr))->st_magic.get() == nn::hac::nca::kNca2StructMagic; - - // decrypt whole header - for (size_t i = 0; i < nn::hac::nca::kHeaderSectorNum; i++) - { - fnd::aes::AesXtsMakeTweak(tweak, (i > 1 && useNca2SectorIndex)? 0 : i); - fnd::aes::AesXtsDecryptSector(src + sectorToOffset(i), nn::hac::nca::kSectorSize, key.key[0], key.key[1], tweak, dst + sectorToOffset(i)); - } -} - -byte_t nn::hac::ContentArchiveUtils::getMasterKeyRevisionFromKeyGeneration(byte_t key_generation) -{ - byte_t masterkey_rev; - - switch (key_generation) - { - case(0): - case(1): - masterkey_rev = 0; - break; - case(2): - masterkey_rev = 1; - break; - case(3): - masterkey_rev = 2; - break; - case(4): - masterkey_rev = 3; - break; - case(5): - masterkey_rev = 4; - break; - default: - masterkey_rev = key_generation - 1; - } - - return masterkey_rev; -} - -void nn::hac::ContentArchiveUtils::getNcaPartitionAesCtr(const nn::hac::sNcaFsHeader* hdr, byte_t* ctr) -{ - for (size_t i = 0; i < 8; i++) - { - ctr[7-i] = hdr->aes_ctr_upper[i]; - ctr[15-i] = 0; - } -} \ No newline at end of file diff --git a/lib/libhac/source/ContentInfo.cpp b/lib/libhac/source/ContentInfo.cpp deleted file mode 100644 index 43902ea..0000000 --- a/lib/libhac/source/ContentInfo.cpp +++ /dev/null @@ -1,123 +0,0 @@ -#include - -nn::hac::ContentInfo::ContentInfo() -{ - clear(); -} - -nn::hac::ContentInfo::ContentInfo(const ContentInfo& other) -{ - *this = other; -} - -void nn::hac::ContentInfo::operator=(const ContentInfo& other) -{ - clear(); - mRawBinary = other.mRawBinary; - mHash = other.mHash; - mContentId = other.mContentId; - mSize = other.mSize; - mType = other.mType; -} - -bool nn::hac::ContentInfo::operator==(const ContentInfo& other) const -{ - return (mHash == other.mHash) \ - && (mContentId == other.mContentId) \ - && (mSize == other.mSize) \ - && (mType == other.mType); -} - -bool nn::hac::ContentInfo::operator!=(const ContentInfo& other) const -{ - return !(*this == other); -} - -void nn::hac::ContentInfo::toBytes() -{ - mRawBinary.alloc(sizeof(sContentInfo)); - sContentInfo* info = (sContentInfo*)mRawBinary.data(); - - info->content_hash = mHash; - info->content_id = mContentId; - info->size_lower = mSize & (uint32_t)(-1); - info->size_higher = (mSize >> 32) & (uint16_t)(-1); - info->content_type = mType; - info->id_offset = mIdOffset; -} - -void nn::hac::ContentInfo::fromBytes(const byte_t* bytes, size_t len) -{ - if (len < sizeof(sContentInfo)) - { - throw fnd::Exception(kModuleName, "ContentInfo too small"); - } - - const sContentInfo* info = (const sContentInfo*)bytes; - - mHash = info->content_hash; - mContentId = info->content_id; - mSize = (uint64_t)(info->size_lower.get()) | (uint64_t)(info->size_higher.get()) << 32; - mType = (cnmt::ContentType)info->content_type; - mIdOffset = info->id_offset; -} - -const fnd::Vec& nn::hac::ContentInfo::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::ContentInfo::clear() -{ - mRawBinary.clear(); -} - -const fnd::sha::sSha256Hash& nn::hac::ContentInfo::getContentHash() const -{ - return mHash; -} - -void nn::hac::ContentInfo::setContentHash(const fnd::sha::sSha256Hash& hash) -{ - mHash = hash; -} - -const nn::hac::cnmt::sContentId& nn::hac::ContentInfo::getContentId() const -{ - return mContentId; -} - -void nn::hac::ContentInfo::setContentId(const cnmt::sContentId& content_id) -{ - mContentId = content_id; -} - -size_t nn::hac::ContentInfo::getContentSize() const -{ - return mSize; -} - -void nn::hac::ContentInfo::setContentSize(size_t size) -{ - mSize = size; -} - -nn::hac::cnmt::ContentType nn::hac::ContentInfo::getContentType() const -{ - return mType; -} - -void nn::hac::ContentInfo::setContentType(cnmt::ContentType type) -{ - mType = type; -} - -byte_t nn::hac::ContentInfo::getIdOffset() const -{ - return mIdOffset; -} - -void nn::hac::ContentInfo::setIdOffset(byte_t id_offset) -{ - mIdOffset = id_offset; -} \ No newline at end of file diff --git a/lib/libhac/source/ContentMeta.cpp b/lib/libhac/source/ContentMeta.cpp deleted file mode 100644 index 3c181de..0000000 --- a/lib/libhac/source/ContentMeta.cpp +++ /dev/null @@ -1,368 +0,0 @@ -#include - -nn::hac::ContentMeta::ContentMeta() -{ - clear(); -} - -nn::hac::ContentMeta::ContentMeta(const ContentMeta & other) -{ - *this = other; -} - -void nn::hac::ContentMeta::operator=(const ContentMeta& other) -{ - if (other.getBytes().size() > 0) - { - fromBytes(other.getBytes().data(), other.getBytes().size()); - } - else - { - clear(); - mTitleId = other.mTitleId; - mTitleVersion = other.mTitleVersion; - mType = other.mType; - mAttributes = other.mAttributes; - mRequiredDownloadSystemVersion = other.mRequiredDownloadSystemVersion; - mApplicationMetaExtendedHeader = other.mApplicationMetaExtendedHeader; - mPatchMetaExtendedHeader = other.mPatchMetaExtendedHeader; - mAddOnContentMetaExtendedHeader = other.mAddOnContentMetaExtendedHeader; - mDeltaMetaExtendedHeader = other.mDeltaMetaExtendedHeader; - mContentInfo = other.mContentInfo; - mContentMetaInfo = other.mContentMetaInfo; - mExtendedData = other.mExtendedData; - memcpy(mDigest.data, other.mDigest.data, cnmt::kDigestLen); - } -} - -bool nn::hac::ContentMeta::operator==(const ContentMeta& other) const -{ - return (mTitleId == other.mTitleId) \ - && (mTitleVersion == other.mTitleVersion) \ - && (mType == other.mType) \ - && (mAttributes == other.mAttributes) \ - && (mRequiredDownloadSystemVersion == other.mRequiredDownloadSystemVersion) \ - && (mApplicationMetaExtendedHeader == other.mApplicationMetaExtendedHeader) \ - && (mPatchMetaExtendedHeader == other.mPatchMetaExtendedHeader) \ - && (mAddOnContentMetaExtendedHeader == other.mAddOnContentMetaExtendedHeader) \ - && (mDeltaMetaExtendedHeader == other.mDeltaMetaExtendedHeader) \ - && (mContentInfo == other.mContentInfo) \ - && (mContentMetaInfo == other.mContentMetaInfo) \ - && (mExtendedData == other.mExtendedData) \ - && (memcmp(mDigest.data, other.mDigest.data, cnmt::kDigestLen) == 0); -} - -bool nn::hac::ContentMeta::operator!=(const ContentMeta& other) const -{ - return !(*this == other); -} - -void nn::hac::ContentMeta::toBytes() -{ - throw fnd::Exception(kModuleName, "toBytes() not implemented"); -} - -void nn::hac::ContentMeta::fromBytes(const byte_t* data, size_t len) -{ - // clear member variables - clear(); - - // validate layout - validateBinary(data, len); - - // get pointer to header structure - const sContentMetaHeader* hdr = (const sContentMetaHeader*)data; - - mTitleId = hdr->id.get(); - mTitleVersion = hdr->version.get(); - mType = (cnmt::ContentMetaType)hdr->type; - mAttributes = hdr->attributes; - mRequiredDownloadSystemVersion = hdr->required_download_system_version.get(); - size_t exdata_size = 0; - - // save exheader - if (hdr->exhdr_size.get() > 0) - { - switch (mType) - { - case (cnmt::METATYPE_APPLICATION): - mApplicationMetaExtendedHeader.fromBytes(data + getExtendedHeaderOffset(), hdr->exhdr_size.get()); - exdata_size = 0; - break; - case (cnmt::METATYPE_PATCH): - mPatchMetaExtendedHeader.fromBytes(data + getExtendedHeaderOffset(), hdr->exhdr_size.get()); - exdata_size = mPatchMetaExtendedHeader.getExtendedDataSize(); - break; - case (cnmt::METATYPE_ADD_ON_CONTENT): - mAddOnContentMetaExtendedHeader.fromBytes(data + getExtendedHeaderOffset(), hdr->exhdr_size.get()); - exdata_size = 0; - break; - case (cnmt::METATYPE_DELTA): - mDeltaMetaExtendedHeader.fromBytes(data + getExtendedHeaderOffset(), hdr->exhdr_size.get()); - exdata_size = mDeltaMetaExtendedHeader.getExtendedDataSize(); - break; - default: - throw fnd::Exception(kModuleName, "Unhandled extended header for ContentMeta"); - //exdata_size = 0; - //break; - } - } - - // save content info - if (hdr->content_count.get() > 0) - { - const sContentInfo* info = (const sContentInfo*)(data + getContentInfoOffset(hdr->exhdr_size.get())); - ContentInfo cinfo; - for (size_t i = 0; i < hdr->content_count.get(); i++) - { - cinfo.fromBytes((const byte_t*)&info[i], sizeof(sContentInfo)); - mContentInfo.addElement(cinfo); - } - } - - // save content meta info - if (hdr->content_meta_count.get() > 0) - { - const sContentMetaInfo* info = (const sContentMetaInfo*)(data + getContentMetaInfoOffset(hdr->exhdr_size.get(), hdr->content_count.get())); - ContentMetaInfo cmeta; - for (size_t i = 0; i < hdr->content_meta_count.get(); i++) - { - cmeta.fromBytes((const byte_t*)&info[i], sizeof(sContentMetaInfo)); - mContentMetaInfo.addElement(cmeta); - } - } - - // save exdata - if (exdata_size > 0) - { - mExtendedData.alloc(exdata_size); - memcpy(mExtendedData.data(), data + getExtendedDataOffset(hdr->exhdr_size.get(), hdr->content_count.get(), hdr->content_meta_count.get()), exdata_size); - } - - // save digest - memcpy(mDigest.data, data + getDigestOffset(hdr->exhdr_size.get(), hdr->content_count.get(), hdr->content_meta_count.get(), exdata_size), cnmt::kDigestLen); -} - -const fnd::Vec& nn::hac::ContentMeta::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::ContentMeta::clear() -{ - mRawBinary.clear(); - mTitleId = 0; - mTitleVersion = 0; - mType = cnmt::METATYPE_SYSTEM_PROGRAM; - mAttributes = 0; - mRequiredDownloadSystemVersion = 0; - mApplicationMetaExtendedHeader.clear(); - mPatchMetaExtendedHeader.clear(); - mAddOnContentMetaExtendedHeader.clear(); - mDeltaMetaExtendedHeader.clear(); - mContentInfo.clear(); - mContentMetaInfo.clear(); - mExtendedData.clear(); - memset(mDigest.data, 0, cnmt::kDigestLen); -} - -uint64_t nn::hac::ContentMeta::getTitleId() const -{ - return mTitleId; -} - -void nn::hac::ContentMeta::setTitleId(uint64_t title_id) -{ - mTitleId = title_id; -} - -uint32_t nn::hac::ContentMeta::getTitleVersion() const -{ - return mTitleVersion; -} - -void nn::hac::ContentMeta::setTitleVersion(uint32_t version) -{ - mTitleVersion = version; -} - -nn::hac::cnmt::ContentMetaType nn::hac::ContentMeta::getContentMetaType() const -{ - return mType; -} - -void nn::hac::ContentMeta::setContentMetaType(cnmt::ContentMetaType type) -{ - mType = type; -} - -byte_t nn::hac::ContentMeta::getAttributes() const -{ - return mAttributes; -} - -void nn::hac::ContentMeta::setAttributes(byte_t attributes) -{ - mAttributes = attributes; -} - -uint32_t nn::hac::ContentMeta::getRequiredDownloadSystemVersion() const -{ - return mRequiredDownloadSystemVersion; -} - -void nn::hac::ContentMeta::setRequiredDownloadSystemVersion(uint32_t version) -{ - mRequiredDownloadSystemVersion = version; -} - -const nn::hac::ApplicationMetaExtendedHeader& nn::hac::ContentMeta::getApplicationMetaExtendedHeader() const -{ - return mApplicationMetaExtendedHeader; -} - -void nn::hac::ContentMeta::setApplicationMetaExtendedHeader(const ApplicationMetaExtendedHeader& exhdr) -{ - mApplicationMetaExtendedHeader = exhdr; -} - -const nn::hac::PatchMetaExtendedHeader& nn::hac::ContentMeta::getPatchMetaExtendedHeader() const -{ - return mPatchMetaExtendedHeader; -} - -void nn::hac::ContentMeta::setPatchMetaExtendedHeader(const PatchMetaExtendedHeader& exhdr) -{ - mPatchMetaExtendedHeader = exhdr; -} - -const nn::hac::AddOnContentMetaExtendedHeader& nn::hac::ContentMeta::getAddOnContentMetaExtendedHeader() const -{ - return mAddOnContentMetaExtendedHeader; -} - -void nn::hac::ContentMeta::setAddOnContentMetaExtendedHeader(const AddOnContentMetaExtendedHeader& exhdr) -{ - mAddOnContentMetaExtendedHeader = exhdr; -} - -const nn::hac::DeltaMetaExtendedHeader& nn::hac::ContentMeta::getDeltaMetaExtendedHeader() const -{ - return mDeltaMetaExtendedHeader; -} - -void nn::hac::ContentMeta::setDeltaMetaExtendedHeader(const DeltaMetaExtendedHeader& exhdr) -{ - mDeltaMetaExtendedHeader = exhdr; -} - -const fnd::List& nn::hac::ContentMeta::getContentInfo() const -{ - return mContentInfo; -} - -void nn::hac::ContentMeta::setContentInfo(const fnd::List& info) -{ - mContentInfo = info; -} - -const fnd::List& nn::hac::ContentMeta::getContentMetaInfo() const -{ - return mContentMetaInfo; -} - -void nn::hac::ContentMeta::setContentMetaInfo(const fnd::List& info) -{ - mContentMetaInfo = info; -} - -const fnd::Vec & nn::hac::ContentMeta::getExtendedData() const -{ - return mExtendedData; -} - -void nn::hac::ContentMeta::setExtendedData(const fnd::Vec& data) -{ - mExtendedData = data; -} - -const nn::hac::cnmt::sDigest & nn::hac::ContentMeta::getDigest() const -{ - return mDigest; -} - -void nn::hac::ContentMeta::setDigest(const nn::hac::cnmt::sDigest& digest) -{ - mDigest = digest; -} - -bool nn::hac::ContentMeta::validateExtendedHeaderSize(cnmt::ContentMetaType type, size_t exhdrSize) const -{ - bool validSize = false; - - switch (type) - { - case (cnmt::METATYPE_APPLICATION): - validSize = (exhdrSize == sizeof(sApplicationMetaExtendedHeader)); - break; - case (cnmt::METATYPE_PATCH): - validSize = (exhdrSize == sizeof(sPatchMetaExtendedHeader)); - break; - case (cnmt::METATYPE_ADD_ON_CONTENT): - validSize = (exhdrSize == sizeof(sAddOnContentMetaExtendedHeader)); - break; - case (cnmt::METATYPE_DELTA): - validSize = (exhdrSize == sizeof(sDeltaMetaExtendedHeader)); - break; - default: - validSize = (exhdrSize == 0); - } - - return validSize; -} - -size_t nn::hac::ContentMeta::getExtendedDataSize(cnmt::ContentMetaType type, const byte_t * data) const -{ - size_t exdata_len = 0; - if (type == cnmt::METATYPE_PATCH) - { - const sPatchMetaExtendedHeader* exhdr = (const sPatchMetaExtendedHeader*)(data); - exdata_len = exhdr->extended_data_size.get(); - } - else if (type == cnmt::METATYPE_DELTA) - { - const sDeltaMetaExtendedHeader* exhdr = (const sDeltaMetaExtendedHeader*)(data); - exdata_len = exhdr->extended_data_size.get(); - } - return exdata_len; -} - -void nn::hac::ContentMeta::validateBinary(const byte_t * data, size_t len) const -{ - // check if it is large enough to read the header - if (len < sizeof(sContentMetaHeader)) - { - throw fnd::Exception(kModuleName, "Binary too small"); - } - - // get pointer to header structure - const sContentMetaHeader* hdr = (const sContentMetaHeader*)data; - - // validate extended header size - if (validateExtendedHeaderSize((cnmt::ContentMetaType)hdr->type, hdr->exhdr_size.get()) == false) - { - throw fnd::Exception(kModuleName, "Invalid extended header size"); - } - - // check binary size again for new minimum size - if (len < getTotalSize(hdr->exhdr_size.get(), hdr->content_count.get(), hdr->content_meta_count.get(), 0)) - { - throw fnd::Exception(kModuleName, "Binary too small"); - } - - // check binary size again with extended data size - if (len < getTotalSize(hdr->exhdr_size.get(), hdr->content_count.get(), hdr->content_meta_count.get(), getExtendedDataSize((cnmt::ContentMetaType)hdr->type, data + getExtendedHeaderOffset()))) - { - throw fnd::Exception(kModuleName, "Binary too small"); - } -} \ No newline at end of file diff --git a/lib/libhac/source/ContentMetaInfo.cpp b/lib/libhac/source/ContentMetaInfo.cpp deleted file mode 100644 index 3a1e4fe..0000000 --- a/lib/libhac/source/ContentMetaInfo.cpp +++ /dev/null @@ -1,114 +0,0 @@ -#include - -nn::hac::ContentMetaInfo::ContentMetaInfo() -{ - clear(); -} - -nn::hac::ContentMetaInfo::ContentMetaInfo(const ContentMetaInfo& other) -{ - *this = other; -} - -void nn::hac::ContentMetaInfo::operator=(const ContentMetaInfo& other) -{ - clear(); - mRawBinary = other.mRawBinary; - mTitleId = other.mTitleId; - mTitleVersion = other.mTitleVersion; - mType = other.mType; - mAttributes = other.mAttributes; -} - -bool nn::hac::ContentMetaInfo::operator==(const ContentMetaInfo& other) const -{ - return (mTitleId == other.mTitleId) \ - && (mTitleVersion == other.mTitleVersion) \ - && (mType == other.mType) \ - && (mAttributes == other.mAttributes); -} - -bool nn::hac::ContentMetaInfo::operator!=(const ContentMetaInfo& other) const -{ - return !(*this == other); -} - -void nn::hac::ContentMetaInfo::toBytes() -{ - mRawBinary.alloc(sizeof(sContentMetaInfo)); - sContentMetaInfo* info = (sContentMetaInfo*)mRawBinary.data(); - - info->id = mTitleId; - info->version = mTitleVersion; - info->type = mType; - info->attributes = mAttributes; -} - -void nn::hac::ContentMetaInfo::fromBytes(const byte_t* bytes, size_t len) -{ - if (len < sizeof(sContentMetaInfo)) - { - throw fnd::Exception(kModuleName, "ContentMetaInfo too small"); - } - - const sContentMetaInfo* info = (const sContentMetaInfo*)bytes; - - mTitleId = info->id.get(); - mTitleVersion = info->version.get(); - mType = (cnmt::ContentMetaType)info->type; - mAttributes = info->attributes; -} - -const fnd::Vec& nn::hac::ContentMetaInfo::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::ContentMetaInfo::clear() -{ - mRawBinary.clear(); - mTitleId = 0; - mTitleVersion = 0; - mType = cnmt::ContentMetaType::METATYPE_APPLICATION; - mAttributes = 0; -} - -uint64_t nn::hac::ContentMetaInfo::getTitleId() const -{ - return mTitleId; -} - -void nn::hac::ContentMetaInfo::setTitleId(uint64_t title_id) -{ - mTitleId = title_id; -} - -uint32_t nn::hac::ContentMetaInfo::getTitleVersion() const -{ - return mTitleVersion; -} - -void nn::hac::ContentMetaInfo::setTitleVersion(uint32_t ver) -{ - mTitleVersion = ver; -} - -nn::hac::cnmt::ContentMetaType nn::hac::ContentMetaInfo::getContentMetaType() const -{ - return mType; -} - -void nn::hac::ContentMetaInfo::setContentMetaType(cnmt::ContentMetaType type) -{ - mType = type; -} - -byte_t nn::hac::ContentMetaInfo::getAttributes() const -{ - return mAttributes; -} - -void nn::hac::ContentMetaInfo::setAttributes(byte_t attr) -{ - mAttributes = attr; -} diff --git a/lib/libhac/source/DeltaMetaExtendedHeader.cpp b/lib/libhac/source/DeltaMetaExtendedHeader.cpp deleted file mode 100644 index b69afa7..0000000 --- a/lib/libhac/source/DeltaMetaExtendedHeader.cpp +++ /dev/null @@ -1,84 +0,0 @@ -#include - -nn::hac::DeltaMetaExtendedHeader::DeltaMetaExtendedHeader() -{ - clear(); -} - -nn::hac::DeltaMetaExtendedHeader::DeltaMetaExtendedHeader(const DeltaMetaExtendedHeader& other) -{ - *this = other; -} - -void nn::hac::DeltaMetaExtendedHeader::operator=(const DeltaMetaExtendedHeader& other) -{ - clear(); - mRawBinary = other.mRawBinary; - mApplicationId = other.mApplicationId; - mExtendedDataSize = other.mExtendedDataSize; -} - -bool nn::hac::DeltaMetaExtendedHeader::operator==(const DeltaMetaExtendedHeader& other) const -{ - return (mApplicationId == other.mApplicationId) \ - && (mExtendedDataSize == other.mExtendedDataSize); -} - -bool nn::hac::DeltaMetaExtendedHeader::operator!=(const DeltaMetaExtendedHeader& other) const -{ - return !(*this == other); -} - -void nn::hac::DeltaMetaExtendedHeader::toBytes() -{ - mRawBinary.alloc(sizeof(sDeltaMetaExtendedHeader)); - sDeltaMetaExtendedHeader* info = (sDeltaMetaExtendedHeader*)mRawBinary.data(); - - info->application_id = mApplicationId; - info->extended_data_size = mExtendedDataSize; -} - -void nn::hac::DeltaMetaExtendedHeader::fromBytes(const byte_t* bytes, size_t len) -{ - if (len < sizeof(sDeltaMetaExtendedHeader)) - { - throw fnd::Exception(kModuleName, "DeltaMetaExtendedHeader too small"); - } - - const sDeltaMetaExtendedHeader* info = (const sDeltaMetaExtendedHeader*)bytes; - - mApplicationId = info->application_id.get(); - mExtendedDataSize = info->extended_data_size.get(); -} - -const fnd::Vec& nn::hac::DeltaMetaExtendedHeader::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::DeltaMetaExtendedHeader::clear() -{ - mRawBinary.clear(); - mApplicationId = 0; - mExtendedDataSize = 0; -} - -uint64_t nn::hac::DeltaMetaExtendedHeader::getApplicationId() const -{ - return mApplicationId; -} - -void nn::hac::DeltaMetaExtendedHeader::setApplicationId(uint64_t application_id) -{ - mApplicationId = application_id; -} - -uint32_t nn::hac::DeltaMetaExtendedHeader::getExtendedDataSize() const -{ - return mExtendedDataSize; -} - -void nn::hac::DeltaMetaExtendedHeader::setExtendedDataSize(uint32_t size) -{ - mExtendedDataSize = size; -} \ No newline at end of file diff --git a/lib/libhac/source/FileSystemAccessControl.cpp b/lib/libhac/source/FileSystemAccessControl.cpp deleted file mode 100644 index ce0e3d9..0000000 --- a/lib/libhac/source/FileSystemAccessControl.cpp +++ /dev/null @@ -1,219 +0,0 @@ -#include -#include - -nn::hac::FileSystemAccessControl::FileSystemAccessControl() -{ - clear(); -} - -nn::hac::FileSystemAccessControl::FileSystemAccessControl(const FileSystemAccessControl & other) -{ - *this = other; -} - -void nn::hac::FileSystemAccessControl::operator=(const FileSystemAccessControl & other) -{ - mRawBinary = other.mRawBinary; - mVersion = other.mVersion; - mFsaRights = other.mFsaRights; - mContentOwnerIdList = other.mContentOwnerIdList; - mSaveDataOwnerIdList = other.mSaveDataOwnerIdList; -} - -bool nn::hac::FileSystemAccessControl::operator==(const FileSystemAccessControl & other) const -{ - return (mVersion == other.mVersion) \ - && (mFsaRights == other.mFsaRights) \ - && (mContentOwnerIdList == other.mContentOwnerIdList) \ - && (mSaveDataOwnerIdList == other.mSaveDataOwnerIdList); -} - -bool nn::hac::FileSystemAccessControl::operator!=(const FileSystemAccessControl & other) const -{ - return !(*this == other); -} - -void nn::hac::FileSystemAccessControl::toBytes() -{ - // determine section layout - struct sLayout { - uint32_t offset, size; - } content, savedata; - - content.offset = (uint32_t)align(sizeof(sFacHeader), fac::kSectionAlignSize); - if (mContentOwnerIdList.size() > 0) - content.size = (uint32_t)(sizeof(uint32_t) + mContentOwnerIdList.size() * sizeof(uint64_t)); - else - content.size = 0; - - savedata.offset = (uint32_t)(content.offset + (content.size > 0 ? align(content.size, fac::kSectionAlignSize) : 0)); - if (mSaveDataOwnerIdList.size() > 0) - savedata.size = (uint32_t)(sizeof(uint32_t) + align(mSaveDataOwnerIdList.size(), fac::kSectionAlignSize) + mSaveDataOwnerIdList.size() * sizeof(uint64_t)); - else - savedata.size = 0; - - - // get total size - size_t total_size = _MAX(_MAX(content.offset + content.size, savedata.offset + savedata.size), align(sizeof(sFacHeader), fac::kSectionAlignSize)); - - mRawBinary.alloc(total_size); - sFacHeader* hdr = (sFacHeader*)mRawBinary.data(); - - // set type - hdr->version = mVersion; - - // flags - uint64_t flag = 0; - for (size_t i = 0; i < mFsaRights.size(); i++) - { - flag |= _BIT((uint64_t)mFsaRights[i]); - } - hdr->fac_flags = flag; - - // set offset/size - hdr->content_owner_ids.offset = content.offset; - if (content.size > 0) - hdr->content_owner_ids.size = content.size; - hdr->save_data_owner_ids.offset = savedata.offset; - if (savedata.size > 0) - hdr->save_data_owner_ids.size = savedata.size; - - // set ids - le_uint32_t* content_owner_id_num = (le_uint32_t*)(mRawBinary.data() + content.offset); - le_uint64_t* content_owner_ids = (le_uint64_t*)(mRawBinary.data() + content.offset + sizeof(uint32_t)); - content_owner_id_num->set((uint32_t)mContentOwnerIdList.size()); - for (size_t i = 0; i < mContentOwnerIdList.size(); i++) - { - content_owner_ids[i] = mContentOwnerIdList[i]; - } - - le_uint32_t* save_data_owner_id_num = (le_uint32_t*)(mRawBinary.data() + savedata.offset); - byte_t* save_data_owner_id_accessibility_array = (mRawBinary.data() + savedata.offset + sizeof(uint32_t)); - le_uint64_t* save_data_owner_ids = (le_uint64_t*)(mRawBinary.data() + savedata.offset + sizeof(uint32_t) + align(mSaveDataOwnerIdList.size(), sizeof(uint32_t))); - save_data_owner_id_num->set((uint32_t)mSaveDataOwnerIdList.size()); - for (size_t i = 0; i < mSaveDataOwnerIdList.size(); i++) - { - save_data_owner_id_accessibility_array[i] = mSaveDataOwnerIdList[i].access_type; - save_data_owner_ids[i] = mSaveDataOwnerIdList[i].id; - } -} - -void nn::hac::FileSystemAccessControl::fromBytes(const byte_t* data, size_t len) -{ - // check size - if (len < sizeof(sFacHeader)) - { - throw fnd::Exception(kModuleName, "FileSystemAccessControlInfo binary is too small"); - } - - // clear variables - clear(); - - // save a copy of the header - sFacHeader hdr; - memcpy((void*)&hdr, data, sizeof(sFacHeader)); - - // check format version - if (hdr.version.get() != fac::kFacFormatVersion) - { - throw fnd::Exception(kModuleName, "FileSystemAccessControlInfo format version unsupported"); - } - - // get total size - size_t total_size = _MAX(_MAX(hdr.content_owner_ids.offset.get() + hdr.content_owner_ids.size.get(), hdr.save_data_owner_ids.offset.get() + hdr.save_data_owner_ids.size.get()), align(sizeof(sFacHeader), fac::kSectionAlignSize)); - - // validate binary size - if (len < total_size) - { - throw fnd::Exception(kModuleName, "FileSystemAccessControlInfo binary is too small"); - } - - // allocate memory - mRawBinary.alloc(total_size); - memcpy(mRawBinary.data(), data, mRawBinary.size()); - - // save variables - mVersion = hdr.version.get(); - for (size_t i = 0; i < 64; i++) - { - if (_HAS_BIT(hdr.fac_flags.get(), i)) - { - mFsaRights.addElement((fac::FsAccessFlag)i); - } - } - - // save ids - if (hdr.content_owner_ids.size.get() > 0) - { - size_t content_owner_id_num = ((le_uint32_t*)(mRawBinary.data() + hdr.content_owner_ids.offset.get()))->get(); - le_uint64_t* content_owner_ids = (le_uint64_t*)(mRawBinary.data() + hdr.content_owner_ids.offset.get() + sizeof(uint32_t)); - for (size_t i = 0; i < content_owner_id_num; i++) - { - mContentOwnerIdList.addElement(content_owner_ids[i].get()); - } - } - if (hdr.save_data_owner_ids.size.get() > 0) - { - size_t save_data_owner_id_num = ((le_uint32_t*)(mRawBinary.data() + hdr.save_data_owner_ids.offset.get()))->get(); - byte_t* save_data_owner_id_accessibility_array = (mRawBinary.data() + hdr.save_data_owner_ids.offset.get() + sizeof(uint32_t)); - le_uint64_t* save_data_owner_ids = (le_uint64_t*)(mRawBinary.data() + hdr.save_data_owner_ids.offset.get() + sizeof(uint32_t) + align(save_data_owner_id_num, fac::kSectionAlignSize)); - for (size_t i = 0; i < save_data_owner_id_num; i++) - { - mSaveDataOwnerIdList.addElement({ (fac::SaveDataOwnerIdAccessType)save_data_owner_id_accessibility_array[i], save_data_owner_ids[i].get() }); - } - } -} - -const fnd::Vec& nn::hac::FileSystemAccessControl::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::FileSystemAccessControl::clear() -{ - mRawBinary.clear(); - mVersion = 0; - mFsaRights.clear(); - mContentOwnerIdList.clear(); - mSaveDataOwnerIdList.clear(); -} - -uint32_t nn::hac::FileSystemAccessControl::getFormatVersion() const -{ - return mVersion; -} - -void nn::hac::FileSystemAccessControl::setFormatVersion(uint32_t format_version) -{ - mVersion = format_version; -} - -const fnd::List& nn::hac::FileSystemAccessControl::getFsaRightsList() const -{ - return mFsaRights; -} - -void nn::hac::FileSystemAccessControl::setFsaRightsList(const fnd::List& list) -{ - mFsaRights = list; -} - -const fnd::List& nn::hac::FileSystemAccessControl::getContentOwnerIdList() const -{ - return mContentOwnerIdList; -} - -void nn::hac::FileSystemAccessControl::setContentOwnerIdList(const fnd::List& list) -{ - mContentOwnerIdList = list; -} - -const fnd::List& nn::hac::FileSystemAccessControl::getSaveDataOwnerIdList() const -{ - return mSaveDataOwnerIdList; -} - -void nn::hac::FileSystemAccessControl::setSaveDataOwnerIdList(const fnd::List& list) -{ - mSaveDataOwnerIdList = list; -} \ No newline at end of file diff --git a/lib/libhac/source/GameCardHeader.cpp b/lib/libhac/source/GameCardHeader.cpp deleted file mode 100644 index dc6bb7d..0000000 --- a/lib/libhac/source/GameCardHeader.cpp +++ /dev/null @@ -1,480 +0,0 @@ -#include - -nn::hac::GameCardHeader::GameCardHeader() -{ - clear(); -} - -nn::hac::GameCardHeader::GameCardHeader(const GameCardHeader& other) -{ - *this = other; -} - -void nn::hac::GameCardHeader::operator=(const GameCardHeader& other) -{ - mRomAreaStartPage = other.mRomAreaStartPage; - mBackupAreaStartPage = other.mBackupAreaStartPage; - mKekIndex = other.mKekIndex; - mTitleKeyDecIndex = other.mTitleKeyDecIndex; - mRomSize = other.mRomSize; - mCardHeaderVersion = other.mCardHeaderVersion; - mFlags = other.mFlags; - mPackageId = other.mPackageId; - mValidDataEndPage = other.mValidDataEndPage; - mAesCbcIv = other.mAesCbcIv; - mPartitionFsHeaderAddress = other.mPartitionFsHeaderAddress; - mPartitionFsHeaderSize = other.mPartitionFsHeaderSize; - mPartitionFsHeaderHash = other.mPartitionFsHeaderHash; - mInitialDataHash = other.mInitialDataHash; - mSelSec = other.mSelSec; - mSelT1Key = other.mSelT1Key; - mSelKey = other.mSelKey; - mLimAreaPage = other.mLimAreaPage; - mFwVersion[0] = other.mFwVersion[0]; - mFwVersion[1] = other.mFwVersion[1]; - mAccCtrl1 = other.mAccCtrl1; - mWait1TimeRead = other.mWait1TimeRead; - mWait2TimeRead = other.mWait2TimeRead; - mWait1TimeWrite = other.mWait1TimeWrite; - mWait2TimeWrite = other.mWait2TimeWrite; - mFwMode = other.mFwMode; - mUppVersion = other.mUppVersion; - memcpy(mUppHash, other.mUppHash, gc::kUppHashLen); - mUppId = other.mUppId; -} - -bool nn::hac::GameCardHeader::operator==(const GameCardHeader& other) const -{ - return (mRomAreaStartPage == other.mRomAreaStartPage) - && (mBackupAreaStartPage == other.mBackupAreaStartPage) - && (mKekIndex == other.mKekIndex) - && (mTitleKeyDecIndex == other.mTitleKeyDecIndex) - && (mRomSize == other.mRomSize) - && (mCardHeaderVersion == other.mCardHeaderVersion) - && (mFlags == other.mFlags) - && (mPackageId == other.mPackageId) - && (mValidDataEndPage == other.mValidDataEndPage) - && (mAesCbcIv == other.mAesCbcIv) - && (mPartitionFsHeaderAddress == other.mPartitionFsHeaderAddress) - && (mPartitionFsHeaderSize == other.mPartitionFsHeaderSize) - && (mPartitionFsHeaderHash == other.mPartitionFsHeaderHash) - && (mInitialDataHash == other.mInitialDataHash) - && (mSelSec == other.mSelSec) - && (mSelT1Key == other.mSelT1Key) - && (mSelKey == other.mSelKey) - && (mLimAreaPage == other.mLimAreaPage) - && (mFwVersion[0] == other.mFwVersion[0]) - && (mFwVersion[1] == other.mFwVersion[1]) - && (mAccCtrl1 == other.mAccCtrl1) - && (mWait1TimeRead == other.mWait1TimeRead) - && (mWait2TimeRead == other.mWait2TimeRead) - && (mWait1TimeWrite == other.mWait1TimeWrite) - && (mWait2TimeWrite == other.mWait2TimeWrite) - && (mFwMode == other.mFwMode) - && (mUppVersion == other.mUppVersion) - && (memcmp(mUppHash, other.mUppHash, gc::kUppHashLen) == 0) - && (mUppId == other.mUppId); -} - -bool nn::hac::GameCardHeader::operator!=(const GameCardHeader& other) const -{ - return !(*this == other); -} - -void nn::hac::GameCardHeader::toBytes() -{ - fnd::Exception(kModuleName, "toBytes() not implemented"); -} - -void nn::hac::GameCardHeader::fromBytes(const byte_t* data, size_t len) -{ - // check input data size - if (len < sizeof(sGcHeader)) - { - throw fnd::Exception(kModuleName, "GameCardImage header size is too small"); - } - - // clear internal members - clear(); - - // allocate internal local binary copy - mRawBinary.alloc(sizeof(sGcHeader)); - memcpy(mRawBinary.data(), data, mRawBinary.size()); - - // get sGcHeader ptr - const nn::hac::sGcHeader* hdr = (const nn::hac::sGcHeader*)mRawBinary.data(); - - // check GameCardImage signature - if (hdr->st_magic.get() != gc::kGcHeaderStructMagic) - { - throw fnd::Exception(kModuleName, "GameCardImage header corrupt"); - } - - mRomAreaStartPage = hdr->rom_area_start_page.get(); - mBackupAreaStartPage = hdr->backup_area_start_page.get(); - mKekIndex = hdr->key_flag & 7; - mTitleKeyDecIndex = (hdr->key_flag >> 4) & 7; - mRomSize = hdr->rom_size; - mCardHeaderVersion = hdr->card_header_version; - mFlags = hdr->flags; - mPackageId = hdr->package_id.get(); - mValidDataEndPage = hdr->valid_data_end_page.get(); - for (size_t i = 0; i < fnd::aes::kAesBlockSize; i++) - mAesCbcIv.iv[i] = hdr->aescbc_iv.iv[15-i]; - mPartitionFsHeaderAddress = hdr->partition_fs_header_address.get(); - mPartitionFsHeaderSize = hdr->partition_fs_header_size.get(); - mPartitionFsHeaderHash = hdr->partition_fs_header_hash; - mInitialDataHash = hdr->initial_data_hash; - mSelSec = hdr->sel_sec.get(); - mSelT1Key = hdr->sel_t1_key.get(); - mSelKey = hdr->sel_key.get(); - mLimAreaPage = hdr->lim_area.get(); - - // if decrypted - if (hdr->reserved_02[sizeof(hdr->reserved_02)-1] == 0x00 && hdr->reserved_02[sizeof(hdr->reserved_02)-2] == 0x00) - { - mFwVersion[gc::FWVER_MAJOR] = hdr->fw_version[gc::FWVER_MAJOR].get(); - mFwVersion[gc::FWVER_MINOR] = hdr->fw_version[gc::FWVER_MINOR].get(); - mAccCtrl1 = hdr->acc_ctrl_1.get(); - mWait1TimeRead = hdr->wait_1_time_read.get(); - mWait2TimeRead = hdr->wait_2_time_read.get(); - mWait1TimeWrite = hdr->wait_1_time_write.get(); - mWait2TimeWrite = hdr->wait_2_time_write.get(); - mFwMode = hdr->fw_mode.get(); - mUppVersion = hdr->upp_version.get(); - memcpy(mUppHash, hdr->upp_hash, gc::kUppHashLen); - mUppId = hdr->upp_id.get(); - } - -} - -const fnd::Vec& nn::hac::GameCardHeader::getBytes() const -{ - return mRawBinary; -} - -// variables -void nn::hac::GameCardHeader::clear() -{ - mRomAreaStartPage = 0; - mBackupAreaStartPage = 0; - mKekIndex = 0; - mTitleKeyDecIndex = 0; - mRomSize = 0; - mCardHeaderVersion = 0; - mFlags = 0; - mPackageId = 0; - mValidDataEndPage = 0; - memset(mAesCbcIv.iv, 0, sizeof(mAesCbcIv)); - mPartitionFsHeaderAddress = 0; - mPartitionFsHeaderSize = 0; - memset(mPartitionFsHeaderHash.bytes, 0, sizeof(mPartitionFsHeaderHash)); - memset(mInitialDataHash.bytes, 0, sizeof(mInitialDataHash)); - mSelSec = 0; - mSelT1Key = 0; - mSelKey = 0; - mLimAreaPage = 0; - mFwVersion[0] = 0; - mFwVersion[1] = 0; - mAccCtrl1 = 0; - mWait1TimeRead = 0; - mWait2TimeRead = 0; - mWait1TimeWrite = 0; - mWait2TimeWrite = 0; - mFwMode = 0; - mUppVersion = 0; - memset(mUppHash, 0, gc::kUppHashLen); - mUppId = 0; -} - -uint32_t nn::hac::GameCardHeader::getRomAreaStartPage() const -{ - return mRomAreaStartPage; -} - -void nn::hac::GameCardHeader::setRomAreaStartPage(uint32_t startPage) -{ - mRomAreaStartPage = startPage; -} - -uint32_t nn::hac::GameCardHeader::getBackupAreaStartPage() const -{ - return mBackupAreaStartPage; -} - -void nn::hac::GameCardHeader::setBackupAreaStartPage(uint32_t startPage) -{ - mBackupAreaStartPage = startPage; -} - -byte_t nn::hac::GameCardHeader::getKekIndex() const -{ - return mKekIndex; -} - -void nn::hac::GameCardHeader::setKekIndex(byte_t kekIndex) -{ - mKekIndex = kekIndex; -} - -byte_t nn::hac::GameCardHeader::getTitleKeyDecIndex() const -{ - return mTitleKeyDecIndex; -} - -void nn::hac::GameCardHeader::setTitleKeyDecIndex(byte_t index) -{ - mTitleKeyDecIndex = index; -} - -byte_t nn::hac::GameCardHeader::getRomSizeType() const -{ - return mRomSize; -} - -void nn::hac::GameCardHeader::setRomSizeType(byte_t romSizeType) -{ - mRomSize = romSizeType; -} - -byte_t nn::hac::GameCardHeader::getCardHeaderVersion() const -{ - return mCardHeaderVersion; -} - -void nn::hac::GameCardHeader::setCardHeaderVersion(byte_t version) -{ - mCardHeaderVersion = version; -} - -byte_t nn::hac::GameCardHeader::getFlags() const -{ - return mFlags; -} - -void nn::hac::GameCardHeader::setFlags(byte_t flags) -{ - mFlags = flags; -} - -uint64_t nn::hac::GameCardHeader::getPackageId() const -{ - return mPackageId; -} - -void nn::hac::GameCardHeader::setPackageId(uint64_t id) -{ - mPackageId = id; -} - -uint32_t nn::hac::GameCardHeader::getValidDataEndPage() const -{ - return mValidDataEndPage; -} - -void nn::hac::GameCardHeader::setValidDataEndPage(uint32_t page) -{ - mValidDataEndPage = page; -} - -const fnd::aes::sAesIvCtr& nn::hac::GameCardHeader::getAesCbcIv() const -{ - return mAesCbcIv; -} - -void nn::hac::GameCardHeader::setAesCbcIv(const fnd::aes::sAesIvCtr& iv) -{ - mAesCbcIv = iv; -} - -uint64_t nn::hac::GameCardHeader::getPartitionFsAddress() const -{ - return mPartitionFsHeaderAddress; -} - -void nn::hac::GameCardHeader::setPartitionFsAddress(uint64_t address) -{ - mPartitionFsHeaderAddress = address; -} - -uint64_t nn::hac::GameCardHeader::getPartitionFsSize() const -{ - return mPartitionFsHeaderSize; -} - -void nn::hac::GameCardHeader::setPartitionFsSize(uint64_t size) -{ - mPartitionFsHeaderSize = size; -} - -const fnd::sha::sSha256Hash& nn::hac::GameCardHeader::getPartitionFsHash() const -{ - return mPartitionFsHeaderHash; -} - -void nn::hac::GameCardHeader::setPartitionFsHash(const fnd::sha::sSha256Hash& hash) -{ - mPartitionFsHeaderHash = hash; -} - -const fnd::sha::sSha256Hash& nn::hac::GameCardHeader::getInitialDataHash() const -{ - return mInitialDataHash; -} - -void nn::hac::GameCardHeader::setInitialDataHash(const fnd::sha::sSha256Hash& hash) -{ - mInitialDataHash = hash; -} - -uint32_t nn::hac::GameCardHeader::getSelSec() const -{ - return mSelSec; -} - -void nn::hac::GameCardHeader::setSelSec(uint32_t sel_sec) -{ - mSelSec = sel_sec; -} - -uint32_t nn::hac::GameCardHeader::getSelT1Key() const -{ - return mSelT1Key; -} - -void nn::hac::GameCardHeader::setSelT1Key(uint32_t sel_t1_key) -{ - mSelT1Key = sel_t1_key; -} - -uint32_t nn::hac::GameCardHeader::getSelKey() const -{ - return mSelKey; -} - -void nn::hac::GameCardHeader::setSelKey(uint32_t sel_key) -{ - mSelKey = sel_key; -} - -uint32_t nn::hac::GameCardHeader::getLimAreaPage() const -{ - return mLimAreaPage; -} - -void nn::hac::GameCardHeader::setLimAreaPage(uint32_t page) -{ - mLimAreaPage = page; -} - - -uint32_t nn::hac::GameCardHeader::getFwVerMajor() const -{ - return mFwVersion[gc::FWVER_MAJOR]; -} - -void nn::hac::GameCardHeader::setFwVerMajor(uint32_t ver) -{ - mFwVersion[gc::FWVER_MAJOR] = ver; -} - -uint32_t nn::hac::GameCardHeader::getFwVerMinor() const -{ - return mFwVersion[gc::FWVER_MINOR]; -} - -void nn::hac::GameCardHeader::setFwVerMinor(uint32_t ver) -{ - mFwVersion[gc::FWVER_MINOR] = ver; -} - -uint32_t nn::hac::GameCardHeader::getAccCtrl1() const -{ - return mAccCtrl1; -} - -void nn::hac::GameCardHeader::setAccCtrl1(uint32_t acc_ctrl_1) -{ - mAccCtrl1 = acc_ctrl_1; -} - -uint32_t nn::hac::GameCardHeader::getWait1TimeRead() const -{ - return mWait1TimeRead; -} - -void nn::hac::GameCardHeader::setWait1TimeRead(uint32_t seconds) -{ - mWait1TimeRead = seconds; -} - -uint32_t nn::hac::GameCardHeader::getWait2TimeRead() const -{ - return mWait2TimeRead; -} - -void nn::hac::GameCardHeader::setWait2TimeRead(uint32_t seconds) -{ - mWait2TimeRead = seconds; -} - -uint32_t nn::hac::GameCardHeader::getWait1TimeWrite() const -{ - return mWait1TimeWrite; -} - -void nn::hac::GameCardHeader::setWait1TimeWrite(uint32_t seconds) -{ - mWait1TimeWrite = seconds; -} - -uint32_t nn::hac::GameCardHeader::getWait2TimeWrite() const -{ - return mWait2TimeWrite; -} - -void nn::hac::GameCardHeader::setWait2TimeWrite(uint32_t seconds) -{ - mWait2TimeWrite = seconds; -} - -uint32_t nn::hac::GameCardHeader::getFwMode() const -{ - return mFwMode; -} - -void nn::hac::GameCardHeader::setFwMode(uint32_t fw_mode) -{ - mFwMode = fw_mode; -} - -uint32_t nn::hac::GameCardHeader::getUppVersion() const -{ - return mUppVersion; -} - -void nn::hac::GameCardHeader::setUppVersion(uint32_t version) -{ - mUppVersion = version; -} - -const byte_t* nn::hac::GameCardHeader::getUppHash() const -{ - return mUppHash; -} - -void nn::hac::GameCardHeader::setUppHash(const byte_t* hash) -{ - memcpy(mUppHash, hash, gc::kUppHashLen); -} - -uint64_t nn::hac::GameCardHeader::getUppId() const -{ - return mUppId; -} - -void nn::hac::GameCardHeader::setUppId(uint64_t id) -{ - mUppId = id; -} - diff --git a/lib/libhac/source/GameCardUtils.cpp b/lib/libhac/source/GameCardUtils.cpp deleted file mode 100644 index 891736e..0000000 --- a/lib/libhac/source/GameCardUtils.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include - -void nn::hac::GameCardUtils::getXciHeaderAesIv(const nn::hac::sGcHeader* hdr, byte_t* iv) -{ - for (size_t i = 0; i < 16; i++) - { - iv[15-i] = hdr->aescbc_iv.iv[i]; - } -} - -void nn::hac::GameCardUtils::decryptXciHeader(const byte_t* src, byte_t* dst, const byte_t* key) -{ - byte_t iv[fnd::aes::kAesBlockSize]; - - getXciHeaderAesIv((const nn::hac::sGcHeader*)src, iv); - - // copy plain - memcpy(dst, src, nn::hac::gc::kHeaderEncOffset); - - // decrypt encrypted data - fnd::aes::AesCbcDecrypt(src + nn::hac::gc::kHeaderEncOffset, nn::hac::gc::kHeaderEncSize, key, iv, dst + nn::hac::gc::kHeaderEncOffset); -} \ No newline at end of file diff --git a/lib/libhac/source/HandleTableSizeEntry.cpp b/lib/libhac/source/HandleTableSizeEntry.cpp deleted file mode 100644 index 23c6257..0000000 --- a/lib/libhac/source/HandleTableSizeEntry.cpp +++ /dev/null @@ -1,69 +0,0 @@ -#include - -nn::hac::HandleTableSizeEntry::HandleTableSizeEntry() : - mCap(kCapId), - mHandleTableSize(0) -{} - -nn::hac::HandleTableSizeEntry::HandleTableSizeEntry(const KernelCapabilityEntry & kernel_cap) : - mCap(kCapId), - mHandleTableSize(0) -{ - setKernelCapability(kernel_cap); -} - -nn::hac::HandleTableSizeEntry::HandleTableSizeEntry(uint16_t size) : - mCap(kCapId), - mHandleTableSize(0) -{ - setHandleTableSize(size); -} - -void nn::hac::HandleTableSizeEntry::operator=(const HandleTableSizeEntry& other) -{ - mHandleTableSize = other.mHandleTableSize; - updateCapField(); -} - -bool nn::hac::HandleTableSizeEntry::operator==(const HandleTableSizeEntry& other) const -{ - return (mHandleTableSize == other.mHandleTableSize); -} - -bool nn::hac::HandleTableSizeEntry::operator!=(const HandleTableSizeEntry& other) const -{ - return !(*this == other); -} - - -const nn::hac::KernelCapabilityEntry & nn::hac::HandleTableSizeEntry::getKernelCapability() const -{ - return mCap; -} - -void nn::hac::HandleTableSizeEntry::setKernelCapability(const KernelCapabilityEntry & kernel_cap) -{ - if (kernel_cap.getType() != kCapId) - { - throw fnd::Exception(kModuleName, "KernelCapabilityEntry is not type 'HandleTableSize'"); - } - - mCap = kernel_cap; - processCapField(); -} - -uint16_t nn::hac::HandleTableSizeEntry::getHandleTableSize() const -{ - return mHandleTableSize; -} - -void nn::hac::HandleTableSizeEntry::setHandleTableSize(uint16_t size) -{ - if (size > kMaxHandleTableSize) - { - throw fnd::Exception(kModuleName, "Illegal HandleTableSize. (range: 0-1023 inclusive)"); - } - - mHandleTableSize = size; - updateCapField(); -} \ No newline at end of file diff --git a/lib/libhac/source/HandleTableSizeHandler.cpp b/lib/libhac/source/HandleTableSizeHandler.cpp deleted file mode 100644 index 3b429cf..0000000 --- a/lib/libhac/source/HandleTableSizeHandler.cpp +++ /dev/null @@ -1,67 +0,0 @@ -#include - -nn::hac::HandleTableSizeHandler::HandleTableSizeHandler() : - mIsSet(false), - mEntry(0) -{} - -void nn::hac::HandleTableSizeHandler::operator=(const HandleTableSizeHandler & other) -{ - mIsSet = other.mIsSet; - mEntry.setKernelCapability(other.mEntry.getKernelCapability()); -} - -bool nn::hac::HandleTableSizeHandler::operator==(const HandleTableSizeHandler & other) const -{ - return (mIsSet == other.mIsSet) \ - && (mEntry.getKernelCapability() == other.mEntry.getKernelCapability()); -} - -bool nn::hac::HandleTableSizeHandler::operator!=(const HandleTableSizeHandler & other) const -{ - return !(*this == other); -} - -void nn::hac::HandleTableSizeHandler::importKernelCapabilityList(const fnd::List& caps) -{ - if (caps.size() > kMaxKernelCapNum) - { - throw fnd::Exception(kModuleName, "Too many kernel capabilities"); - } - - if (caps.size() == 0) - return; - - mEntry.setKernelCapability(caps[0]); - mIsSet = true; -} - -void nn::hac::HandleTableSizeHandler::exportKernelCapabilityList(fnd::List& caps) const -{ - if (isSet() == false) - return; - - caps.addElement(mEntry.getKernelCapability()); -} - -void nn::hac::HandleTableSizeHandler::clear() -{ - mIsSet = false; - mEntry.setHandleTableSize(0); -} - -bool nn::hac::HandleTableSizeHandler::isSet() const -{ - return mIsSet; -} - -uint16_t nn::hac::HandleTableSizeHandler::getHandleTableSize() const -{ - return mEntry.getHandleTableSize(); -} - -void nn::hac::HandleTableSizeHandler::setHandleTableSize(uint16_t size) -{ - mEntry.setHandleTableSize(size); - mIsSet = true; -} \ No newline at end of file diff --git a/lib/libhac/source/HierarchicalIntegrityHeader.cpp b/lib/libhac/source/HierarchicalIntegrityHeader.cpp deleted file mode 100644 index c842a4e..0000000 --- a/lib/libhac/source/HierarchicalIntegrityHeader.cpp +++ /dev/null @@ -1,137 +0,0 @@ -#include -#include - -nn::hac::HierarchicalIntegrityHeader::HierarchicalIntegrityHeader() -{ - clear(); -} - -nn::hac::HierarchicalIntegrityHeader::HierarchicalIntegrityHeader(const HierarchicalIntegrityHeader & other) -{ - *this = other; -} - -void nn::hac::HierarchicalIntegrityHeader::operator=(const HierarchicalIntegrityHeader & other) -{ - if (other.getBytes().size() != 0) - { - fromBytes(other.getBytes().data(), other.getBytes().size()); - } - else - { - clear(); - mLayerInfo = other.mLayerInfo; - mMasterHashList = other.mMasterHashList; - } -} - -bool nn::hac::HierarchicalIntegrityHeader::operator==(const HierarchicalIntegrityHeader & other) const -{ - return (mLayerInfo == other.mLayerInfo) \ - && (mMasterHashList == other.mMasterHashList); -} - -bool nn::hac::HierarchicalIntegrityHeader::operator!=(const HierarchicalIntegrityHeader & other) const -{ - return !(*this == other); -} - -void nn::hac::HierarchicalIntegrityHeader::toBytes() -{ - throw fnd::Exception(kModuleName, "exportBinary() not implemented"); -} - -void nn::hac::HierarchicalIntegrityHeader::fromBytes(const byte_t* data, size_t len) -{ - std::stringstream error_str; - - // validate size for at least header - if (len < sizeof(nn::hac::sHierarchicalIntegrityHeader)) - { - throw fnd::Exception(kModuleName, "Header too small"); - } - - const nn::hac::sHierarchicalIntegrityHeader* hdr = (const nn::hac::sHierarchicalIntegrityHeader*)data; - - // Validate Header Sig "IVFC" - if (hdr->st_magic.get() != hierarchicalintegrity::kStructMagic) - { - throw fnd::Exception(kModuleName, "Invalid struct magic"); - } - - // Validate TypeId - if (hdr->type_id.get() != nn::hac::hierarchicalintegrity::kRomfsTypeId) - { - error_str.clear(); - error_str << "Unsupported type id (" << std::hex << hdr->type_id.get() << ")"; - throw fnd::Exception(kModuleName, error_str.str()); - } - - // Validate Layer Num - if (hdr->layer_num.get() != hierarchicalintegrity::kDefaultLayerNum+1) - { - error_str.clear(); - error_str << "Invalid layer count. "; - error_str << "(actual=" << std::dec << hdr->layer_num.get() << ", expected=" << nn::hac::hierarchicalintegrity::kDefaultLayerNum+1 << ")"; - throw fnd::Exception(kModuleName, error_str.str()); - } - - // Get Sizes/Offsets - size_t master_hash_offset = align((sizeof(nn::hac::sHierarchicalIntegrityHeader) + sizeof(nn::hac::sHierarchicalIntegrityLayerInfo) * hdr->layer_num.get()), nn::hac::hierarchicalintegrity::kHeaderAlignLen); - size_t total_size = master_hash_offset + hdr->master_hash_size.get(); - - // Validate total size - if (len < total_size) - { - throw fnd::Exception(kModuleName, "Header too small"); - } - - // copy to internal storage - mRawBinary.alloc(total_size); - memcpy(mRawBinary.data(), data, mRawBinary.size()); - - // save layer info - const nn::hac::sHierarchicalIntegrityLayerInfo* layer_info = (const nn::hac::sHierarchicalIntegrityLayerInfo*)(mRawBinary.data() + sizeof(nn::hac::sHierarchicalIntegrityHeader)); - for (size_t i = 0; i < hierarchicalintegrity::kDefaultLayerNum; i++) - { - mLayerInfo.addElement({layer_info[i].offset.get(), layer_info[i].size.get(), layer_info[i].block_size.get()}); - } - - // save hash list - const fnd::sha::sSha256Hash* hash_list = (const fnd::sha::sSha256Hash*)(mRawBinary.data() + master_hash_offset); - for (size_t i = 0; i < hdr->master_hash_size.get()/sizeof(fnd::sha::sSha256Hash); i++) - { - mMasterHashList.addElement(hash_list[i]); - } -} - -const fnd::Vec& nn::hac::HierarchicalIntegrityHeader::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::HierarchicalIntegrityHeader::clear() -{ - mLayerInfo.clear(); - mMasterHashList.clear(); -} - -const fnd::List& nn::hac::HierarchicalIntegrityHeader::getLayerInfo() const -{ - return mLayerInfo; -} - -void nn::hac::HierarchicalIntegrityHeader::setLayerInfo(const fnd::List& layer_info) -{ - mLayerInfo = layer_info; -} - -const fnd::List& nn::hac::HierarchicalIntegrityHeader::getMasterHashList() const -{ - return mMasterHashList; -} - -void nn::hac::HierarchicalIntegrityHeader::setMasterHashList(const fnd::List& master_hash_list) -{ - mMasterHashList = master_hash_list; -} \ No newline at end of file diff --git a/lib/libhac/source/HierarchicalSha256Header.cpp b/lib/libhac/source/HierarchicalSha256Header.cpp deleted file mode 100644 index e959f0b..0000000 --- a/lib/libhac/source/HierarchicalSha256Header.cpp +++ /dev/null @@ -1,112 +0,0 @@ -#include -#include - -nn::hac::HierarchicalSha256Header::HierarchicalSha256Header() -{ - clear(); -} - -nn::hac::HierarchicalSha256Header::HierarchicalSha256Header(const HierarchicalSha256Header & other) -{ - *this = other; -} - -void nn::hac::HierarchicalSha256Header::operator=(const HierarchicalSha256Header & other) -{ - if (other.getBytes().size() != 0) - { - fromBytes(other.getBytes().data(), other.getBytes().size()); - } - else - { - mMasterHash = other.mMasterHash; - mHashBlockSize = other.mHashBlockSize; - mLayerInfo = other.mLayerInfo; - } -} - -bool nn::hac::HierarchicalSha256Header::operator==(const HierarchicalSha256Header & other) const -{ - return (mMasterHash == other.mMasterHash) \ - && (mHashBlockSize == other.mHashBlockSize) \ - && (mLayerInfo == other.mLayerInfo); -} - -bool nn::hac::HierarchicalSha256Header::operator!=(const HierarchicalSha256Header & other) const -{ - return !(*this == other); -} - -void nn::hac::HierarchicalSha256Header::toBytes() -{ - throw fnd::Exception(kModuleName, "exportBinary() not implemented"); -} - -void nn::hac::HierarchicalSha256Header::fromBytes(const byte_t* data, size_t len) -{ - std::stringstream error_str; - - if (len < sizeof(nn::hac::sHierarchicalSha256Header)) - { - throw fnd::Exception(kModuleName, "Header too small"); - } - - const nn::hac::sHierarchicalSha256Header* hdr = (const nn::hac::sHierarchicalSha256Header*)data; - - if (hdr->layer_num.get() != nn::hac::hierarchicalsha256::kDefaultLayerNum) - { - error_str.clear(); - error_str << "Invalid layer count. "; - error_str << "(actual=" << std::dec << hdr->layer_num.get() << ", expected=" << nn::hac::hierarchicalsha256::kDefaultLayerNum << ")"; - throw fnd::Exception(kModuleName, error_str.str()); - } - - mMasterHash = hdr->master_hash; - mHashBlockSize = hdr->hash_block_size.get(); - for (size_t i = 0; i < hdr->layer_num.get(); i++) - { - mLayerInfo.addElement({hdr->layer[i].offset.get(), hdr->layer[i].size.get()}); - } -} - -const fnd::Vec& nn::hac::HierarchicalSha256Header::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::HierarchicalSha256Header::clear() -{ - memset(mMasterHash.bytes, 0, sizeof(fnd::sha::sSha256Hash)); - mHashBlockSize = 0; - mLayerInfo.clear(); -} - -const fnd::sha::sSha256Hash & nn::hac::HierarchicalSha256Header::getMasterHash() const -{ - return mMasterHash; -} - -void nn::hac::HierarchicalSha256Header::setMasterHash(const fnd::sha::sSha256Hash & master_hash) -{ - mMasterHash = master_hash; -} - -size_t nn::hac::HierarchicalSha256Header::getHashBlockSize() const -{ - return mHashBlockSize; -} - -void nn::hac::HierarchicalSha256Header::setHashBlockSize(size_t hash_block_size) -{ - mHashBlockSize = hash_block_size; -} - -const fnd::List& nn::hac::HierarchicalSha256Header::getLayerInfo() const -{ - return mLayerInfo; -} - -void nn::hac::HierarchicalSha256Header::setLayerInfo(const fnd::List& layer_info) -{ - mLayerInfo = layer_info; -} \ No newline at end of file diff --git a/lib/libhac/source/IdConverter.cpp b/lib/libhac/source/IdConverter.cpp deleted file mode 100644 index 5455263..0000000 --- a/lib/libhac/source/IdConverter.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include - -uint64_t nn::hac::IdConverter::convertToAocBaseId(uint64_t application_id) -{ - return application_id + kAocBaseId; -} - -uint64_t nn::hac::IdConverter::convertToDeltaId(uint64_t application_id) -{ - return application_id + kDeltaId; -} - -uint64_t nn::hac::IdConverter::convertToPatchId(uint64_t application_id) -{ - return application_id + kPatchId; -} \ No newline at end of file diff --git a/lib/libhac/source/IniHeader.cpp b/lib/libhac/source/IniHeader.cpp deleted file mode 100644 index 15c2689..0000000 --- a/lib/libhac/source/IniHeader.cpp +++ /dev/null @@ -1,114 +0,0 @@ -#include - -nn::hac::IniHeader::IniHeader() -{ - clear(); -} - -nn::hac::IniHeader::IniHeader(const IniHeader& other) -{ - *this = other; -} - -void nn::hac::IniHeader::operator=(const IniHeader& other) -{ - clear(); - this->mSize = other.mSize; - this->mKipNum = other.mKipNum; -} - -bool nn::hac::IniHeader::operator==(const IniHeader& other) const -{ - return (this->mSize == other.mSize) \ - && (this->mKipNum == other.mKipNum); -} - -bool nn::hac::IniHeader::operator!=(const IniHeader& other) const -{ - return !(*this == other); -} - -void nn::hac::IniHeader::toBytes() -{ - mRawBinary.alloc(sizeof(sIniHeader)); - nn::hac::sIniHeader* hdr = (nn::hac::sIniHeader*)mRawBinary.data(); - - // set header identifers - hdr->st_magic = ini::kIniStructMagic; - - if (mKipNum > ini::kMaxKipNum) - { - throw fnd::Exception(kModuleName, "Cannot generate INI Header (Too many KIPs)"); - } - - // write variables - hdr->size = mSize; - hdr->kip_num = mKipNum; -} - -void nn::hac::IniHeader::fromBytes(const byte_t* data, size_t len) -{ - // check input data size - if (len < sizeof(sIniHeader)) - { - throw fnd::Exception(kModuleName, "INI header corrupt (header size is too small)"); - } - - // clear internal members - clear(); - - // allocate internal local binary copy - mRawBinary.alloc(sizeof(sIniHeader)); - memcpy(mRawBinary.data(), data, mRawBinary.size()); - - // get sIniHeader ptr - const nn::hac::sIniHeader* hdr = (const nn::hac::sIniHeader*)mRawBinary.data(); - - // check INI signature - if (hdr->st_magic.get() != ini::kIniStructMagic) - { - throw fnd::Exception(kModuleName, "INI header corrupt (unrecognised header signature)"); - } - - // check KIP num - if (hdr->kip_num.get() > ini::kMaxKipNum) - { - throw fnd::Exception(kModuleName, "INI header corrupt (too many KIPs)"); - } - - // save variables - mSize = hdr->size.get(); - mKipNum = hdr->kip_num.get(); -} - -const fnd::Vec& nn::hac::IniHeader::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::IniHeader::clear() -{ - mRawBinary.clear(); - mSize = 0; - mKipNum = 0; -} - -uint32_t nn::hac::IniHeader::getSize() const -{ - return mSize; -} - -void nn::hac::IniHeader::setSize(uint32_t size) -{ - mSize = size; -} - -uint32_t nn::hac::IniHeader::getKipNum() const -{ - return mKipNum; -} - -void nn::hac::IniHeader::setKipNum(uint32_t num) -{ - mKipNum = num; -} \ No newline at end of file diff --git a/lib/libhac/source/InteruptEntry.cpp b/lib/libhac/source/InteruptEntry.cpp deleted file mode 100644 index 188de53..0000000 --- a/lib/libhac/source/InteruptEntry.cpp +++ /dev/null @@ -1,78 +0,0 @@ -#include - -nn::hac::InteruptEntry::InteruptEntry() : - mCap(kCapId), - mInterupt{0,0} -{ - -} - -nn::hac::InteruptEntry::InteruptEntry(const KernelCapabilityEntry & kernel_cap) : - mCap(kCapId), - mInterupt{ 0,0 } -{ - setKernelCapability(kernel_cap); -} - -nn::hac::InteruptEntry::InteruptEntry(uint32_t interupt0, uint32_t interupt1) : - mCap(kCapId), - mInterupt{ 0,0 } -{ - setInterupt(0, interupt0); - setInterupt(1, interupt1); -} - -void nn::hac::InteruptEntry::operator=(const InteruptEntry& other) -{ - mInterupt[0] = other.mInterupt[0]; - mInterupt[1] = other.mInterupt[1]; - updateCapField(); -} - -bool nn::hac::InteruptEntry::operator==(const InteruptEntry& other) const -{ - return (mInterupt[0] == other.mInterupt[0]) \ - && (mInterupt[1] == other.mInterupt[1]); -} - -bool nn::hac::InteruptEntry::operator!=(const InteruptEntry& other) const -{ - return !(*this == other); -} - -const nn::hac::KernelCapabilityEntry & nn::hac::InteruptEntry::getKernelCapability() const -{ - return mCap; -} - -void nn::hac::InteruptEntry::setKernelCapability(const KernelCapabilityEntry & kernel_cap) -{ - if (kernel_cap.getType() != kCapId) - { - throw fnd::Exception(kModuleName, "KernelCapabilityEntry is not type 'EnableInterupts'"); - } - - mCap = kernel_cap; - processCapField(); -} - -uint32_t nn::hac::InteruptEntry::operator[](size_t index) const -{ - return getInterupt(index); -} - -uint32_t nn::hac::InteruptEntry::getInterupt(size_t index) const -{ - return mInterupt[index % kInteruptNum]; -} - -void nn::hac::InteruptEntry::setInterupt(size_t index, uint32_t interupt) -{ - if (interupt > kInteruptMax) - { - throw fnd::Exception(kModuleName, "Illegal interupt value."); - } - - mInterupt[index % kInteruptNum] = interupt; - updateCapField(); -} \ No newline at end of file diff --git a/lib/libhac/source/InteruptHandler.cpp b/lib/libhac/source/InteruptHandler.cpp deleted file mode 100644 index ca74daf..0000000 --- a/lib/libhac/source/InteruptHandler.cpp +++ /dev/null @@ -1,111 +0,0 @@ -#include - -nn::hac::InteruptHandler::InteruptHandler() : - mIsSet(false), - mInterupts() -{} - -void nn::hac::InteruptHandler::operator=(const InteruptHandler & other) -{ - mIsSet = other.mIsSet; - mInterupts = other.mInterupts; -} - -bool nn::hac::InteruptHandler::operator==(const InteruptHandler & other) const -{ - return (mIsSet == other.mIsSet) \ - && (mInterupts == other.mInterupts); -} - -bool nn::hac::InteruptHandler::operator!=(const InteruptHandler & other) const -{ - return !(*this == other); -} - -void nn::hac::InteruptHandler::importKernelCapabilityList(const fnd::List& caps) -{ - if (caps.size() == 0) - return; - // convert to interupts - fnd::List interupts; - for (size_t i = 0; i < caps.size(); i++) - { - interupts.addElement(InteruptEntry(caps[i])); - } - - mInterupts.clear(); - for (size_t i = 0; i < interupts.size(); i++) - { - // weird condition for first interupt - if (interupts[i][1] == 0 && i == 0) - { - mInterupts.addElement(interupts[i][0]); - continue; - } - - // we found a stub - if (interupts[i][1] == InteruptEntry::kInteruptMax && interupts[i][1] == InteruptEntry::kInteruptMax) - { - continue; - } - - // add interupts - mInterupts.hasElement(interupts[i][0]) == false ? mInterupts.addElement(interupts[i][0]) : throw fnd::Exception(kModuleName, "Interupt already added"); - mInterupts.hasElement(interupts[i][1]) == false ? mInterupts.addElement(interupts[i][1]) : throw fnd::Exception(kModuleName, "Interupt already added"); - } - - mIsSet = true; -} - -void nn::hac::InteruptHandler::exportKernelCapabilityList(fnd::List& caps) const -{ - if (isSet() == false) - return; - - size_t i = 0; - if (mInterupts.size() % 2) - { - caps.addElement(InteruptEntry(mInterupts[i], 0).getKernelCapability()); - i++; - } - for (; i < mInterupts.size(); i += 2) - { - if (mInterupts[i] == InteruptEntry::kInteruptMax) - { - caps.addElement(InteruptEntry(InteruptEntry::kInteruptMax, InteruptEntry::kInteruptMax).getKernelCapability()); - } - caps.addElement(InteruptEntry(mInterupts[i], mInterupts[i+1]).getKernelCapability()); - if (mInterupts[i+1] == InteruptEntry::kInteruptMax) - { - caps.addElement(InteruptEntry(InteruptEntry::kInteruptMax, InteruptEntry::kInteruptMax).getKernelCapability()); - } - - } -} - -void nn::hac::InteruptHandler::clear() -{ - mIsSet = false; - mInterupts.clear(); -} - -bool nn::hac::InteruptHandler::isSet() const -{ - return mIsSet; -} - -const fnd::List& nn::hac::InteruptHandler::getInteruptList() const -{ - return mInterupts; -} - -void nn::hac::InteruptHandler::setInteruptList(const fnd::List& interupts) -{ - mInterupts.clear(); - for (size_t i = 0; i < interupts.size(); i++) - { - mInterupts.hasElement(interupts[i]) == false ? mInterupts.addElement(interupts[i]) : throw fnd::Exception(kModuleName, "Interupt already added"); - } - - mIsSet = true; -} \ No newline at end of file diff --git a/lib/libhac/source/KernelCapabilityControl.cpp b/lib/libhac/source/KernelCapabilityControl.cpp deleted file mode 100644 index f20ef55..0000000 --- a/lib/libhac/source/KernelCapabilityControl.cpp +++ /dev/null @@ -1,234 +0,0 @@ -#include - -nn::hac::KernelCapabilityControl::KernelCapabilityControl() -{} - -nn::hac::KernelCapabilityControl::KernelCapabilityControl(const KernelCapabilityControl & other) -{ - *this = other; -} - -void nn::hac::KernelCapabilityControl::operator=(const KernelCapabilityControl & other) -{ - clear(); - mRawBinary = other.mRawBinary; - mThreadInfo = other.mThreadInfo; - mSystemCalls = other.mSystemCalls; - mMemoryMap = other.mMemoryMap; - mInterupts = other.mInterupts; - mMiscParams = other.mMiscParams; - mKernelVersion = other.mKernelVersion; - mHandleTableSize = other.mHandleTableSize; - mMiscFlags = other.mMiscFlags; -} - -bool nn::hac::KernelCapabilityControl::operator==(const KernelCapabilityControl & other) const -{ - return (mThreadInfo == other.mThreadInfo) \ - && (mSystemCalls == other.mSystemCalls) \ - && (mMemoryMap == other.mMemoryMap) \ - && (mInterupts == other.mInterupts) \ - && (mMiscParams == other.mMiscParams) \ - && (mKernelVersion == other.mKernelVersion) \ - && (mHandleTableSize == other.mHandleTableSize) \ - && (mMiscFlags == other.mMiscFlags); -} - -bool nn::hac::KernelCapabilityControl::operator!=(const KernelCapabilityControl & other) const -{ - return !(*this == other); -} - -void nn::hac::KernelCapabilityControl::toBytes() -{ - fnd::List caps; - - // get kernel capabiliteis - mThreadInfo.exportKernelCapabilityList(caps); - mSystemCalls.exportKernelCapabilityList(caps); - mMemoryMap.exportKernelCapabilityList(caps); - mInterupts.exportKernelCapabilityList(caps); - mMiscParams.exportKernelCapabilityList(caps); - mKernelVersion.exportKernelCapabilityList(caps); - mHandleTableSize.exportKernelCapabilityList(caps); - mMiscFlags.exportKernelCapabilityList(caps); - - // allocate memory - mRawBinary.alloc(caps.size() * sizeof(uint32_t)); - - // write to binary - uint32_t* raw_caps = (uint32_t*)mRawBinary.data(); - for (size_t i = 0; i < caps.size(); i++) - { - raw_caps[i] = le_word(caps[i].getCap()); - } -} - -void nn::hac::KernelCapabilityControl::fromBytes(const byte_t * data, size_t len) -{ - if ((len % sizeof(uint32_t)) != 0) - { - throw fnd::Exception(kModuleName, "KernelCapabilityEntry list must be aligned to 4 bytes"); - } - - // save copy of KernelCapabilityControl - mRawBinary.alloc(len); - memcpy(mRawBinary.data(), data, len); - - fnd::List threadInfoCaps; - fnd::List systemCallCaps; - fnd::List memoryMapCaps; - fnd::List interuptCaps; - fnd::List miscParamCaps; - fnd::List kernelVersionCaps; - fnd::List handleTableSizeCaps; - fnd::List miscFlagsCaps; - - const le_uint32_t* raw_caps = (const le_uint32_t*)mRawBinary.data(); - size_t cap_num = mRawBinary.size() / sizeof(uint32_t); - KernelCapabilityEntry cap; - for (size_t i = 0; i < cap_num; i++) - { - cap.setCap(raw_caps[i].get()); - switch (cap.getType()) - { - case (kc::KC_THREAD_INFO) : - threadInfoCaps.addElement(cap); - break; - case (kc::KC_ENABLE_SYSTEM_CALLS): - systemCallCaps.addElement(cap); - break; - case (kc::KC_MEMORY_MAP): - case (kc::KC_IO_MEMORY_MAP): - memoryMapCaps.addElement(cap); - break; - case (kc::KC_ENABLE_INTERUPTS): - interuptCaps.addElement(cap); - break; - case (kc::KC_MISC_PARAMS): - miscParamCaps.addElement(cap); - break; - case (kc::KC_KERNEL_VERSION): - kernelVersionCaps.addElement(cap); - break; - case (kc::KC_HANDLE_TABLE_SIZE): - handleTableSizeCaps.addElement(cap); - break; - case (kc::KC_MISC_FLAGS): - miscFlagsCaps.addElement(cap); - break; - case (kc::KC_STUB): - // ignore stubbed - break; - default: - throw fnd::Exception(kModuleName, "Unsupported kernel capability type"); - } - } - - mThreadInfo.importKernelCapabilityList(threadInfoCaps); - mSystemCalls.importKernelCapabilityList(systemCallCaps); - mMemoryMap.importKernelCapabilityList(memoryMapCaps); - mInterupts.importKernelCapabilityList(interuptCaps); - mMiscParams.importKernelCapabilityList(miscParamCaps); - mKernelVersion.importKernelCapabilityList(kernelVersionCaps); - mHandleTableSize.importKernelCapabilityList(handleTableSizeCaps); - mMiscFlags.importKernelCapabilityList(miscFlagsCaps); -} - -const fnd::Vec& nn::hac::KernelCapabilityControl::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::KernelCapabilityControl::clear() -{ - mRawBinary.clear(); - mThreadInfo.clear(); - mSystemCalls.clear(); - mMemoryMap.clear(); - mInterupts.clear(); - mMiscParams.clear(); - mKernelVersion.clear(); - mHandleTableSize.clear(); - mMiscFlags.clear(); -} - -const nn::hac::ThreadInfoHandler & nn::hac::KernelCapabilityControl::getThreadInfo() const -{ - return mThreadInfo; -} - -nn::hac::ThreadInfoHandler & nn::hac::KernelCapabilityControl::getThreadInfo() -{ - return mThreadInfo; -} - -const nn::hac::SystemCallHandler & nn::hac::KernelCapabilityControl::getSystemCalls() const -{ - return mSystemCalls; -} - -nn::hac::SystemCallHandler & nn::hac::KernelCapabilityControl::getSystemCalls() -{ - return mSystemCalls; -} - -const nn::hac::MemoryMappingHandler & nn::hac::KernelCapabilityControl::getMemoryMaps() const -{ - return mMemoryMap; -} - -nn::hac::MemoryMappingHandler & nn::hac::KernelCapabilityControl::getMemoryMaps() -{ - return mMemoryMap; -} - -const nn::hac::InteruptHandler & nn::hac::KernelCapabilityControl::getInterupts() const -{ - return mInterupts; -} - -nn::hac::InteruptHandler & nn::hac::KernelCapabilityControl::getInterupts() -{ - return mInterupts; -} - -const nn::hac::MiscParamsHandler & nn::hac::KernelCapabilityControl::getMiscParams() const -{ - return mMiscParams; -} - -nn::hac::MiscParamsHandler & nn::hac::KernelCapabilityControl::getMiscParams() -{ - return mMiscParams; -} - -const nn::hac::KernelVersionHandler & nn::hac::KernelCapabilityControl::getKernelVersion() const -{ - return mKernelVersion; -} - -nn::hac::KernelVersionHandler & nn::hac::KernelCapabilityControl::getKernelVersion() -{ - return mKernelVersion; -} - -const nn::hac::HandleTableSizeHandler & nn::hac::KernelCapabilityControl::getHandleTableSize() const -{ - return mHandleTableSize; -} - -nn::hac::HandleTableSizeHandler & nn::hac::KernelCapabilityControl::getHandleTableSize() -{ - return mHandleTableSize; -} - -const nn::hac::MiscFlagsHandler & nn::hac::KernelCapabilityControl::getMiscFlags() const -{ - return mMiscFlags; -} - -nn::hac::MiscFlagsHandler & nn::hac::KernelCapabilityControl::getMiscFlags() -{ - return mMiscFlags; -} \ No newline at end of file diff --git a/lib/libhac/source/KernelCapabilityEntry.cpp b/lib/libhac/source/KernelCapabilityEntry.cpp deleted file mode 100644 index 7da3bf1..0000000 --- a/lib/libhac/source/KernelCapabilityEntry.cpp +++ /dev/null @@ -1,63 +0,0 @@ -#include - -nn::hac::KernelCapabilityEntry::KernelCapabilityEntry() : - mType(kc::KC_INVALID) -{} - -nn::hac::KernelCapabilityEntry::KernelCapabilityEntry(kc::KernelCapId type) : - mType(type), - mField(0) -{} - -nn::hac::KernelCapabilityEntry::KernelCapabilityEntry(kc::KernelCapId type, uint32_t field) : - mType(type), - mField(field) -{} - -void nn::hac::KernelCapabilityEntry::operator=(const KernelCapabilityEntry & other) -{ - mType = other.mType; - mField = other.mField; -} - -bool nn::hac::KernelCapabilityEntry::operator==(const KernelCapabilityEntry & other) const -{ - return (mType == other.mType) \ - && (mField == other.mField); -} - -bool nn::hac::KernelCapabilityEntry::operator!=(const KernelCapabilityEntry & other) const -{ - return !operator==(other); -} - -uint32_t nn::hac::KernelCapabilityEntry::getCap() const -{ - return (mField & getFieldMask()) << getFieldShift() | getCapMask(); -} - -void nn::hac::KernelCapabilityEntry::setCap(uint32_t cap) -{ - mType = getCapId(cap); - mField = (cap >> getFieldShift()) & getFieldMask(); -} - -nn::hac::kc::KernelCapId nn::hac::KernelCapabilityEntry::getType() const -{ - return mType; -} - -void nn::hac::KernelCapabilityEntry::setType(kc::KernelCapId type) -{ - mType = type; -} - -uint32_t nn::hac::KernelCapabilityEntry::getField() const -{ - return mField & getFieldMask(); -} - -void nn::hac::KernelCapabilityEntry::setField(uint32_t field) -{ - mField = field; -} diff --git a/lib/libhac/source/KernelInitialProcessHeader.cpp b/lib/libhac/source/KernelInitialProcessHeader.cpp deleted file mode 100644 index aa504e2..0000000 --- a/lib/libhac/source/KernelInitialProcessHeader.cpp +++ /dev/null @@ -1,346 +0,0 @@ -#include - -nn::hac::KernelInitialProcessHeader::KernelInitialProcessHeader() -{ - clear(); -} - -nn::hac::KernelInitialProcessHeader::KernelInitialProcessHeader(const KernelInitialProcessHeader& other) -{ - *this = other; -} - -void nn::hac::KernelInitialProcessHeader::operator=(const KernelInitialProcessHeader& other) -{ - clear(); - this->mName = other.mName; - this->mTitleId = other.mTitleId; - this->mProcessCategory = other.mProcessCategory; - this->mFlagList = other.mFlagList; - this->mMainThreadPriority = other.mMainThreadPriority; - this->mMainThreadCpuId = other.mMainThreadCpuId; - this->mMainThreadStackSize = other.mMainThreadStackSize; - this->mTextInfo = other.mTextInfo; - this->mRoInfo = other.mRoInfo; - this->mDataInfo = other.mDataInfo; - this->mBssSize = other.mBssSize; - this->mKernelCapabilities = other.mKernelCapabilities; -} - -bool nn::hac::KernelInitialProcessHeader::operator==(const KernelInitialProcessHeader& other) const -{ - return (this->mName == other.mName) \ - && (this->mTitleId == other.mTitleId) \ - && (this->mProcessCategory == other.mProcessCategory) \ - && (this->mFlagList == other.mFlagList) \ - && (this->mMainThreadPriority == other.mMainThreadPriority) \ - && (this->mMainThreadCpuId == other.mMainThreadCpuId) \ - && (this->mMainThreadStackSize == other.mMainThreadStackSize) \ - && (this->mTextInfo == other.mTextInfo) \ - && (this->mRoInfo == other.mRoInfo) \ - && (this->mDataInfo == other.mDataInfo) \ - && (this->mBssSize == other.mBssSize) \ - && (this->mKernelCapabilities == other.mKernelCapabilities); -} - -bool nn::hac::KernelInitialProcessHeader::operator!=(const KernelInitialProcessHeader& other) const -{ - return !(*this == other); -} - -void nn::hac::KernelInitialProcessHeader::toBytes() -{ - mRawBinary.alloc(sizeof(sKipHeader)); - nn::hac::sKipHeader* hdr = (nn::hac::sKipHeader*)mRawBinary.data(); - - // set header identifers - hdr->st_magic = kip::kKipStructMagic; - - // variable to store flags before commiting to header - byte_t flags = 0; - - // properties - strncpy(hdr->name, mName.c_str(), kip::kNameMaxLen); - hdr->title_id = mTitleId; - hdr->process_category = mProcessCategory; - hdr->main_thread_priority = mMainThreadPriority; - hdr->main_thread_cpu_id = mMainThreadCpuId; - hdr->main_thread_stack_size = mMainThreadStackSize; - - // kernel caps - mKernelCapabilities.toBytes(); - if (mKernelCapabilities.getBytes().size() > kip::kKernCapabilitySize) - { - throw fnd::Exception(kModuleName, "Too many kernel capabilities"); - } - memcpy(hdr->capabilities, mKernelCapabilities.getBytes().data(), mKernelCapabilities.getBytes().size()); - - // stub remaining entries - if (mKernelCapabilities.getBytes().size() < kip::kKernCapabilitySize) - { - memset(hdr->capabilities + mKernelCapabilities.getBytes().size(), 0xff, kip::kKernCapabilitySize - mKernelCapabilities.getBytes().size()); - } - - // flags - for (size_t i = 0; i < mFlagList.size(); i++) - { - switch(mFlagList[i]) - { - case (kip::FLAG_TEXT_COMPRESS) : - case (kip::FLAG_RO_COMPRESS) : - case (kip::FLAG_DATA_COMPRESS) : - break; - default: - flags |= _BIT(mFlagList[i] & 7); - break; - } - } - - // set bss size - hdr->bss.file_size = 0; - hdr->bss.memory_offset = 0; - hdr->bss.memory_size = mBssSize; - - // set text segment - hdr->text.memory_offset = mTextInfo.memory_layout.offset; - hdr->text.memory_size = mTextInfo.memory_layout.size; - hdr->text.file_size = mTextInfo.file_layout.size; - if (mTextInfo.is_compressed) - { - flags |= _BIT(kip::FLAG_TEXT_COMPRESS); - } - - // set ro segment - hdr->ro.memory_offset = mRoInfo.memory_layout.offset; - hdr->ro.memory_size = mRoInfo.memory_layout.size; - hdr->ro.file_size = mRoInfo.file_layout.size; - if (mRoInfo.is_compressed) - { - flags |= _BIT(kip::FLAG_TEXT_COMPRESS); - } - - // set data segment - hdr->data.memory_offset = mDataInfo.memory_layout.offset; - hdr->data.memory_size = mDataInfo.memory_layout.size; - hdr->data.file_size = mDataInfo.file_layout.size; - if (mDataInfo.is_compressed) - { - flags |= _BIT(kip::FLAG_TEXT_COMPRESS); - } - - hdr->flags = flags; -} - -void nn::hac::KernelInitialProcessHeader::fromBytes(const byte_t* data, size_t len) -{ - // check input data size - if (len < sizeof(sKipHeader)) - { - throw fnd::Exception(kModuleName, "KIP header size is too small"); - } - - // clear internal members - clear(); - - // allocate internal local binary copy - mRawBinary.alloc(sizeof(sKipHeader)); - memcpy(mRawBinary.data(), data, mRawBinary.size()); - - // get sKipHeader ptr - const nn::hac::sKipHeader* hdr = (const nn::hac::sKipHeader*)mRawBinary.data(); - - // check KIP signature - if (hdr->st_magic.get() != kip::kKipStructMagic) - { - throw fnd::Exception(kModuleName, "KIP header corrupt (unrecognised header signature)"); - } - - // properties - if (hdr->name[0] != 0) - mName = std::string(hdr->name, _MIN(strlen(hdr->name), kip::kNameMaxLen)); - mTitleId = hdr->title_id.get(); - mProcessCategory = (kip::ProcessCategory)hdr->process_category.get(); - mMainThreadPriority = hdr->main_thread_priority; - mMainThreadCpuId = hdr->main_thread_cpu_id; - mMainThreadStackSize = hdr->main_thread_stack_size.get(); - mKernelCapabilities.fromBytes(hdr->capabilities, kip::kKernCapabilitySize); - - for (byte_t i = 0; i < 8; i++) - { - if (_HAS_BIT(hdr->flags, i)) - { - switch(i) - { - case (kip::FLAG_TEXT_COMPRESS) : - case (kip::FLAG_RO_COMPRESS) : - case (kip::FLAG_DATA_COMPRESS) : - break; - default: - mFlagList.addElement((kip::HeaderFlags)i); - break; - } - } - } - - // code segment info - mTextInfo.file_layout.offset = sizeof(sKipHeader); - mTextInfo.file_layout.size = hdr->text.file_size.get(); - mTextInfo.memory_layout.offset = hdr->text.memory_offset.get(); - mTextInfo.memory_layout.size = hdr->text.memory_size.get(); - mTextInfo.is_compressed = _HAS_BIT(hdr->flags, kip::FLAG_TEXT_COMPRESS); - - mRoInfo.file_layout.offset = mTextInfo.file_layout.offset + mTextInfo.file_layout.size; - mRoInfo.file_layout.size = hdr->ro.file_size.get(); - mRoInfo.memory_layout.offset = hdr->ro.memory_offset.get(); - mRoInfo.memory_layout.size = hdr->ro.memory_size.get(); - mRoInfo.is_compressed = _HAS_BIT(hdr->flags, kip::FLAG_RO_COMPRESS); - - mDataInfo.file_layout.offset = mRoInfo.file_layout.offset + mRoInfo.file_layout.size; - mDataInfo.file_layout.size = hdr->data.file_size.get(); - mDataInfo.memory_layout.offset = hdr->data.memory_offset.get(); - mDataInfo.memory_layout.size = hdr->data.memory_size.get(); - mDataInfo.is_compressed = _HAS_BIT(hdr->flags, kip::FLAG_DATA_COMPRESS); - - mBssSize = hdr->bss.memory_size.get(); -} - -const fnd::Vec& nn::hac::KernelInitialProcessHeader::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::KernelInitialProcessHeader::clear() -{ - mRawBinary.clear(); - mName.clear(); - mTitleId = 0; - mProcessCategory = (kip::ProcessCategory)0; - mFlagList.clear(); - mMainThreadPriority = 0; - mMainThreadCpuId = 0; - mMainThreadStackSize = 0; - mTextInfo = sCodeSegment(); - mRoInfo = sCodeSegment(); - mDataInfo = sCodeSegment(); - mBssSize = 0; - mKernelCapabilities.clear();; -} - -const std::string& nn::hac::KernelInitialProcessHeader::getName() const -{ - return mName; -} - -void nn::hac::KernelInitialProcessHeader::setName(const std::string& name) -{ - mName = name; -} - -uint64_t nn::hac::KernelInitialProcessHeader::getTitleId() const -{ - return mTitleId; -} - -void nn::hac::KernelInitialProcessHeader::setTitleId(uint64_t title_id) -{ - mTitleId = title_id; -} - -nn::hac::kip::ProcessCategory nn::hac::KernelInitialProcessHeader::getProcessCategory() const -{ - return mProcessCategory; -} - -void nn::hac::KernelInitialProcessHeader::setProcessCategory(kip::ProcessCategory cat) -{ - mProcessCategory = cat; -} - -const fnd::List& nn::hac::KernelInitialProcessHeader::getFlagList() const -{ - return mFlagList; -} -void nn::hac::KernelInitialProcessHeader::setFlagList(const fnd::List& flags) -{ - mFlagList = flags; -} - -byte_t nn::hac::KernelInitialProcessHeader::getMainThreadPriority() const -{ - return mMainThreadPriority; -} - -void nn::hac::KernelInitialProcessHeader::setMainThreadPriority(byte_t priority) -{ - mMainThreadPriority = priority; -} - -byte_t nn::hac::KernelInitialProcessHeader::getMainThreadCpuId() const -{ - return mMainThreadCpuId; -} - -void nn::hac::KernelInitialProcessHeader::setMainThreadCpuId(byte_t cpu_id) -{ - mMainThreadCpuId = cpu_id; -} - -uint32_t nn::hac::KernelInitialProcessHeader::getMainThreadStackSize() const -{ - return mMainThreadStackSize; -} - -void nn::hac::KernelInitialProcessHeader::setMainThreadStackSize(uint32_t size) -{ - mMainThreadStackSize = size; -} - -const nn::hac::KernelInitialProcessHeader::sCodeSegment& nn::hac::KernelInitialProcessHeader::getTextSegmentInfo() const -{ - return mTextInfo; -} - -void nn::hac::KernelInitialProcessHeader::setTextSegmentInfo(const sCodeSegment& info) -{ - mTextInfo = info; -} - -const nn::hac::KernelInitialProcessHeader::sCodeSegment& nn::hac::KernelInitialProcessHeader::getRoSegmentInfo() const -{ - return mRoInfo; -} - -void nn::hac::KernelInitialProcessHeader::setRoSegmentInfo(const sCodeSegment& info) -{ - mRoInfo = info; -} - -const nn::hac::KernelInitialProcessHeader::sCodeSegment& nn::hac::KernelInitialProcessHeader::getDataSegmentInfo() const -{ - return mDataInfo; -} - -void nn::hac::KernelInitialProcessHeader::setDataSegmentInfo(const sCodeSegment& info) -{ - mDataInfo = info; -} - -uint32_t nn::hac::KernelInitialProcessHeader::getBssSize() const -{ - return mBssSize; -} - -void nn::hac::KernelInitialProcessHeader::setBssSize(uint32_t size) -{ - mBssSize = size; -} - -const nn::hac::KernelCapabilityControl& nn::hac::KernelInitialProcessHeader::getKernelCapabilities() const -{ - return mKernelCapabilities; -} - -void nn::hac::KernelInitialProcessHeader::setKernelCapabilities(const KernelCapabilityControl& kc) -{ - mKernelCapabilities = kc; -} \ No newline at end of file diff --git a/lib/libhac/source/KernelVersionEntry.cpp b/lib/libhac/source/KernelVersionEntry.cpp deleted file mode 100644 index 98343d5..0000000 --- a/lib/libhac/source/KernelVersionEntry.cpp +++ /dev/null @@ -1,90 +0,0 @@ -#include - -nn::hac::KernelVersionEntry::KernelVersionEntry() : - mCap(kCapId), - mVerMajor(0), - mVerMinor(0) -{} - -nn::hac::KernelVersionEntry::KernelVersionEntry(const KernelCapabilityEntry & kernel_cap) : - mCap(kCapId), - mVerMajor(0), - mVerMinor(0) -{ - setKernelCapability(kernel_cap); -} - -nn::hac::KernelVersionEntry::KernelVersionEntry(uint16_t major, uint8_t minor) : - mCap(kCapId), - mVerMajor(0), - mVerMinor(0) -{ - setVerMajor(major); - setVerMinor(minor); -} - -void nn::hac::KernelVersionEntry::operator=(const KernelVersionEntry& other) -{ - mVerMajor = other.mVerMajor; - mVerMinor = other.mVerMinor; - updateCapField(); -} - -bool nn::hac::KernelVersionEntry::operator==(const KernelVersionEntry& other) const -{ - return (mVerMajor == other.mVerMajor) \ - && (mVerMinor == other.mVerMinor); -} - -bool nn::hac::KernelVersionEntry::operator!=(const KernelVersionEntry& other) const -{ - return !(*this == other); -} - -const nn::hac::KernelCapabilityEntry & nn::hac::KernelVersionEntry::getKernelCapability() const -{ - return mCap; -} - -void nn::hac::KernelVersionEntry::setKernelCapability(const KernelCapabilityEntry & kernel_cap) -{ - if (kernel_cap.getType() != kCapId) - { - throw fnd::Exception(kModuleName, "KernelCapabilityEntry is not type 'KernelVersion'"); - } - - mCap = kernel_cap; - processCapField(); -} - -uint16_t nn::hac::KernelVersionEntry::getVerMajor() const -{ - return mVerMajor; -} - -void nn::hac::KernelVersionEntry::setVerMajor(uint16_t major) -{ - if (major > kVerMajorMax) - { - throw fnd::Exception(kModuleName, "Illegal KernelVersionMajor. (range: 0-0x1fff)"); - } - - mVerMajor = major; - updateCapField(); -} - -uint8_t nn::hac::KernelVersionEntry::getVerMinor() const -{ - return mVerMinor; -} - -void nn::hac::KernelVersionEntry::setVerMinor(uint8_t minor) -{ - if (minor > kVerMinorMax) - { - throw fnd::Exception(kModuleName, "Illegal KernelVersionMinor. (range: 0-0xf)"); - } - - mVerMinor = minor; - updateCapField(); -} diff --git a/lib/libhac/source/KernelVersionHandler.cpp b/lib/libhac/source/KernelVersionHandler.cpp deleted file mode 100644 index 580fa6f..0000000 --- a/lib/libhac/source/KernelVersionHandler.cpp +++ /dev/null @@ -1,80 +0,0 @@ -#include - -nn::hac::KernelVersionHandler::KernelVersionHandler() : - mIsSet(false), - mEntry(0,0) -{} - -void nn::hac::KernelVersionHandler::operator=(const KernelVersionHandler & other) -{ - mIsSet = other.mIsSet; - mEntry.setKernelCapability(other.mEntry.getKernelCapability()); -} - -bool nn::hac::KernelVersionHandler::operator==(const KernelVersionHandler & other) const -{ - return (mIsSet == other.mIsSet) \ - && (mEntry.getKernelCapability() == other.mEntry.getKernelCapability()); -} - -bool nn::hac::KernelVersionHandler::operator!=(const KernelVersionHandler & other) const -{ - return !(*this == other); -} - -void nn::hac::KernelVersionHandler::importKernelCapabilityList(const fnd::List& caps) -{ - if (caps.size() > kMaxKernelCapNum) - { - throw fnd::Exception(kModuleName, "Too many kernel capabilities"); - } - - if (caps.size() == 0) - return; - - mEntry.setKernelCapability(caps[0]); - - mIsSet = true; -} - -void nn::hac::KernelVersionHandler::exportKernelCapabilityList(fnd::List& caps) const -{ - if (isSet() == false) - return; - - caps.addElement(mEntry.getKernelCapability()); -} - -void nn::hac::KernelVersionHandler::clear() -{ - mIsSet = false; - mEntry.setVerMajor(0); - mEntry.setVerMinor(0); -} - -bool nn::hac::KernelVersionHandler::isSet() const -{ - return mIsSet; -} - -uint16_t nn::hac::KernelVersionHandler::getVerMajor() const -{ - return mEntry.getVerMajor(); -} - -void nn::hac::KernelVersionHandler::setVerMajor(uint16_t major) -{ - mEntry.setVerMajor(major); - mIsSet = true; -} - -uint8_t nn::hac::KernelVersionHandler::getVerMinor() const -{ - return mEntry.getVerMinor(); -} - -void nn::hac::KernelVersionHandler::setVerMinor(uint8_t minor) -{ - mEntry.setVerMinor(minor); - mIsSet = true; -} \ No newline at end of file diff --git a/lib/libhac/source/MemoryMappingHandler.cpp b/lib/libhac/source/MemoryMappingHandler.cpp deleted file mode 100644 index 6b12f36..0000000 --- a/lib/libhac/source/MemoryMappingHandler.cpp +++ /dev/null @@ -1,139 +0,0 @@ -#include -#include - -nn::hac::MemoryMappingHandler::MemoryMappingHandler() : - mIsSet(false) -{} - -void nn::hac::MemoryMappingHandler::operator=(const MemoryMappingHandler & other) -{ - mIsSet = other.mIsSet; - mMemRange = other.mMemRange; - mMemPage = other.mMemPage; -} - -bool nn::hac::MemoryMappingHandler::operator==(const MemoryMappingHandler & other) const -{ - return (mIsSet == other.mIsSet) \ - && (mMemRange == other.mMemRange) \ - && (mMemPage == other.mMemPage); -} - -bool nn::hac::MemoryMappingHandler::operator!=(const MemoryMappingHandler & other) const -{ - return !(*this == other); -} - -void nn::hac::MemoryMappingHandler::importKernelCapabilityList(const fnd::List& caps) -{ - if (caps.size() == 0) - return; - - // get entry list - fnd::List entries; - for (size_t i = 0; i < caps.size(); i++) - { - entries.addElement(caps[i]); - } - - mMemRange.clear(); - mMemPage.clear(); - for (size_t i = 0; i < entries.size();) - { - // has flag means "MemMap" - if (entries[i].isMultiplePages()) - { - // this entry is the last one or the next one isn't a memory map - if ((i + 1) == entries.size() || entries[i+1].isMultiplePages() == false) - { - throw fnd::Exception(kModuleName, "No paired entry"); - } - - // check valid page address - if (entries[i].getPage() > kMaxPageAddr) - { - throw fnd::Exception(kModuleName, "Illegal page address"); - } - - // check valid page num - if (entries[i+1].getPage() > kMaxPageAddr) - { - throw fnd::Exception(kModuleName, "Illegal page num"); - } - - // add to list - mMemRange.addElement({ entries[i].getPage(), entries[i+1].getPage(), entries[i].getFlag() ? MEM_RO : MEM_RW, entries[i+1].getFlag() ? MAP_STATIC : MAP_IO }); - - // increment i by two - i += 2; - } - // otherwise means "IoMemMap" - else - { - // check valid page address - if (entries[i].getPage() > kMaxPageAddr) - { - throw fnd::Exception(kModuleName, "Illegal page address"); - } - - // add to list - mMemPage.addElement({ entries[i].getPage(), 1, MEM_RW, MAP_IO }); - - // increment i by one - i += 1; - } - } - - mIsSet = true; -} - -void nn::hac::MemoryMappingHandler::exportKernelCapabilityList(fnd::List& caps) const -{ - if (isSet() == false) - return; - - MemoryPageEntry cap; - - // "mem maps" - cap.setMapMultiplePages(true); - for (size_t i = 0; i < mMemRange.size(); i++) - { - cap.setPage(mMemRange[i].addr & kMaxPageAddr); - cap.setFlag(mMemRange[i].perm == MEM_RO); - caps.addElement(cap.getKernelCapability()); - - cap.setPage(mMemRange[i].size & kMaxPageNum); - cap.setFlag(mMemRange[i].type == MAP_STATIC); - caps.addElement(cap.getKernelCapability()); - } - - // "io maps" - cap.setMapMultiplePages(false); - for (size_t i = 0; i < mMemPage.size(); i++) - { - cap.setPage(mMemPage[i].addr & kMaxPageAddr); - caps.addElement(cap.getKernelCapability()); - } -} - -void nn::hac::MemoryMappingHandler::clear() -{ - mIsSet = false; - mMemRange.clear(); - mMemPage.clear(); -} - -bool nn::hac::MemoryMappingHandler::isSet() const -{ - return mIsSet; -} - -const fnd::List& nn::hac::MemoryMappingHandler::getMemoryMaps() const -{ - return mMemRange; -} - -const fnd::List& nn::hac::MemoryMappingHandler::getIoMemoryMaps() const -{ - return mMemPage; -} \ No newline at end of file diff --git a/lib/libhac/source/MemoryPageEntry.cpp b/lib/libhac/source/MemoryPageEntry.cpp deleted file mode 100644 index 2277c09..0000000 --- a/lib/libhac/source/MemoryPageEntry.cpp +++ /dev/null @@ -1,109 +0,0 @@ -#include - -nn::hac::MemoryPageEntry::MemoryPageEntry() : - mCap(kc::KC_INVALID), - mPage(0), - mFlag(false), - mUseFlag(false) -{} - -nn::hac::MemoryPageEntry::MemoryPageEntry(const KernelCapabilityEntry & kernel_cap) : - mCap(kc::KC_INVALID), - mPage(0), - mFlag(false), - mUseFlag(false) -{ - setKernelCapability(kernel_cap); -} - -nn::hac::MemoryPageEntry::MemoryPageEntry(uint32_t page) : - mCap(kc::KC_INVALID), - mPage(0), - mFlag(false), - mUseFlag(false) -{ - setPage(page); -} - -nn::hac::MemoryPageEntry::MemoryPageEntry(uint32_t page, bool flag) : - mCap(kc::KC_INVALID), - mPage(0), - mFlag(false), - mUseFlag(true) -{ - setPage(page); - setFlag(flag); -} - -void nn::hac::MemoryPageEntry::operator=(const MemoryPageEntry& other) -{ - mPage = other.mPage; - mFlag = other.mFlag; - mUseFlag = other.mUseFlag; - updateCapField(); -} - -bool nn::hac::MemoryPageEntry::operator==(const MemoryPageEntry& other) const -{ - return (mPage == other.mPage) \ - && (mFlag == other.mFlag) \ - && (mUseFlag == other.mUseFlag); -} - -bool nn::hac::MemoryPageEntry::operator!=(const MemoryPageEntry& other) const -{ - return !(*this == other); -} - -const nn::hac::KernelCapabilityEntry & nn::hac::MemoryPageEntry::getKernelCapability() const -{ - return mCap; -} - -void nn::hac::MemoryPageEntry::setKernelCapability(const KernelCapabilityEntry & kernel_cap) -{ - if (kernel_cap.getType() != kc::KC_MEMORY_MAP && kernel_cap.getType() != kc::KC_IO_MEMORY_MAP) - { - throw fnd::Exception(kModuleName, "KernelCapabilityEntry is not type 'MemoryMap' or 'IOMemoryMap"); - } - - mCap = kernel_cap; - processCapField(); -} - -uint32_t nn::hac::MemoryPageEntry::getPage() const -{ - return mPage; -} - -void nn::hac::MemoryPageEntry::setPage(uint32_t page) -{ - if (page > kMaxPage) - { - throw fnd::Exception(kModuleName, "Illegal memory page. (range: 0x000000 - 0xFFFFFF)"); - } - - mPage = page; - updateCapField(); -} - -bool nn::hac::MemoryPageEntry::getFlag() const -{ - return mFlag; -} - -void nn::hac::MemoryPageEntry::setFlag(bool flag) -{ - mFlag = flag; - updateCapField(); -} - -bool nn::hac::MemoryPageEntry::isMultiplePages() const -{ - return mUseFlag; -} - -void nn::hac::MemoryPageEntry::setMapMultiplePages(bool useFlag) -{ - mUseFlag = useFlag; -} diff --git a/lib/libhac/source/Meta.cpp b/lib/libhac/source/Meta.cpp deleted file mode 100644 index 34e994c..0000000 --- a/lib/libhac/source/Meta.cpp +++ /dev/null @@ -1,295 +0,0 @@ -#include - -#include - -nn::hac::Meta::Meta() -{ - clear(); -} - -nn::hac::Meta::Meta(const Meta & other) : - Meta() -{ - *this = other; -} - -void nn::hac::Meta::operator=(const Meta & other) -{ - mRawBinary = other.mRawBinary; - mInstructionType = other.mInstructionType; - mProcAddressSpaceType = other.mProcAddressSpaceType; - mMainThreadPriority = other.mMainThreadPriority; - mMainThreadCpuId = other.mMainThreadCpuId; - mVersion = other.mVersion; - mMainThreadStackSize = other.mMainThreadStackSize; - mName = other.mName; - mProductCode = other.mProductCode; - mAci = other.mAci; - mAcid = other.mAcid; -} - -bool nn::hac::Meta::operator==(const Meta & other) const -{ - return (mInstructionType == other.mInstructionType) \ - && (mProcAddressSpaceType == other.mProcAddressSpaceType) \ - && (mMainThreadPriority == other.mMainThreadPriority) \ - && (mMainThreadCpuId == other.mMainThreadCpuId) \ - && (mVersion == other.mVersion) \ - && (mMainThreadStackSize == other.mMainThreadStackSize) \ - && (mName == other.mName) \ - && (mProductCode == other.mProductCode) \ - && (mAci == other.mAci) \ - && (mAcid == other.mAcid); -} - -bool nn::hac::Meta::operator!=(const Meta & other) const -{ - return !(*this == other); -} - -void nn::hac::Meta::toBytes() -{ - if (mAcid.getBytes().size() == 0) - mAcid.toBytes(); - - if (mAci.getBytes().size() == 0) - mAci.toBytes(); - - - // determine section layout - struct sLayout { - uint32_t offset, size; - } acid, aci; - - acid.offset = (uint32_t)align(sizeof(sMetaHeader), meta::kSectionAlignSize); - acid.size = (uint32_t)mAcid.getBytes().size(); - aci.offset = (uint32_t)(acid.offset + align(acid.size, meta::kSectionAlignSize)); - aci.size = (uint32_t)mAci.getBytes().size(); - - - // get total size - size_t total_size = _MAX(_MAX(acid.offset + acid.size, aci.offset + aci.size), align(sizeof(sMetaHeader), meta::kSectionAlignSize)); - - mRawBinary.alloc(total_size); - sMetaHeader* hdr = (sMetaHeader*)mRawBinary.data(); - - // set type - hdr->st_magic = meta::kMetaStructMagic; - - // set variables - byte_t flag = ((byte_t)(mInstructionType & 1) | (byte_t)((mProcAddressSpaceType & 3) << 1)) & 0xf; - hdr->flags = flag; - hdr->main_thread_priority = mMainThreadPriority; - hdr->main_thread_cpu_id = mMainThreadCpuId; - hdr->version = mVersion; - hdr->main_thread_stack_size = mMainThreadStackSize; - strncpy(hdr->name, mName.c_str(), meta::kNameMaxLen); - strncpy(hdr->product_code, mProductCode.c_str(), meta::kProductCodeMaxLen); - - // set offset/size - hdr->aci.offset = aci.offset; - hdr->aci.size = aci.size; - hdr->acid.offset = acid.offset; - hdr->acid.size = acid.size; - - // write aci & acid - if (mAci.getBytes().size() > 0) - { - memcpy(mRawBinary.data() + aci.offset, mAci.getBytes().data(), mAci.getBytes().size()); - } - if (mAcid.getBytes().size() > 0) - { - memcpy(mRawBinary.data() + acid.offset, mAcid.getBytes().data(), mAcid.getBytes().size()); - } -} - -void nn::hac::Meta::fromBytes(const byte_t* data, size_t len) -{ - // check size - if (len < sizeof(sMetaHeader)) - { - throw fnd::Exception(kModuleName, "META binary is too small"); - } - - // clear variables - clear(); - - // save a copy of the header - sMetaHeader hdr; - memcpy((void*)&hdr, data, sizeof(sMetaHeader)); - - // check magic - if (hdr.st_magic.get() != meta::kMetaStructMagic) - { - throw fnd::Exception(kModuleName, "META header corrupt (unrecognised struct signature)"); - } - - // save variables - byte_t flag = hdr.flags & 0xf; - mInstructionType = (meta::InstructionType)(flag & 1); - mProcAddressSpaceType = (meta::ProcAddrSpaceType)((flag >> 1) & 3); - mMainThreadPriority = hdr.main_thread_priority; - mMainThreadCpuId = hdr.main_thread_cpu_id; - mVersion = hdr.version.get(); - mMainThreadStackSize = hdr.main_thread_stack_size.get(); - mName = std::string(hdr.name, _MIN(strlen(hdr.name), meta::kNameMaxLen)); - mProductCode = std::string(hdr.product_code, _MIN(strlen(hdr.product_code), meta::kProductCodeMaxLen)); - - // total size - size_t total_size = _MAX(_MAX(hdr.acid.offset.get() + hdr.acid.size.get(), hdr.aci.offset.get() + hdr.aci.size.get()), sizeof(sMetaHeader)); - - // check size - if (total_size > len) - { - throw fnd::Exception(kModuleName, "META binary too small"); - } - - // save local copy - mRawBinary.alloc(total_size); - memcpy(mRawBinary.data(), data, mRawBinary.size()); - - // import Aci/Acid - if (hdr.aci.size.get()) - { - mAci.fromBytes(mRawBinary.data() + hdr.aci.offset.get(), hdr.aci.size.get()); - } - if (hdr.acid.size.get()) - { - mAcid.fromBytes(mRawBinary.data() + hdr.acid.offset.get(), hdr.acid.size.get()); - } -} - -const fnd::Vec& nn::hac::Meta::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::Meta::clear() -{ - mRawBinary.clear(); - mInstructionType = meta::INSTR_64BIT; - mProcAddressSpaceType = meta::ADDR_SPACE_64BIT; - mMainThreadPriority = 0; - mMainThreadCpuId = 0; - mVersion = 0; - mMainThreadStackSize = 0; - mName.clear(); - mProductCode.clear(); - mAci.clear(); - mAcid.clear(); -} - -nn::hac::meta::InstructionType nn::hac::Meta::getInstructionType() const -{ - return mInstructionType; -} - -void nn::hac::Meta::setInstructionType(meta::InstructionType type) -{ - mInstructionType = type; -} - -nn::hac::meta::ProcAddrSpaceType nn::hac::Meta::getProcAddressSpaceType() const -{ - return mProcAddressSpaceType; -} - -void nn::hac::Meta::setProcAddressSpaceType(meta::ProcAddrSpaceType type) -{ - mProcAddressSpaceType = type; -} - -byte_t nn::hac::Meta::getMainThreadPriority() const -{ - return mMainThreadPriority; -} - -void nn::hac::Meta::setMainThreadPriority(byte_t priority) -{ - if (priority > meta::kMaxPriority) - { - throw fnd::Exception(kModuleName, "Illegal main thread priority (range 0-63)"); - } - - mMainThreadPriority = priority; -} - -byte_t nn::hac::Meta::getMainThreadCpuId() const -{ - return mMainThreadCpuId; -} - -void nn::hac::Meta::setMainThreadCpuId(byte_t core_num) -{ - mMainThreadCpuId = core_num; -} - -uint32_t nn::hac::Meta::getVersion() const -{ - return mVersion; -} - -void nn::hac::Meta::setVersion(uint32_t version) -{ - mVersion = version; -} - -uint32_t nn::hac::Meta::getMainThreadStackSize() const -{ - return mMainThreadStackSize; -} - -void nn::hac::Meta::setMainThreadStackSize(uint32_t size) -{ - mMainThreadStackSize = size; -} - -const std::string & nn::hac::Meta::getName() const -{ - return mName; -} - -void nn::hac::Meta::setName(const std::string & name) -{ - if (name.length() > meta::kNameMaxLen) - { - throw fnd::Exception(kModuleName, "Name is too long"); - } - - mName = name; -} - -const std::string & nn::hac::Meta::getProductCode() const -{ - return mProductCode; -} - -void nn::hac::Meta::setProductCode(const std::string & product_code) -{ - if (product_code.length() > meta::kProductCodeMaxLen) - { - throw fnd::Exception(kModuleName, "Product Code is too long"); - } - - mProductCode = product_code; -} - -const nn::hac::AccessControlInfo & nn::hac::Meta::getAci() const -{ - return mAci; -} - -void nn::hac::Meta::setAci(const AccessControlInfo & aci) -{ - mAci = aci; -} - -const nn::hac::AccessControlInfoDesc & nn::hac::Meta::getAcid() const -{ - return mAcid; -} - -void nn::hac::Meta::setAcid(const AccessControlInfoDesc & acid) -{ - mAcid = acid; -} \ No newline at end of file diff --git a/lib/libhac/source/MiscFlagsEntry.cpp b/lib/libhac/source/MiscFlagsEntry.cpp deleted file mode 100644 index fe100ef..0000000 --- a/lib/libhac/source/MiscFlagsEntry.cpp +++ /dev/null @@ -1,68 +0,0 @@ -#include - -nn::hac::MiscFlagsEntry::MiscFlagsEntry() : - mCap(kCapId), - mFlags(0) -{} - -nn::hac::MiscFlagsEntry::MiscFlagsEntry(const KernelCapabilityEntry & kernel_cap) : - mCap(kCapId), - mFlags(0) -{ - setKernelCapability(kernel_cap); -} - -nn::hac::MiscFlagsEntry::MiscFlagsEntry(uint32_t flags) : - mCap(kCapId), - mFlags(0) -{ - setFlags(flags); -} - -void nn::hac::MiscFlagsEntry::operator=(const MiscFlagsEntry& other) -{ - mFlags = other.mFlags; - updateCapField(); -} - -bool nn::hac::MiscFlagsEntry::operator==(const MiscFlagsEntry& other) const -{ - return (mFlags == other.mFlags); -} - -bool nn::hac::MiscFlagsEntry::operator!=(const MiscFlagsEntry& other) const -{ - return !(*this == other); -} - -const nn::hac::KernelCapabilityEntry & nn::hac::MiscFlagsEntry::getKernelCapability() const -{ - return mCap; -} - -void nn::hac::MiscFlagsEntry::setKernelCapability(const KernelCapabilityEntry & kernel_cap) -{ - if (kernel_cap.getType() != kCapId) - { - throw fnd::Exception(kModuleName, "KernelCapabilityEntry is not type 'MiscFlags'"); - } - - mCap = kernel_cap; - processCapField(); -} - -uint32_t nn::hac::MiscFlagsEntry::getFlags() const -{ - return mFlags; -} - -void nn::hac::MiscFlagsEntry::setFlags(uint32_t flags) -{ - if ((flags & ~kMaxVal) != 0) - { - throw fnd::Exception(kModuleName, "Illegal MiscFlag bits set. (settable bits: 0-14 inclusive)"); - } - - mFlags = flags; - updateCapField(); -} diff --git a/lib/libhac/source/MiscFlagsHandler.cpp b/lib/libhac/source/MiscFlagsHandler.cpp deleted file mode 100644 index bb9a961..0000000 --- a/lib/libhac/source/MiscFlagsHandler.cpp +++ /dev/null @@ -1,89 +0,0 @@ -#include - -nn::hac::MiscFlagsHandler::MiscFlagsHandler() : - mIsSet(false) -{} - -void nn::hac::MiscFlagsHandler::operator=(const MiscFlagsHandler & other) -{ - mIsSet = other.mIsSet; - mFlags = other.mFlags; -} - -bool nn::hac::MiscFlagsHandler::operator==(const MiscFlagsHandler & other) const -{ - return (mIsSet == other.mIsSet) \ - && (mFlags == other.mFlags); -} - -bool nn::hac::MiscFlagsHandler::operator!=(const MiscFlagsHandler & other) const -{ - return !(*this == other); -} - -void nn::hac::MiscFlagsHandler::importKernelCapabilityList(const fnd::List& caps) -{ - if (caps.size() > kMaxKernelCapNum) - { - throw fnd::Exception(kModuleName, "Too many kernel capabilities"); - } - - if (caps.size() == 0) - return; - - MiscFlagsEntry entry; - entry.setKernelCapability(caps[0]); - - clear(); - for (uint32_t i = 0; i < FLAG_NUM; i++) - { - if ((entry.getFlags() & BIT(i)) == BIT(i)) - { - mFlags.addElement((Flags)i); - } - } - - mIsSet = true; -} - -void nn::hac::MiscFlagsHandler::exportKernelCapabilityList(fnd::List& caps) const -{ - if (isSet() == false) - return; - - // convert list to word flags - uint32_t flag = 0; - for (size_t i = 0; i < mFlags.size(); i++) - { - flag |= BIT(mFlags[i]); - } - - // create MiscFlag entry - MiscFlagsEntry entry; - entry.setFlags(flag); - - // add to list - caps.addElement(entry.getKernelCapability()); -} - -void nn::hac::MiscFlagsHandler::clear() -{ - mIsSet = false; - mFlags.clear(); -} - -bool nn::hac::MiscFlagsHandler::isSet() const -{ - return mIsSet; -} - -const fnd::List& nn::hac::MiscFlagsHandler::getFlagList() const -{ - return mFlags; -} - -void nn::hac::MiscFlagsHandler::setFlagList(fnd::List flags) -{ - mFlags = flags; - mIsSet = true; -} \ No newline at end of file diff --git a/lib/libhac/source/MiscParamsEntry.cpp b/lib/libhac/source/MiscParamsEntry.cpp deleted file mode 100644 index f9a14cb..0000000 --- a/lib/libhac/source/MiscParamsEntry.cpp +++ /dev/null @@ -1,68 +0,0 @@ -#include - -nn::hac::MiscParamsEntry::MiscParamsEntry() : - mCap(kCapId), - mProgramType(0) -{} - -nn::hac::MiscParamsEntry::MiscParamsEntry(const KernelCapabilityEntry & kernel_cap) : - mCap(kCapId), - mProgramType(0) -{ - setKernelCapability(kernel_cap); -} - -nn::hac::MiscParamsEntry::MiscParamsEntry(uint8_t program_type) : - mCap(kCapId), - mProgramType(0) -{ - setProgramType(program_type); -} - -void nn::hac::MiscParamsEntry::operator=(const MiscParamsEntry& other) -{ - mProgramType = other.mProgramType; - updateCapField(); -} - -bool nn::hac::MiscParamsEntry::operator==(const MiscParamsEntry& other) const -{ - return (mProgramType == other.mProgramType); -} - -bool nn::hac::MiscParamsEntry::operator!=(const MiscParamsEntry& other) const -{ - return !(*this == other); -} - -const nn::hac::KernelCapabilityEntry & nn::hac::MiscParamsEntry::getKernelCapability() const -{ - return mCap; -} - -void nn::hac::MiscParamsEntry::setKernelCapability(const KernelCapabilityEntry & kernel_cap) -{ - if (kernel_cap.getType() != kCapId) - { - throw fnd::Exception(kModuleName, "KernelCapabilityEntry is not type 'ThreadInfo'"); - } - - mCap = kernel_cap; - processCapField(); -} - -uint8_t nn::hac::MiscParamsEntry::getProgramType() const -{ - return mProgramType; -} - -void nn::hac::MiscParamsEntry::setProgramType(uint8_t type) -{ - if (type > kMaxProgramType) - { - throw fnd::Exception(kModuleName, "Illegal ProgramType. (range: 0-7 inclusive)"); - } - - mProgramType = type; - updateCapField(); -} diff --git a/lib/libhac/source/MiscParamsHandler.cpp b/lib/libhac/source/MiscParamsHandler.cpp deleted file mode 100644 index d7bc863..0000000 --- a/lib/libhac/source/MiscParamsHandler.cpp +++ /dev/null @@ -1,68 +0,0 @@ -#include - -nn::hac::MiscParamsHandler::MiscParamsHandler() : - mIsSet(false), - mEntry(0) -{} - -void nn::hac::MiscParamsHandler::operator=(const MiscParamsHandler & other) -{ - mIsSet = other.mIsSet; - mEntry.setKernelCapability(other.mEntry.getKernelCapability()); -} - -bool nn::hac::MiscParamsHandler::operator==(const MiscParamsHandler & other) const -{ - return (mIsSet == other.mIsSet) \ - && (mEntry.getKernelCapability() == other.mEntry.getKernelCapability()); -} - -bool nn::hac::MiscParamsHandler::operator!=(const MiscParamsHandler & other) const -{ - return !(*this == other); -} - -void nn::hac::MiscParamsHandler::importKernelCapabilityList(const fnd::List& caps) -{ - if (caps.size() > kMaxKernelCapNum) - { - throw fnd::Exception(kModuleName, "Too many kernel capabilities"); - } - - if (caps.size() == 0) - return; - - mEntry.setKernelCapability(caps[0]); - - mIsSet = true; -} - -void nn::hac::MiscParamsHandler::exportKernelCapabilityList(fnd::List& caps) const -{ - if (isSet() == false) - return; - - caps.addElement(mEntry.getKernelCapability()); -} - -void nn::hac::MiscParamsHandler::clear() -{ - mIsSet = false; - mEntry.setProgramType(0); -} - -bool nn::hac::MiscParamsHandler::isSet() const -{ - return mIsSet; -} - -uint8_t nn::hac::MiscParamsHandler::getProgramType() const -{ - return mEntry.getProgramType(); -} - -void nn::hac::MiscParamsHandler::setProgramType(uint8_t type) -{ - mEntry.setProgramType(type); - mIsSet = true; -} \ No newline at end of file diff --git a/lib/libhac/source/NroHeader.cpp b/lib/libhac/source/NroHeader.cpp deleted file mode 100644 index 40f8d21..0000000 --- a/lib/libhac/source/NroHeader.cpp +++ /dev/null @@ -1,270 +0,0 @@ -#include - -nn::hac::NroHeader::NroHeader() -{ - clear(); -} - -nn::hac::NroHeader::NroHeader(const NroHeader& other) -{ - *this = other; -} - -void nn::hac::NroHeader::operator=(const NroHeader& other) -{ - clear(); - mRoCrt = other.mRoCrt; - mNroSize = other.mNroSize; - mTextInfo = other.mTextInfo; - mTextInfo = other.mTextInfo; - mRoInfo = other.mRoInfo; - mDataInfo = other.mDataInfo; - mBssSize = other.mBssSize; - mModuleId = other.mModuleId; - mRoEmbeddedInfo = other.mRoEmbeddedInfo; - mRoDynStrInfo = other.mRoDynStrInfo; - mRoDynSymInfo = other.mRoDynSymInfo; -} - -bool nn::hac::NroHeader::operator==(const NroHeader& other) const -{ - return (mRoCrt == other.mRoCrt) \ - && (mNroSize == other.mNroSize) \ - && (mTextInfo == other.mTextInfo) \ - && (mTextInfo == other.mTextInfo) \ - && (mRoInfo == other.mRoInfo) \ - && (mDataInfo == other.mDataInfo) \ - && (mBssSize == other.mBssSize) \ - && (mModuleId == other.mModuleId) \ - && (mRoEmbeddedInfo == other.mRoEmbeddedInfo) \ - && (mRoDynStrInfo == other.mRoDynStrInfo) \ - && (mRoDynSymInfo == other.mRoDynSymInfo); -} - -bool nn::hac::NroHeader::operator!=(const NroHeader& other) const -{ - return !(*this == other); -} - -void nn::hac::NroHeader::toBytes() -{ - mRawBinary.alloc(sizeof(sNroHeader)); - nn::hac::sNroHeader* hdr = (nn::hac::sNroHeader*)mRawBinary.data(); - - // set header identifers - hdr->st_magic = nro::kNroStructMagic; - hdr->format_version = nro::kDefaultFormatVersion; - hdr->flags = 0; - - // set ro crt - memcpy(hdr->ro_crt, mRoCrt.data, nro::kRoCrtSize); - - // set nro size - hdr->size = mNroSize; - - // set text section - hdr->text.memory_offset = mTextInfo.memory_offset; - hdr->text.size = mTextInfo.size; - - // set ro section - hdr->ro.memory_offset = mRoInfo.memory_offset; - hdr->ro.size = mRoInfo.size; - - // set data section - hdr->data.memory_offset = mDataInfo.memory_offset; - hdr->data.size = mDataInfo.size; - - // set bss size - hdr->bss_size = mBssSize; - - // set moduleid - memcpy(hdr->module_id, mModuleId.data, nro::kModuleIdSize); - - // set ro embedded info - hdr->embedded.memory_offset = mRoEmbeddedInfo.memory_offset; - hdr->embedded.size = mRoEmbeddedInfo.size; - - // set ro dyn str info - hdr->dyn_str.memory_offset = mRoDynStrInfo.memory_offset; - hdr->dyn_str.size = mRoDynStrInfo.size; - - // set ro dyn sym info - hdr->dyn_sym.memory_offset = mRoDynSymInfo.memory_offset; - hdr->dyn_sym.size = mRoDynSymInfo.size; -} - -void nn::hac::NroHeader::fromBytes(const byte_t* data, size_t len) -{ - // check input data size - if (len < sizeof(sNroHeader)) - { - throw fnd::Exception(kModuleName, "NRO header size is too small"); - } - - // clear internal members - clear(); - - // allocate internal local binary copy - mRawBinary.alloc(sizeof(sNroHeader)); - memcpy(mRawBinary.data(), data, mRawBinary.size()); - - // get sNroHeader ptr - const nn::hac::sNroHeader* hdr = (const nn::hac::sNroHeader*)mRawBinary.data(); - - // check NRO signature - if (hdr->st_magic.get() != nro::kNroStructMagic) - { - throw fnd::Exception(kModuleName, "NRO header corrupt (unrecognised header signature)"); - } - - // check NRO format version - if (hdr->format_version.get() != nro::kDefaultFormatVersion) - { - throw fnd::Exception(kModuleName, "NRO header corrupt (unsupported format version)"); - } - - // check NRO flags - if (hdr->flags.get() != 0) - { - throw fnd::Exception(kModuleName, "NRO header corrupt (unsupported flag)"); - } - - memcpy(mRoCrt.data, hdr->ro_crt, nro::kRoCrtSize); - mNroSize = hdr->size.get(); - mTextInfo.memory_offset = hdr->text.memory_offset.get(); - mTextInfo.size = hdr->text.size.get(); - mRoInfo.memory_offset = hdr->ro.memory_offset.get(); - mRoInfo.size = hdr->ro.size.get(); - mDataInfo.memory_offset = hdr->data.memory_offset.get(); - mDataInfo.size = hdr->data.size.get(); - mBssSize = hdr->bss_size.get(); - memcpy(mModuleId.data, hdr->module_id, nro::kModuleIdSize); - - mRoEmbeddedInfo.memory_offset = hdr->embedded.memory_offset.get(); - mRoEmbeddedInfo.size = hdr->embedded.size.get(); - - mRoDynStrInfo.memory_offset = hdr->dyn_str.memory_offset.get(); - mRoDynStrInfo.size = hdr->dyn_str.size.get(); - - mRoDynSymInfo.memory_offset = hdr->dyn_sym.memory_offset.get(); - mRoDynSymInfo.size = hdr->dyn_sym.size.get(); -} - -const fnd::Vec& nn::hac::NroHeader::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::NroHeader::clear() -{ - mRawBinary.clear(); - memset(&mRoCrt, 0, sizeof(mRoCrt)); - memset(&mTextInfo, 0, sizeof(mTextInfo)); - memset(&mRoInfo, 0, sizeof(mRoInfo)); - memset(&mDataInfo, 0, sizeof(mDataInfo)); - mBssSize = 0; - memset(&mModuleId, 0, sizeof(mModuleId)); - memset(&mRoEmbeddedInfo, 0, sizeof(mRoEmbeddedInfo)); - memset(&mRoDynStrInfo, 0, sizeof(mRoDynStrInfo)); - memset(&mRoDynSymInfo, 0, sizeof(mRoDynSymInfo)); -} - -const nn::hac::NroHeader::sRoCrt& nn::hac::NroHeader::getRoCrt() const -{ - return mRoCrt; -} - -void nn::hac::NroHeader::setRoCrt(const sRoCrt& ro_crt) -{ - mRoCrt = ro_crt; -} - -uint32_t nn::hac::NroHeader::getNroSize() const -{ - return mNroSize; -} - -void nn::hac::NroHeader::setNroSize(uint32_t size) -{ - mNroSize = size; -} - -const nn::hac::NroHeader::sSection& nn::hac::NroHeader::getTextInfo() const -{ - return mTextInfo; -} - -void nn::hac::NroHeader::setTextInfo(const sSection& info) -{ - mTextInfo = info; -} - -const nn::hac::NroHeader::sSection& nn::hac::NroHeader::getRoInfo() const -{ - return mRoInfo; -} - -void nn::hac::NroHeader::setRoInfo(const sSection& info) -{ - mRoInfo = info; -} - -const nn::hac::NroHeader::sSection& nn::hac::NroHeader::getDataInfo() const -{ - return mDataInfo; -} - -void nn::hac::NroHeader::setDataInfo(const sSection& info) -{ - mDataInfo = info; -} - -uint32_t nn::hac::NroHeader::getBssSize() const -{ - return mBssSize; -} - -void nn::hac::NroHeader::setBssSize(uint32_t size) -{ - mBssSize = size; -} - -const nn::hac::NroHeader::sModuleId& nn::hac::NroHeader::getModuleId() const -{ - return mModuleId; -} - -void nn::hac::NroHeader::setModuleId(const sModuleId& id) -{ - mModuleId = id; -} - -const nn::hac::NroHeader::sSection& nn::hac::NroHeader::getRoEmbeddedInfo() const -{ - return mRoEmbeddedInfo; -} - -void nn::hac::NroHeader::setRoEmbeddedInfo(const sSection& info) -{ - mRoEmbeddedInfo = info; -} - -const nn::hac::NroHeader::sSection& nn::hac::NroHeader::getRoDynStrInfo() const -{ - return mRoDynStrInfo; -} - -void nn::hac::NroHeader::setRoDynStrInfo(const sSection& info) -{ - mRoDynStrInfo = info; -} - -const nn::hac::NroHeader::sSection& nn::hac::NroHeader::getRoDynSymInfo() const -{ - return mRoDynSymInfo; -} - -void nn::hac::NroHeader::setRoDynSymInfo(const sSection& info) -{ - mRoDynSymInfo = info; -} \ No newline at end of file diff --git a/lib/libhac/source/NsoHeader.cpp b/lib/libhac/source/NsoHeader.cpp deleted file mode 100644 index 85468fd..0000000 --- a/lib/libhac/source/NsoHeader.cpp +++ /dev/null @@ -1,306 +0,0 @@ -#include - -nn::hac::NsoHeader::NsoHeader() -{ - clear(); -} - -nn::hac::NsoHeader::NsoHeader(const NsoHeader& other) -{ - *this = other; -} - -void nn::hac::NsoHeader::operator=(const NsoHeader& other) -{ - clear(); - mModuleId = other.mModuleId; - mBssSize = other.mBssSize; - mTextSegmentInfo = other.mTextSegmentInfo; - mRoSegmentInfo = other.mRoSegmentInfo; - mDataSegmentInfo = other.mDataSegmentInfo; - mModuleNameInfo = other.mModuleNameInfo; - mRoEmbeddedInfo = other.mRoEmbeddedInfo; - mRoDynStrInfo = other.mRoDynStrInfo; - mRoDynSymInfo = other.mRoDynSymInfo; -} - - -bool nn::hac::NsoHeader::operator==(const NsoHeader& other) const -{ - return (mModuleId == other.mModuleId) \ - && (mBssSize == other.mBssSize) \ - && (mTextSegmentInfo == other.mTextSegmentInfo) \ - && (mRoSegmentInfo == other.mRoSegmentInfo) \ - && (mDataSegmentInfo == other.mDataSegmentInfo) \ - && (mModuleNameInfo == other.mModuleNameInfo) \ - && (mRoEmbeddedInfo == other.mRoEmbeddedInfo) \ - && (mRoDynStrInfo == other.mRoDynStrInfo) \ - && (mRoDynSymInfo == other.mRoDynSymInfo); -} - -bool nn::hac::NsoHeader::operator!=(const NsoHeader& other) const -{ - return !(*this == other); -} - -void nn::hac::NsoHeader::toBytes() -{ - mRawBinary.alloc(sizeof(sNsoHeader)); - nn::hac::sNsoHeader* hdr = (nn::hac::sNsoHeader*)mRawBinary.data(); - - // set header identifers - hdr->st_magic = nso::kNsoStructMagic; - hdr->format_version = nso::kDefaultFormatVersion; - - // variable to store flags before commiting to header - uint32_t flags = 0; - - // set moduleid - memcpy(hdr->module_id, mModuleId.data, nso::kModuleIdSize); - - // set bss size - hdr->bss_size = mBssSize; - - // set text segment - hdr->text.file_offset = mTextSegmentInfo.file_layout.offset; - hdr->text.memory_offset = mTextSegmentInfo.memory_layout.offset; - hdr->text.size = mTextSegmentInfo.memory_layout.size; - hdr->text_file_size = mTextSegmentInfo.file_layout.size; - if (mTextSegmentInfo.is_compressed) - { - flags |= _BIT(nso::FLAG_TEXT_COMPRESS); - } - if (mTextSegmentInfo.is_hashed) - { - flags |= _BIT(nso::FLAG_TEXT_HASH); - hdr->text_hash = mTextSegmentInfo.hash; - } - - // set ro segment - hdr->ro.file_offset = mRoSegmentInfo.file_layout.offset; - hdr->ro.memory_offset = mRoSegmentInfo.memory_layout.offset; - hdr->ro.size = mRoSegmentInfo.memory_layout.size; - hdr->ro_file_size = mRoSegmentInfo.file_layout.size; - if (mRoSegmentInfo.is_compressed) - { - flags |= _BIT(nso::FLAG_RO_COMPRESS); - } - if (mRoSegmentInfo.is_hashed) - { - flags |= _BIT(nso::FLAG_RO_HASH); - hdr->ro_hash = mRoSegmentInfo.hash; - } - - // set data segment - hdr->data.file_offset = mDataSegmentInfo.file_layout.offset; - hdr->data.memory_offset = mDataSegmentInfo.memory_layout.offset; - hdr->data.size = mDataSegmentInfo.memory_layout.size; - hdr->data_file_size = mDataSegmentInfo.file_layout.size; - if (mDataSegmentInfo.is_compressed) - { - flags |= _BIT(nso::FLAG_DATA_COMPRESS); - } - if (mDataSegmentInfo.is_hashed) - { - flags |= _BIT(nso::FLAG_DATA_HASH); - hdr->data_hash = mDataSegmentInfo.hash; - } - - // set module name info - hdr->module_name_offset = mModuleNameInfo.offset; - hdr->module_name_size = mModuleNameInfo.size; - - // set ro embedded info - hdr->embedded.offset = mRoEmbeddedInfo.offset; - hdr->embedded.size = mRoEmbeddedInfo.size; - - // set ro dyn str info - hdr->dyn_str.offset = mRoDynStrInfo.offset; - hdr->dyn_str.size = mRoDynStrInfo.size; - - // set ro dyn sym info - hdr->dyn_sym.offset = mRoDynSymInfo.offset; - hdr->dyn_sym.size = mRoDynSymInfo.size; - - hdr->flags = flags; -} - -void nn::hac::NsoHeader::fromBytes(const byte_t* data, size_t len) -{ - // check input data size - if (len < sizeof(sNsoHeader)) - { - throw fnd::Exception(kModuleName, "NSO header size is too small"); - } - - // clear internal members - clear(); - - // allocate internal local binary copy - mRawBinary.alloc(sizeof(sNsoHeader)); - memcpy(mRawBinary.data(), data, mRawBinary.size()); - - // get sNsoHeader ptr - const nn::hac::sNsoHeader* hdr = (const nn::hac::sNsoHeader*)mRawBinary.data(); - - // check NSO signature - if (hdr->st_magic.get() != nso::kNsoStructMagic) - { - throw fnd::Exception(kModuleName, "NSO header corrupt (unrecognised header signature)"); - } - - // check NSO format version - if (hdr->format_version.get() != nso::kDefaultFormatVersion) - { - throw fnd::Exception(kModuleName, "NSO header corrupt (unsupported format version)"); - } - - memcpy(mModuleId.data, hdr->module_id, nso::kModuleIdSize); - - mBssSize = hdr->bss_size.get(); - - mTextSegmentInfo.file_layout.offset = hdr->text.file_offset.get(); - mTextSegmentInfo.file_layout.size = hdr->text_file_size.get(); - mTextSegmentInfo.memory_layout.offset = hdr->text.memory_offset.get(); - mTextSegmentInfo.memory_layout.size = hdr->text.size.get(); - mTextSegmentInfo.is_compressed = _HAS_BIT(hdr->flags.get(), nso::FLAG_TEXT_COMPRESS); - mTextSegmentInfo.is_hashed = _HAS_BIT(hdr->flags.get(), nso::FLAG_TEXT_HASH); - mTextSegmentInfo.hash = hdr->text_hash; - - mRoSegmentInfo.file_layout.offset = hdr->ro.file_offset.get(); - mRoSegmentInfo.file_layout.size = hdr->ro_file_size.get(); - mRoSegmentInfo.memory_layout.offset = hdr->ro.memory_offset.get(); - mRoSegmentInfo.memory_layout.size = hdr->ro.size.get(); - mRoSegmentInfo.is_compressed = _HAS_BIT(hdr->flags.get(), nso::FLAG_RO_COMPRESS); - mRoSegmentInfo.is_hashed = _HAS_BIT(hdr->flags.get(), nso::FLAG_RO_HASH); - mRoSegmentInfo.hash = hdr->ro_hash; - - mDataSegmentInfo.file_layout.offset = hdr->data.file_offset.get(); - mDataSegmentInfo.file_layout.size = hdr->data_file_size.get(); - mDataSegmentInfo.memory_layout.offset = hdr->data.memory_offset.get(); - mDataSegmentInfo.memory_layout.size = hdr->data.size.get(); - mDataSegmentInfo.is_compressed = _HAS_BIT(hdr->flags.get(), nso::FLAG_RO_COMPRESS); - mDataSegmentInfo.is_hashed = _HAS_BIT(hdr->flags.get(), nso::FLAG_RO_HASH); - mDataSegmentInfo.hash = hdr->data_hash; - - mModuleNameInfo.offset = hdr->module_name_offset.get(); - mModuleNameInfo.size = hdr->module_name_size.get(); - - mRoEmbeddedInfo.offset = hdr->embedded.offset.get(); - mRoEmbeddedInfo.size = hdr->embedded.size.get(); - - mRoDynStrInfo.offset = hdr->dyn_str.offset.get(); - mRoDynStrInfo.size = hdr->dyn_str.size.get(); - - mRoDynSymInfo.offset = hdr->dyn_sym.offset.get(); - mRoDynSymInfo.size = hdr->dyn_sym.size.get(); -} - -const fnd::Vec& nn::hac::NsoHeader::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::NsoHeader::clear() -{ - mRawBinary.clear(); - memset(&mModuleId, 0, sizeof(mModuleId)); - mBssSize = 0; - memset(&mTextSegmentInfo, 0, sizeof(mTextSegmentInfo)); - memset(&mRoSegmentInfo, 0, sizeof(mRoSegmentInfo)); - memset(&mDataSegmentInfo, 0, sizeof(mDataSegmentInfo)); - memset(&mModuleNameInfo, 0, sizeof(mModuleNameInfo)); - memset(&mRoEmbeddedInfo, 0, sizeof(mRoEmbeddedInfo)); - memset(&mRoDynStrInfo, 0, sizeof(mRoDynStrInfo)); - memset(&mRoDynSymInfo, 0, sizeof(mRoDynSymInfo)); -} - -const nn::hac::NsoHeader::sModuleId& nn::hac::NsoHeader::getModuleId() const -{ - return mModuleId; -} - -void nn::hac::NsoHeader::setModuleId(const sModuleId& id) -{ - mModuleId = id; -} - -uint32_t nn::hac::NsoHeader::getBssSize() const -{ - return mBssSize; -} - -void nn::hac::NsoHeader::setBssSize(uint32_t size) -{ - mBssSize = size; -} - -const nn::hac::NsoHeader::sCodeSegment& nn::hac::NsoHeader::getTextSegmentInfo() const -{ - return mTextSegmentInfo; -} - -void nn::hac::NsoHeader::setTextSegmentInfo(const sCodeSegment& info) -{ - mTextSegmentInfo = info; -} - -const nn::hac::NsoHeader::sCodeSegment& nn::hac::NsoHeader::getRoSegmentInfo() const -{ - return mRoSegmentInfo; -} - -void nn::hac::NsoHeader::setRoSegmentInfo(const sCodeSegment& info) -{ - mRoSegmentInfo = info; -} - -const nn::hac::NsoHeader::sCodeSegment& nn::hac::NsoHeader::getDataSegmentInfo() const -{ - return mDataSegmentInfo; -} - -void nn::hac::NsoHeader::setDataSegmentInfo(const sCodeSegment& info) -{ - mDataSegmentInfo = info; -} - -const nn::hac::NsoHeader::sLayout& nn::hac::NsoHeader::getModuleNameInfo() const -{ - return mModuleNameInfo; -} - -void nn::hac::NsoHeader::setModuleNameInfo(const sLayout& info) -{ - mModuleNameInfo = info; -} - -const nn::hac::NsoHeader::sLayout& nn::hac::NsoHeader::getRoEmbeddedInfo() const -{ - return mRoEmbeddedInfo; -} - -void nn::hac::NsoHeader::setRoEmbeddedInfo(const sLayout& info) -{ - mRoEmbeddedInfo = info; -} - -const nn::hac::NsoHeader::sLayout& nn::hac::NsoHeader::getRoDynStrInfo() const -{ - return mRoDynStrInfo; -} - -void nn::hac::NsoHeader::setRoDynStrInfo(const sLayout& info) -{ - mRoDynStrInfo = info; -} - -const nn::hac::NsoHeader::sLayout& nn::hac::NsoHeader::getRoDynSymInfo() const -{ - return mRoDynSymInfo; -} - -void nn::hac::NsoHeader::setRoDynSymInfo(const sLayout& info) -{ - mRoDynSymInfo = info; -} \ No newline at end of file diff --git a/lib/libhac/source/PartitionFsHeader.cpp b/lib/libhac/source/PartitionFsHeader.cpp deleted file mode 100644 index 1e4a431..0000000 --- a/lib/libhac/source/PartitionFsHeader.cpp +++ /dev/null @@ -1,253 +0,0 @@ -#include - -nn::hac::PartitionFsHeader::PartitionFsHeader() -{ - clear(); -} - -nn::hac::PartitionFsHeader::PartitionFsHeader(const PartitionFsHeader & other) -{ - *this = other; -} - -void nn::hac::PartitionFsHeader::operator=(const PartitionFsHeader & other) -{ - if (other.getBytes().size()) - { - fromBytes(other.getBytes().data(), other.getBytes().size()); - } - else - { - clear(); - mFsType = other.mFsType; - mFileList = other.mFileList; - } -} - -bool nn::hac::PartitionFsHeader::operator==(const PartitionFsHeader & other) const -{ - return (mFsType == other.mFsType) \ - && (mFileList == other.mFileList); -} - -bool nn::hac::PartitionFsHeader::operator!=(const PartitionFsHeader & other) const -{ - return !(*this == other); -} - -const fnd::Vec& nn::hac::PartitionFsHeader::getBytes() const -{ - return mRawBinary; -} - - -void nn::hac::PartitionFsHeader::toBytes() -{ - // calculate name table size - size_t name_table_size = 0; - for (size_t i = 0; i < mFileList.size(); i++) - { - name_table_size += mFileList[i].name.length() + 1; - } - - size_t pfs_header_size = align(sizeof(sPfsHeader) + getFileEntrySize(mFsType) * mFileList.size() + name_table_size, pfs::kHeaderAlign); - - // align name_table_size - name_table_size = pfs_header_size - (sizeof(sPfsHeader) + getFileEntrySize(mFsType) * mFileList.size()); - - // allocate pfs header binary - mRawBinary.alloc(pfs_header_size); - sPfsHeader* hdr = (sPfsHeader*)mRawBinary.data(); - - // set header fields - switch (mFsType) - { - case (TYPE_PFS0): - hdr->st_magic = pfs::kPfsStructMagic; - break; - case (TYPE_HFS0): - hdr->st_magic = pfs::kHashedPfsStructMagic; - break; - } - - hdr->file_num = (uint32_t)mFileList.size(); - hdr->name_table_size = (uint32_t)name_table_size; - - // set file entries - if (mFsType == TYPE_PFS0) - { - sPfsFile* raw_files = (sPfsFile*)(mRawBinary.data() + sizeof(sPfsHeader)); - char* raw_name_table = (char*)(mRawBinary.data() + sizeof(sPfsHeader) + sizeof(sPfsFile) * mFileList.size()); - size_t raw_name_table_pos = 0; - - calculateOffsets(pfs_header_size); - for (size_t i = 0; i < mFileList.size(); i++) - { - raw_files[i].data_offset = (mFileList[i].offset - pfs_header_size); - raw_files[i].size = mFileList[i].size; - raw_files[i].name_offset = (uint32_t)raw_name_table_pos; - - strcpy(raw_name_table + raw_name_table_pos, mFileList[i].name.c_str()); - raw_name_table_pos += (uint32_t)(mFileList[i].name.length() + 1); - } - } - else if (mFsType == TYPE_HFS0) - { - sHashedPfsFile* raw_files = (sHashedPfsFile*)(mRawBinary.data() + sizeof(sPfsHeader)); - char* raw_name_table = (char*)(mRawBinary.data() + sizeof(sPfsHeader) + sizeof(sHashedPfsFile) * mFileList.size()); - size_t raw_name_table_pos = 0; - - calculateOffsets(pfs_header_size); - for (size_t i = 0; i < mFileList.size(); i++) - { - raw_files[i].data_offset = (mFileList[i].offset - pfs_header_size); - raw_files[i].size = mFileList[i].size; - raw_files[i].name_offset = (uint32_t)raw_name_table_pos; - raw_files[i].hash_protected_size = (uint32_t)mFileList[i].hash_protected_size; - raw_files[i].hash = mFileList[i].hash; - - strcpy(raw_name_table + raw_name_table_pos, mFileList[i].name.c_str()); - raw_name_table_pos += mFileList[i].name.length() + 1; - } - } - -} - -void nn::hac::PartitionFsHeader::fromBytes(const byte_t* data, size_t len) -{ - // check input length meets minimum size - if (len < sizeof(sPfsHeader)) - { - throw fnd::Exception(kModuleName, "PFS header too small"); - } - - // clear variables - clear(); - - // import minimum header - mRawBinary.alloc(sizeof(sPfsHeader)); - memcpy(mRawBinary.data(), data, mRawBinary.size()); - const sPfsHeader* hdr = (const sPfsHeader*)mRawBinary.data(); - - // check struct signature - FsType fs_type; - switch(hdr->st_magic.get()) - { - case (pfs::kPfsStructMagic): - fs_type = TYPE_PFS0; - break; - case (pfs::kHashedPfsStructMagic): - fs_type = TYPE_HFS0; - break; - default: - throw fnd::Exception(kModuleName, "PFS header corrupt"); - } - - // determine complete header size - size_t pfs_full_header_size = sizeof(sPfsHeader) + getFileEntrySize(fs_type) * hdr->file_num.get() + hdr->name_table_size.get(); - - // check input length meets complete size - if (len < pfs_full_header_size) - { - throw fnd::Exception(kModuleName, "PFS header too small"); - } - - // import full header - mRawBinary.alloc(pfs_full_header_size); - memcpy(mRawBinary.data(), data, mRawBinary.size()); - hdr = (const sPfsHeader*)mRawBinary.data(); - - mFsType = fs_type; - if (mFsType == TYPE_PFS0) - { - // get pointers to raw data - const sPfsFile* raw_files = (const sPfsFile*)(mRawBinary.data() + sizeof(sPfsHeader)); - const char* raw_name_table = (const char*)(mRawBinary.data() + sizeof(sPfsHeader) + sizeof(sPfsFile) * hdr->file_num.get()); - - // process file entries - for (size_t i = 0; i < hdr->file_num.get(); i++) - { - mFileList.addElement({ - std::string(raw_name_table + raw_files[i].name_offset.get()), - raw_files[i].data_offset.get() + pfs_full_header_size, - raw_files[i].size.get() - }); - } - } - else if (mFsType == TYPE_HFS0) - { - // get pointers to raw data - const sHashedPfsFile* raw_files = (const sHashedPfsFile*)(mRawBinary.data() + sizeof(sPfsHeader)); - const char* raw_name_table = (const char*)(mRawBinary.data() + sizeof(sPfsHeader) + sizeof(sHashedPfsFile) * hdr->file_num.get()); - - // process file entries - for (size_t i = 0; i < hdr->file_num.get(); i++) - { - mFileList.addElement({ - std::string(raw_name_table + raw_files[i].name_offset.get()), - raw_files[i].data_offset.get() + pfs_full_header_size, - raw_files[i].size.get(), - raw_files[i].hash_protected_size.get(), - raw_files[i].hash - }); - } - } - -} - -void nn::hac::PartitionFsHeader::clear() -{ - mRawBinary.clear(); - mFsType = TYPE_PFS0; - mFileList.clear(); -} - -nn::hac::PartitionFsHeader::FsType nn::hac::PartitionFsHeader::getFsType() const -{ - return mFsType; -} - -void nn::hac::PartitionFsHeader::setFsType(FsType type) -{ - mFsType = type; -} - -const fnd::List& nn::hac::PartitionFsHeader::getFileList() const -{ - return mFileList; -} - -void nn::hac::PartitionFsHeader::addFile(const std::string & name, size_t size) -{ - mFileList.addElement({ name, 0, size, 0 }); -} - -void nn::hac::PartitionFsHeader::addFile(const std::string & name, size_t size, size_t hash_protected_size, const fnd::sha::sSha256Hash& hash) -{ - mFileList.addElement({ name, 0, size, hash_protected_size, hash }); -} - -size_t nn::hac::PartitionFsHeader::getFileEntrySize(FsType fs_type) -{ - size_t size = 0; - switch(fs_type) - { - case (TYPE_PFS0): - size = sizeof(sPfsFile); - break; - case (TYPE_HFS0): - size = sizeof(sHashedPfsFile); - break; - default: - throw fnd::Exception(kModuleName, "Unknown PFS type"); - } - return size; -} - -void nn::hac::PartitionFsHeader::calculateOffsets(size_t data_offset) -{ - for (size_t i = 0; i < mFileList.size(); i++) - { - mFileList[i].offset = (i == 0) ? data_offset : mFileList[i - 1].offset + mFileList[i - 1].size; - } -} \ No newline at end of file diff --git a/lib/libhac/source/PatchMetaExtendedHeader.cpp b/lib/libhac/source/PatchMetaExtendedHeader.cpp deleted file mode 100644 index 02a0f4c..0000000 --- a/lib/libhac/source/PatchMetaExtendedHeader.cpp +++ /dev/null @@ -1,99 +0,0 @@ -#include - -nn::hac::PatchMetaExtendedHeader::PatchMetaExtendedHeader() -{ - clear(); -} - -nn::hac::PatchMetaExtendedHeader::PatchMetaExtendedHeader(const PatchMetaExtendedHeader& other) -{ - *this = other; -} - -void nn::hac::PatchMetaExtendedHeader::operator=(const PatchMetaExtendedHeader& other) -{ - clear(); - mRawBinary = other.mRawBinary; - mApplicationId = other.mApplicationId; - mRequiredSystemVersion = other.mRequiredSystemVersion; - mExtendedDataSize = other.mExtendedDataSize; -} - -bool nn::hac::PatchMetaExtendedHeader::operator==(const PatchMetaExtendedHeader& other) const -{ - return (mApplicationId == other.mApplicationId) \ - && (mRequiredSystemVersion == other.mRequiredSystemVersion) \ - && (mExtendedDataSize == other.mExtendedDataSize); -} - -bool nn::hac::PatchMetaExtendedHeader::operator!=(const PatchMetaExtendedHeader& other) const -{ - return !(*this == other); -} - -void nn::hac::PatchMetaExtendedHeader::toBytes() -{ - mRawBinary.alloc(sizeof(sPatchMetaExtendedHeader)); - sPatchMetaExtendedHeader* info = (sPatchMetaExtendedHeader*)mRawBinary.data(); - - info->application_id = mApplicationId; - info->required_system_version = mRequiredSystemVersion; - info->extended_data_size = mExtendedDataSize; -} - -void nn::hac::PatchMetaExtendedHeader::fromBytes(const byte_t* bytes, size_t len) -{ - if (len < sizeof(sPatchMetaExtendedHeader)) - { - throw fnd::Exception(kModuleName, "PatchMetaExtendedHeader too small"); - } - - const sPatchMetaExtendedHeader* info = (const sPatchMetaExtendedHeader*)bytes; - - mApplicationId = info->application_id.get(); - mRequiredSystemVersion = info->required_system_version.get(); - mExtendedDataSize = info->extended_data_size.get(); -} - -const fnd::Vec& nn::hac::PatchMetaExtendedHeader::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::PatchMetaExtendedHeader::clear() -{ - mRawBinary.clear(); - mApplicationId = 0; - mRequiredSystemVersion = 0; - mExtendedDataSize = 0; -} - -uint64_t nn::hac::PatchMetaExtendedHeader::getApplicationId() const -{ - return mApplicationId; -} - -void nn::hac::PatchMetaExtendedHeader::setApplicationId(uint64_t application_id) -{ - mApplicationId = application_id; -} - -uint32_t nn::hac::PatchMetaExtendedHeader::getRequiredSystemVersion() const -{ - return mRequiredSystemVersion; -} - -void nn::hac::PatchMetaExtendedHeader::setRequiredSystemVersion(uint32_t sys_ver) -{ - mRequiredSystemVersion = sys_ver; -} - -uint32_t nn::hac::PatchMetaExtendedHeader::getExtendedDataSize() const -{ - return mExtendedDataSize; -} - -void nn::hac::PatchMetaExtendedHeader::setExtendedDataSize(uint32_t size) -{ - mExtendedDataSize = size; -} \ No newline at end of file diff --git a/lib/libhac/source/Result.cpp b/lib/libhac/source/Result.cpp deleted file mode 100644 index da06c05..0000000 --- a/lib/libhac/source/Result.cpp +++ /dev/null @@ -1,62 +0,0 @@ -#include - -nn::hac::Result::Result() : - mResult(0) -{} - -nn::hac::Result::Result(uint32_t result) : - mResult(result) -{} - -nn::hac::Result::Result(uint32_t module_num, uint32_t desc, uint32_t sub_desc) : - mResult(0) -{ - mResult |= (module_num & bitWidthToMask(kModuleNumBitWidth)) << kModuleNumBitPos; - mResult |= (desc & bitWidthToMask(kDescriptionBitWidth)) << kDescriptionBitPos; - mResult |= (sub_desc & bitWidthToMask(kSubDescriptionBitWidth)) << kSubDescriptionBitPos; -} - -void nn::hac::Result::operator=(const Result & other) -{ - mResult = other.mResult; -} - -bool nn::hac::Result::operator==(const Result & other) const -{ - return mResult == other.mResult; -} - -bool nn::hac::Result::operator!=(const Result & other) const -{ - return !(*this == other); -} - -bool nn::hac::Result::isSuccess() const -{ - return mResult == 0; -} - -bool nn::hac::Result::isFailure() const -{ - return !isSuccess(); -} - -uint32_t nn::hac::Result::getInnerValue() const -{ - return mResult; -} - -uint32_t nn::hac::Result::getModuleNum() const -{ - return (mResult >> kModuleNumBitPos) & bitWidthToMask(kModuleNumBitWidth); -} - -uint32_t nn::hac::Result::getDescription() const -{ - return (mResult >> kDescriptionBitPos) & bitWidthToMask(kDescriptionBitWidth); -} - -uint32_t nn::hac::Result::getSubDescription() const -{ - return (mResult >> kSubDescriptionBitPos) & bitWidthToMask(kSubDescriptionBitWidth); -} diff --git a/lib/libhac/source/ServiceAccessControl.cpp b/lib/libhac/source/ServiceAccessControl.cpp deleted file mode 100644 index eaca784..0000000 --- a/lib/libhac/source/ServiceAccessControl.cpp +++ /dev/null @@ -1,79 +0,0 @@ -#include -#include - -nn::hac::ServiceAccessControl::ServiceAccessControl() -{ - clear(); -} - -nn::hac::ServiceAccessControl::ServiceAccessControl(const ServiceAccessControl & other) -{ - *this = other; -} - -void nn::hac::ServiceAccessControl::operator=(const ServiceAccessControl & other) -{ - mRawBinary = other.mRawBinary; - mServices = other.mServices; -} - -bool nn::hac::ServiceAccessControl::operator==(const ServiceAccessControl & other) const -{ - return (mServices == other.mServices); -} - -bool nn::hac::ServiceAccessControl::operator!=(const ServiceAccessControl & other) const -{ - return !(*this == other); -} - -void nn::hac::ServiceAccessControl::toBytes() -{ - size_t totalSize = 0; - for (size_t i = 0; i < mServices.size(); i++) - { - mServices[i].toBytes(); - totalSize += mServices[i].getBytes().size(); - } - - mRawBinary.alloc(totalSize); - for (size_t i = 0, pos = 0; i < mServices.size(); pos += mServices[i].getBytes().size(), i++) - { - memcpy((mRawBinary.data() + pos), mServices[i].getBytes().data(), mServices[i].getBytes().size()); - } -} - -void nn::hac::ServiceAccessControl::fromBytes(const byte_t* data, size_t len) -{ - clear(); - mRawBinary.alloc(len); - memcpy(mRawBinary.data(), data, mRawBinary.size()); - - ServiceAccessControlEntry sac; - for (size_t pos = 0; pos < len; pos += mServices.atBack().getBytes().size()) - { - sac.fromBytes((const byte_t*)(mRawBinary.data() + pos), len - pos); - mServices.addElement(sac); - } -} - -const fnd::Vec& nn::hac::ServiceAccessControl::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::ServiceAccessControl::clear() -{ - mRawBinary.clear(); - mServices.clear(); -} - -const fnd::List& nn::hac::ServiceAccessControl::getServiceList() const -{ - return mServices; -} - -void nn::hac::ServiceAccessControl::setServiceList(const fnd::List& list) -{ - mServices = list; -} \ No newline at end of file diff --git a/lib/libhac/source/ServiceAccessControlEntry.cpp b/lib/libhac/source/ServiceAccessControlEntry.cpp deleted file mode 100644 index 3c7a311..0000000 --- a/lib/libhac/source/ServiceAccessControlEntry.cpp +++ /dev/null @@ -1,132 +0,0 @@ -#include -#include - -nn::hac::ServiceAccessControlEntry::ServiceAccessControlEntry() -{ - clear(); -} - -nn::hac::ServiceAccessControlEntry::ServiceAccessControlEntry(const std::string & name, bool isServer) : - mIsServer(isServer), - mName(name) -{ - toBytes(); -} - -nn::hac::ServiceAccessControlEntry::ServiceAccessControlEntry(const ServiceAccessControlEntry & other) -{ - *this = other; -} - -void nn::hac::ServiceAccessControlEntry::operator=(const ServiceAccessControlEntry & other) -{ - if (other.getBytes().size()) - { - fromBytes(other.getBytes().data(), other.getBytes().size()); - } - else - { - clear(); - this->mIsServer = other.mIsServer; - this->mName = other.mName; - } -} - -bool nn::hac::ServiceAccessControlEntry::operator==(const ServiceAccessControlEntry & other) const -{ - return (mIsServer == other.mIsServer) \ - && (mName == other.mName); -} - -bool nn::hac::ServiceAccessControlEntry::operator!=(const ServiceAccessControlEntry & other) const -{ - return !(*this == other); -} - - -void nn::hac::ServiceAccessControlEntry::toBytes() -{ - try { - mRawBinary.alloc(mName.size() + 1); - } - catch (const fnd::Exception& e) - { - throw fnd::Exception(kModuleName, "Failed to allocate memory for ServiceAccessControlEntry: " + std::string(e.what())); - } - - if (mName.length() == 0) - { - throw fnd::Exception(kModuleName, "Service name is empty"); - } - - if (mName.length() > kMaxServiceNameLen) - { - throw fnd::Exception(kModuleName, "Service name string too long (max 8 chars)"); - } - - // copy data into binary blob - mRawBinary[0] = (mIsServer ? SAC_IS_SERVER : 0) | ((mName.length()-1) & SAC_NAME_LEN_MASK); // bug? - memcpy(mRawBinary.data() + 1, mName.c_str(), mName.length()); -} - -void nn::hac::ServiceAccessControlEntry::fromBytes(const byte_t* data, size_t len) -{ - bool isServer = (data[0] & SAC_IS_SERVER) == SAC_IS_SERVER; - size_t nameLen = (data[0] & SAC_NAME_LEN_MASK) + 1; // bug? - - if (nameLen+1 > len) - { - throw fnd::Exception(kModuleName, "SAC entry is too small"); - } - - if (nameLen == 0) - { - throw fnd::Exception(kModuleName, "SAC entry has no service name"); - } - else if (nameLen > kMaxServiceNameLen) - { - throw fnd::Exception(kModuleName, "Service name string too long (max 8 chars)"); - } - - mRawBinary.alloc(nameLen + 1); - memcpy(mRawBinary.data(), data, mRawBinary.size()); - - mIsServer = isServer; - mName = std::string((const char*)(mRawBinary.data() + 1), nameLen); -} - -const fnd::Vec& nn::hac::ServiceAccessControlEntry::getBytes() const -{ - return mRawBinary; -} - -void nn::hac::ServiceAccessControlEntry::clear() -{ - mIsServer = false; - mName.clear(); -} - -bool nn::hac::ServiceAccessControlEntry::isServer() const -{ - return mIsServer; -} - -void nn::hac::ServiceAccessControlEntry::setIsServer(bool isServer) -{ - mIsServer = isServer; -} - -const std::string & nn::hac::ServiceAccessControlEntry::getName() const -{ - return mName; -} - -void nn::hac::ServiceAccessControlEntry::setName(const std::string & name) -{ - if (name.length() > kMaxServiceNameLen) - { - throw fnd::Exception(kModuleName, "Service name string too long (max 8 chars)"); - } - - mName = name; -} \ No newline at end of file diff --git a/lib/libhac/source/SystemCallEntry.cpp b/lib/libhac/source/SystemCallEntry.cpp deleted file mode 100644 index 6af1677..0000000 --- a/lib/libhac/source/SystemCallEntry.cpp +++ /dev/null @@ -1,92 +0,0 @@ -#include - -nn::hac::SystemCallEntry::SystemCallEntry() : - mCap(kCapId), - mSystemCallUpper(0), - mSystemCallLower(0) -{ - -} - -nn::hac::SystemCallEntry::SystemCallEntry(const KernelCapabilityEntry & kernel_cap) : - mCap(kCapId), - mSystemCallUpper(0), - mSystemCallLower(0) -{ - setKernelCapability(kernel_cap); -} - -nn::hac::SystemCallEntry::SystemCallEntry(uint32_t upper_bits, uint32_t lower_bits) : - mCap(kCapId), - mSystemCallUpper(0), - mSystemCallLower(0) -{ - setSystemCallUpperBits(upper_bits); - setSystemCallLowerBits(lower_bits); -} - -void nn::hac::SystemCallEntry::operator=(const SystemCallEntry& other) -{ - mSystemCallUpper = other.mSystemCallUpper; - mSystemCallLower = other.mSystemCallLower; - updateCapField(); -} - -bool nn::hac::SystemCallEntry::operator==(const SystemCallEntry& other) const -{ - return (mSystemCallUpper == other.mSystemCallUpper) \ - && (mSystemCallLower == other.mSystemCallLower); -} - -bool nn::hac::SystemCallEntry::operator!=(const SystemCallEntry& other) const -{ - return !(*this == other); -} - -const nn::hac::KernelCapabilityEntry & nn::hac::SystemCallEntry::getKernelCapability() const -{ - return mCap; -} - -void nn::hac::SystemCallEntry::setKernelCapability(const KernelCapabilityEntry & kernel_cap) -{ - if (kernel_cap.getType() != kCapId) - { - throw fnd::Exception(kModuleName, "KernelCapabilityEntry is not type 'EnableSystemCalls'"); - } - - mCap = kernel_cap; - processCapField(); -} - -uint32_t nn::hac::SystemCallEntry::getSystemCallUpperBits() const -{ - return mSystemCallUpper; -} - -void nn::hac::SystemCallEntry::setSystemCallUpperBits(uint32_t upper_bits) -{ - if (upper_bits > kSysCallUpperMax) - { - throw fnd::Exception(kModuleName, "Illegal SystemCall upper bits."); - } - - mSystemCallUpper = upper_bits; - updateCapField(); -} - -uint32_t nn::hac::SystemCallEntry::getSystemCallLowerBits() const -{ - return mSystemCallLower; -} - -void nn::hac::SystemCallEntry::setSystemCallLowerBits(uint32_t lower_bits) -{ - if (lower_bits > kSysCallLowerMax) - { - throw fnd::Exception(kModuleName, "Illegal SystemCall upper bits."); - } - - mSystemCallLower = lower_bits; - updateCapField(); -} diff --git a/lib/libhac/source/SystemCallHandler.cpp b/lib/libhac/source/SystemCallHandler.cpp deleted file mode 100644 index da03380..0000000 --- a/lib/libhac/source/SystemCallHandler.cpp +++ /dev/null @@ -1,113 +0,0 @@ -#include -#include - -nn::hac::SystemCallHandler::SystemCallHandler() : - mIsSet(false), - mSystemCalls() -{} - -void nn::hac::SystemCallHandler::operator=(const SystemCallHandler & other) -{ - mIsSet = other.mIsSet; - mSystemCalls = other.mSystemCalls; -} - -bool nn::hac::SystemCallHandler::operator==(const SystemCallHandler & other) const -{ - return (mIsSet == other.mIsSet) \ - && (mSystemCalls == other.mSystemCalls); -} - -bool nn::hac::SystemCallHandler::operator!=(const SystemCallHandler & other) const -{ - return !(*this == other); -} - -void nn::hac::SystemCallHandler::importKernelCapabilityList(const fnd::List& caps) -{ - if (caps.size() == 0) - return; - - SystemCallEntry entry; - - uint8_t syscallUpper, syscall; - for (size_t i = 0; i < caps.size(); i++) - { - entry.setKernelCapability(caps[i]); - syscallUpper = 24 * entry.getSystemCallUpperBits(); - for (uint8_t j = 0; j < 24; j++) - { - syscall = syscallUpper + j; - if (((entry.getSystemCallLowerBits() >> j) & 1) == 1) - { - mSystemCalls.hasElement(syscall) == false ? mSystemCalls.addElement(syscall) : throw fnd::Exception(kModuleName, "SystemCall already added"); - } - } - } - - - mIsSet = true; -} - -void nn::hac::SystemCallHandler::exportKernelCapabilityList(fnd::List& caps) const -{ - if (isSet() == false) - return; - - SystemCallEntry entries[kSyscallTotalEntryNum]; - for (size_t i = 0; i < kSyscallTotalEntryNum; i++) - { - entries[i].setSystemCallUpperBits((uint32_t)i); - entries[i].setSystemCallLowerBits(0); - } - - for (size_t i = 0; i < mSystemCalls.size(); i++) - { - if (mSystemCalls[i] > kMaxSystemCall) - { - throw fnd::Exception(kModuleName, "Illegal SystemCall. (range: 0x00-0xBF inclusive)"); - } - - entries[mSystemCalls[i] / 24].setSystemCallLowerBits(entries[mSystemCalls[i] / 24].getSystemCallLowerBits() | BIT(mSystemCalls[i] % 24)); - } - - for (size_t i = 0; i < kSyscallTotalEntryNum; i++) - { - if (entries[i].getSystemCallLowerBits() != 0) - { - caps.addElement(entries[i].getKernelCapability()); - } - } -} - -void nn::hac::SystemCallHandler::clear() -{ - mIsSet = false; - mSystemCalls.clear(); -} - -bool nn::hac::SystemCallHandler::isSet() const -{ - return mIsSet; -} - -const fnd::List& nn::hac::SystemCallHandler::getSystemCalls() const -{ - return mSystemCalls; -} - -void nn::hac::SystemCallHandler::setSystemCallList(const fnd::List& calls) -{ - mSystemCalls.clear(); - for (size_t i = 0; i < calls.size(); i++) - { - if (mSystemCalls[i] > kMaxSystemCall) - { - throw fnd::Exception(kModuleName, "Illegal SystemCall. (range: 0x00-0xBF inclusive)"); - } - - mSystemCalls.hasElement(calls[i]) == false ? mSystemCalls.addElement(calls[i]) : throw fnd::Exception(kModuleName, "SystemCall already added"); - } - - mIsSet = true; -} \ No newline at end of file diff --git a/lib/libhac/source/ThreadInfoEntry.cpp b/lib/libhac/source/ThreadInfoEntry.cpp deleted file mode 100644 index a1c957c..0000000 --- a/lib/libhac/source/ThreadInfoEntry.cpp +++ /dev/null @@ -1,134 +0,0 @@ -#include - -nn::hac::ThreadInfoEntry::ThreadInfoEntry() : - mCap(kCapId), - mMinPriority(kDefaultPriority), - mMaxPriority(kDefaultPriority), - mMinCpuId(kDefaultCpuId), - mMaxCpuId(kDefaultCpuId) -{} - -nn::hac::ThreadInfoEntry::ThreadInfoEntry(const KernelCapabilityEntry & kernel_cap) : - mCap(kCapId), - mMinPriority(kDefaultPriority), - mMaxPriority(kDefaultPriority), - mMinCpuId(kDefaultCpuId), - mMaxCpuId(kDefaultCpuId) -{ - setKernelCapability(kernel_cap); -} - -nn::hac::ThreadInfoEntry::ThreadInfoEntry(uint8_t min_priority, uint8_t max_priority, uint8_t min_core_number, uint8_t max_core_number) : - mCap(kCapId), - mMinPriority(kDefaultPriority), - mMaxPriority(kDefaultPriority), - mMinCpuId(kDefaultCpuId), - mMaxCpuId(kDefaultCpuId) -{ - setMinPriority(min_priority); - setMaxPriority(max_priority); - setMinCpuId(min_core_number); - setMaxCpuId(max_core_number); -} - -void nn::hac::ThreadInfoEntry::operator=(const ThreadInfoEntry& other) -{ - mMinPriority = other.mMinPriority; - mMaxPriority = other.mMaxPriority; - mMinCpuId = other.mMinCpuId; - mMaxCpuId = other.mMaxCpuId; - updateCapField(); -} - -bool nn::hac::ThreadInfoEntry::operator==(const ThreadInfoEntry& other) const -{ - return (mMinPriority == other.mMinPriority) \ - && (mMaxPriority == other.mMaxPriority) \ - && (mMinCpuId == other.mMinCpuId) \ - && (mMaxCpuId == other.mMaxCpuId); -} - -bool nn::hac::ThreadInfoEntry::operator!=(const ThreadInfoEntry& other) const -{ - return !(*this == other); -} - -const nn::hac::KernelCapabilityEntry & nn::hac::ThreadInfoEntry::getKernelCapability() const -{ - return mCap; -} - -void nn::hac::ThreadInfoEntry::setKernelCapability(const KernelCapabilityEntry & kernel_cap) -{ - if (kernel_cap.getType() != kCapId) - { - throw fnd::Exception(kModuleName, "KernelCapabilityEntry is not type 'ThreadInfo'"); - } - - mCap = kernel_cap; - processCapField(); -} - -uint8_t nn::hac::ThreadInfoEntry::getMinPriority() const -{ - return mMinPriority; -} - -void nn::hac::ThreadInfoEntry::setMinPriority(uint8_t priority) -{ - if (priority > kMaxVal) - { - throw fnd::Exception(kModuleName, "Illegal MinPriority (range 0-63)"); - } - - mMinPriority = priority; - updateCapField(); -} - -uint8_t nn::hac::ThreadInfoEntry::getMaxPriority() const -{ - return mMaxPriority; -} - -void nn::hac::ThreadInfoEntry::setMaxPriority(uint8_t priority) -{ - if (priority > kMaxVal) - { - throw fnd::Exception(kModuleName, "Illegal MaxPriority (range 0-63)"); - } - - mMaxPriority = priority; - updateCapField(); -} - -uint8_t nn::hac::ThreadInfoEntry::getMinCpuId() const -{ - return mMinCpuId; -} - -void nn::hac::ThreadInfoEntry::setMinCpuId(uint8_t core_num) -{ - if (core_num > kMaxVal) - { - throw fnd::Exception(kModuleName, "Illegal MinCoreNumber (range 0-63)"); - } - - mMinCpuId = core_num; - updateCapField(); -} - -uint8_t nn::hac::ThreadInfoEntry::getMaxCpuId() const -{ - return mMaxCpuId; -} - -void nn::hac::ThreadInfoEntry::setMaxCpuId(uint8_t core_num) -{ - if (core_num > kMaxVal) - { - throw fnd::Exception(kModuleName, "Illegal MaxCoreNumber (range 0-63)"); - } - - mMaxCpuId = core_num; - updateCapField(); -} diff --git a/lib/libhac/source/ThreadInfoHandler.cpp b/lib/libhac/source/ThreadInfoHandler.cpp deleted file mode 100644 index c0d8532..0000000 --- a/lib/libhac/source/ThreadInfoHandler.cpp +++ /dev/null @@ -1,103 +0,0 @@ -#include - -nn::hac::ThreadInfoHandler::ThreadInfoHandler() : - mIsSet(false), - mEntry(0,0,0,0) -{} - -void nn::hac::ThreadInfoHandler::operator=(const ThreadInfoHandler & other) -{ - mIsSet = other.mIsSet; - mEntry.setKernelCapability(other.mEntry.getKernelCapability()); -} - -bool nn::hac::ThreadInfoHandler::operator==(const ThreadInfoHandler & other) const -{ - return (mIsSet == other.mIsSet) \ - && (mEntry.getKernelCapability() == other.mEntry.getKernelCapability()); -} - -bool nn::hac::ThreadInfoHandler::operator!=(const ThreadInfoHandler & other) const -{ - return !(*this == other); -} - -void nn::hac::ThreadInfoHandler::importKernelCapabilityList(const fnd::List& caps) -{ - if (caps.size() > kMaxKernelCapNum) - { - throw fnd::Exception(kModuleName, "Too many kernel capabilities"); - } - - if (caps.size() == 0) - return; - - mEntry.setKernelCapability(caps[0]); - mIsSet = true; -} - -void nn::hac::ThreadInfoHandler::exportKernelCapabilityList(fnd::List& caps) const -{ - if (isSet() == false) - return; - - caps.addElement(mEntry.getKernelCapability()); -} - -void nn::hac::ThreadInfoHandler::clear() -{ - mIsSet = false; - mEntry.setMaxPriority(0); - mEntry.setMinPriority(0); - mEntry.setMaxCpuId(0); - mEntry.setMinCpuId(0); -} - -bool nn::hac::ThreadInfoHandler::isSet() const -{ - return mIsSet; -} - -uint8_t nn::hac::ThreadInfoHandler::getMinPriority() const -{ - return mEntry.getMinPriority(); -} - -void nn::hac::ThreadInfoHandler::setMinPriority(uint8_t priority) -{ - mEntry.setMinPriority(priority); - mIsSet = true; -} - -uint8_t nn::hac::ThreadInfoHandler::getMaxPriority() const -{ - return mEntry.getMaxPriority(); -} - -void nn::hac::ThreadInfoHandler::setMaxPriority(uint8_t priority) -{ - mEntry.setMaxPriority(priority); - mIsSet = true; -} - -uint8_t nn::hac::ThreadInfoHandler::getMinCpuId() const -{ - return mEntry.getMinCpuId(); -} - -void nn::hac::ThreadInfoHandler::setMinCpuId(uint8_t core_num) -{ - mEntry.setMinCpuId(core_num); - mIsSet = true; -} - -uint8_t nn::hac::ThreadInfoHandler::getMaxCpuId() const -{ - return mEntry.getMaxCpuId(); -} - -void nn::hac::ThreadInfoHandler::setMaxCpuId(uint8_t core_num) -{ - mEntry.setMaxCpuId(core_num); - mIsSet = true; -} \ No newline at end of file diff --git a/lib/liblz4/include/lz4.h b/lib/liblz4/include/lz4.h deleted file mode 100644 index fd3e5d4..0000000 --- a/lib/liblz4/include/lz4.h +++ /dev/null @@ -1,607 +0,0 @@ -/* - * LZ4 - Fast LZ compression algorithm - * Header File - * Copyright (C) 2011-2017, Yann Collet. - - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - LZ4 homepage : http://www.lz4.org - - LZ4 source repository : https://github.com/lz4/lz4 -*/ -#if defined (__cplusplus) -extern "C" { -#endif - -#ifndef LZ4_H_2983827168210 -#define LZ4_H_2983827168210 - -/* --- Dependency --- */ -#include /* size_t */ - - -/** - Introduction - - LZ4 is lossless compression algorithm, providing compression speed at 400 MB/s per core, - scalable with multi-cores CPU. It features an extremely fast decoder, with speed in - multiple GB/s per core, typically reaching RAM speed limits on multi-core systems. - - The LZ4 compression library provides in-memory compression and decompression functions. - Compression can be done in: - - a single step (described as Simple Functions) - - a single step, reusing a context (described in Advanced Functions) - - unbounded multiple steps (described as Streaming compression) - - lz4.h provides block compression functions. It gives full buffer control to user. - Decompressing an lz4-compressed block also requires metadata (such as compressed size). - Each application is free to encode such metadata in whichever way it wants. - - An additional format, called LZ4 frame specification (doc/lz4_Frame_format.md), - take care of encoding standard metadata alongside LZ4-compressed blocks. - If your application requires interoperability, it's recommended to use it. - A library is provided to take care of it, see lz4frame.h. -*/ - -/*^*************************************************************** -* Export parameters -*****************************************************************/ -/* -* LZ4_DLL_EXPORT : -* Enable exporting of functions when building a Windows DLL -* LZ4LIB_VISIBILITY : -* Control library symbols visibility. -*/ -#ifndef LZ4LIB_VISIBILITY -# if defined(__GNUC__) && (__GNUC__ >= 4) -# define LZ4LIB_VISIBILITY __attribute__ ((visibility ("default"))) -# else -# define LZ4LIB_VISIBILITY -# endif -#endif -#if defined(LZ4_DLL_EXPORT) && (LZ4_DLL_EXPORT==1) -# define LZ4LIB_API __declspec(dllexport) LZ4LIB_VISIBILITY -#elif defined(LZ4_DLL_IMPORT) && (LZ4_DLL_IMPORT==1) -# define LZ4LIB_API __declspec(dllimport) LZ4LIB_VISIBILITY /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/ -#else -# define LZ4LIB_API LZ4LIB_VISIBILITY -#endif - -/*------ Version ------*/ -#define LZ4_VERSION_MAJOR 1 /* for breaking interface changes */ -#define LZ4_VERSION_MINOR 8 /* for new (non-breaking) interface capabilities */ -#define LZ4_VERSION_RELEASE 2 /* for tweaks, bug-fixes, or development */ - -#define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE) - -#define LZ4_LIB_VERSION LZ4_VERSION_MAJOR.LZ4_VERSION_MINOR.LZ4_VERSION_RELEASE -#define LZ4_QUOTE(str) #str -#define LZ4_EXPAND_AND_QUOTE(str) LZ4_QUOTE(str) -#define LZ4_VERSION_STRING LZ4_EXPAND_AND_QUOTE(LZ4_LIB_VERSION) - -LZ4LIB_API int LZ4_versionNumber (void); /**< library version number; useful to check dll version */ -LZ4LIB_API const char* LZ4_versionString (void); /**< library version string; unseful to check dll version */ - - -/*-************************************ -* Tuning parameter -**************************************/ -/*! - * LZ4_MEMORY_USAGE : - * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.) - * Increasing memory usage improves compression ratio - * Reduced memory usage may improve speed, thanks to cache effect - * Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache - */ -#ifndef LZ4_MEMORY_USAGE -# define LZ4_MEMORY_USAGE 14 -#endif - -/*-************************************ -* Simple Functions -**************************************/ -/*! LZ4_compress_default() : - Compresses 'srcSize' bytes from buffer 'src' - into already allocated 'dst' buffer of size 'dstCapacity'. - Compression is guaranteed to succeed if 'dstCapacity' >= LZ4_compressBound(srcSize). - It also runs faster, so it's a recommended setting. - If the function cannot compress 'src' into a more limited 'dst' budget, - compression stops *immediately*, and the function result is zero. - Note : as a consequence, 'dst' content is not valid. - Note 2 : This function is protected against buffer overflow scenarios (never writes outside 'dst' buffer, nor read outside 'source' buffer). - srcSize : max supported value is LZ4_MAX_INPUT_SIZE. - dstCapacity : size of buffer 'dst' (which must be already allocated) - return : the number of bytes written into buffer 'dst' (necessarily <= dstCapacity) - or 0 if compression fails */ -LZ4LIB_API int LZ4_compress_default(const char* src, char* dst, int srcSize, int dstCapacity); - -/*! LZ4_decompress_safe() : - compressedSize : is the exact complete size of the compressed block. - dstCapacity : is the size of destination buffer, which must be already allocated. - return : the number of bytes decompressed into destination buffer (necessarily <= dstCapacity) - If destination buffer is not large enough, decoding will stop and output an error code (negative value). - If the source stream is detected malformed, the function will stop decoding and return a negative result. - This function is protected against malicious data packets. -*/ -LZ4LIB_API int LZ4_decompress_safe (const char* src, char* dst, int compressedSize, int dstCapacity); - - -/*-************************************ -* Advanced Functions -**************************************/ -#define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */ -#define LZ4_COMPRESSBOUND(isize) ((unsigned)(isize) > (unsigned)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16) - -/*! -LZ4_compressBound() : - Provides the maximum size that LZ4 compression may output in a "worst case" scenario (input data not compressible) - This function is primarily useful for memory allocation purposes (destination buffer size). - Macro LZ4_COMPRESSBOUND() is also provided for compilation-time evaluation (stack memory allocation for example). - Note that LZ4_compress_default() compresses faster when dstCapacity is >= LZ4_compressBound(srcSize) - inputSize : max supported value is LZ4_MAX_INPUT_SIZE - return : maximum output size in a "worst case" scenario - or 0, if input size is incorrect (too large or negative) -*/ -LZ4LIB_API int LZ4_compressBound(int inputSize); - -/*! -LZ4_compress_fast() : - Same as LZ4_compress_default(), but allows selection of "acceleration" factor. - The larger the acceleration value, the faster the algorithm, but also the lesser the compression. - It's a trade-off. It can be fine tuned, with each successive value providing roughly +~3% to speed. - An acceleration value of "1" is the same as regular LZ4_compress_default() - Values <= 0 will be replaced by ACCELERATION_DEFAULT (currently == 1, see lz4.c). -*/ -LZ4LIB_API int LZ4_compress_fast (const char* src, char* dst, int srcSize, int dstCapacity, int acceleration); - - -/*! -LZ4_compress_fast_extState() : - Same compression function, just using an externally allocated memory space to store compression state. - Use LZ4_sizeofState() to know how much memory must be allocated, - and allocate it on 8-bytes boundaries (using malloc() typically). - Then, provide it as 'void* state' to compression function. -*/ -LZ4LIB_API int LZ4_sizeofState(void); -LZ4LIB_API int LZ4_compress_fast_extState (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration); - - -/*! -LZ4_compress_destSize() : - Reverse the logic : compresses as much data as possible from 'src' buffer - into already allocated buffer 'dst' of size 'targetDestSize'. - This function either compresses the entire 'src' content into 'dst' if it's large enough, - or fill 'dst' buffer completely with as much data as possible from 'src'. - *srcSizePtr : will be modified to indicate how many bytes where read from 'src' to fill 'dst'. - New value is necessarily <= old value. - return : Nb bytes written into 'dst' (necessarily <= targetDestSize) - or 0 if compression fails -*/ -LZ4LIB_API int LZ4_compress_destSize (const char* src, char* dst, int* srcSizePtr, int targetDstSize); - - -/*! -LZ4_decompress_fast() : **unsafe!** -This function is a bit faster than LZ4_decompress_safe(), -but it may misbehave on malformed input because it doesn't perform full validation of compressed data. - originalSize : is the uncompressed size to regenerate - Destination buffer must be already allocated, and its size must be >= 'originalSize' bytes. - return : number of bytes read from source buffer (== compressed size). - If the source stream is detected malformed, the function stops decoding and return a negative result. - note : This function is only usable if the originalSize of uncompressed data is known in advance. - The caller should also check that all the compressed input has been consumed properly, - i.e. that the return value matches the size of the buffer with compressed input. - The function never writes past the output buffer. However, since it doesn't know its 'src' size, - it may read past the intended input. Also, because match offsets are not validated during decoding, - reads from 'src' may underflow. Use this function in trusted environment **only**. -*/ -LZ4LIB_API int LZ4_decompress_fast (const char* src, char* dst, int originalSize); - -/*! -LZ4_decompress_safe_partial() : - This function decompress a compressed block of size 'srcSize' at position 'src' - into destination buffer 'dst' of size 'dstCapacity'. - The function will decompress a minimum of 'targetOutputSize' bytes, and stop after that. - However, it's not accurate, and may write more than 'targetOutputSize' (but always <= dstCapacity). - @return : the number of bytes decoded in the destination buffer (necessarily <= dstCapacity) - Note : this number can also be < targetOutputSize, if compressed block contains less data. - Therefore, always control how many bytes were decoded. - If source stream is detected malformed, function returns a negative result. - This function is protected against malicious data packets. -*/ -LZ4LIB_API int LZ4_decompress_safe_partial (const char* src, char* dst, int srcSize, int targetOutputSize, int dstCapacity); - - -/*-********************************************* -* Streaming Compression Functions -***********************************************/ -typedef union LZ4_stream_u LZ4_stream_t; /* incomplete type (defined later) */ - -/*! LZ4_createStream() and LZ4_freeStream() : - * LZ4_createStream() will allocate and initialize an `LZ4_stream_t` structure. - * LZ4_freeStream() releases its memory. - */ -LZ4LIB_API LZ4_stream_t* LZ4_createStream(void); -LZ4LIB_API int LZ4_freeStream (LZ4_stream_t* streamPtr); - -/*! LZ4_resetStream() : - * An LZ4_stream_t structure can be allocated once and re-used multiple times. - * Use this function to start compressing a new stream. - */ -LZ4LIB_API void LZ4_resetStream (LZ4_stream_t* streamPtr); - -/*! LZ4_loadDict() : - * Use this function to load a static dictionary into LZ4_stream_t. - * Any previous data will be forgotten, only 'dictionary' will remain in memory. - * Loading a size of 0 is allowed, and is the same as reset. - * @return : dictionary size, in bytes (necessarily <= 64 KB) - */ -LZ4LIB_API int LZ4_loadDict (LZ4_stream_t* streamPtr, const char* dictionary, int dictSize); - -/*! LZ4_compress_fast_continue() : - * Compress 'src' content using data from previously compressed blocks, for better compression ratio. - * 'dst' buffer must be already allocated. - * If dstCapacity >= LZ4_compressBound(srcSize), compression is guaranteed to succeed, and runs faster. - * - * Important : The previous 64KB of compressed data is assumed to remain present and unmodified in memory! - * - * Special 1 : When input is a double-buffer, they can have any size, including < 64 KB. - * Make sure that buffers are separated by at least one byte. - * This way, each block only depends on previous block. - * Special 2 : If input buffer is a ring-buffer, it can have any size, including < 64 KB. - * - * @return : size of compressed block - * or 0 if there is an error (typically, cannot fit into 'dst'). - * After an error, the stream status is invalid, it can only be reset or freed. - */ -LZ4LIB_API int LZ4_compress_fast_continue (LZ4_stream_t* streamPtr, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration); - -/*! LZ4_saveDict() : - * If last 64KB data cannot be guaranteed to remain available at its current memory location, - * save it into a safer place (char* safeBuffer). - * This is schematically equivalent to a memcpy() followed by LZ4_loadDict(), - * but is much faster, because LZ4_saveDict() doesn't need to rebuild tables. - * @return : saved dictionary size in bytes (necessarily <= maxDictSize), or 0 if error. - */ -LZ4LIB_API int LZ4_saveDict (LZ4_stream_t* streamPtr, char* safeBuffer, int maxDictSize); - - -/*-********************************************** -* Streaming Decompression Functions -* Bufferless synchronous API -************************************************/ -typedef union LZ4_streamDecode_u LZ4_streamDecode_t; /* tracking context */ - -/*! LZ4_createStreamDecode() and LZ4_freeStreamDecode() : - * creation / destruction of streaming decompression tracking context. - * A tracking context can be re-used multiple times. - */ -LZ4LIB_API LZ4_streamDecode_t* LZ4_createStreamDecode(void); -LZ4LIB_API int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream); - -/*! LZ4_setStreamDecode() : - * An LZ4_streamDecode_t context can be allocated once and re-used multiple times. - * Use this function to start decompression of a new stream of blocks. - * A dictionary can optionnally be set. Use NULL or size 0 for a reset order. - * Dictionary is presumed stable : it must remain accessible and unmodified during next decompression. - * @return : 1 if OK, 0 if error - */ -LZ4LIB_API int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize); - -/*! LZ4_decoderRingBufferSize() : v1.8.2 - * Note : in a ring buffer scenario (optional), - * blocks are presumed decompressed next to each other - * up to the moment there is not enough remaining space for next block (remainingSize < maxBlockSize), - * at which stage it resumes from beginning of ring buffer. - * When setting such a ring buffer for streaming decompression, - * provides the minimum size of this ring buffer - * to be compatible with any source respecting maxBlockSize condition. - * @return : minimum ring buffer size, - * or 0 if there is an error (invalid maxBlockSize). - */ -LZ4LIB_API int LZ4_decoderRingBufferSize(int maxBlockSize); -#define LZ4_DECODER_RING_BUFFER_SIZE(mbs) (65536 + 14 + (mbs)) /* for static allocation; mbs presumed valid */ - -/*! LZ4_decompress_*_continue() : - * These decoding functions allow decompression of consecutive blocks in "streaming" mode. - * A block is an unsplittable entity, it must be presented entirely to a decompression function. - * Decompression functions only accepts one block at a time. - * The last 64KB of previously decoded data *must* remain available and unmodified at the memory position where they were decoded. - * If less than 64KB of data has been decoded, all the data must be present. - * - * Special : if decompression side sets a ring buffer, it must respect one of the following conditions : - * - Decompression buffer size is _at least_ LZ4_decoderRingBufferSize(maxBlockSize). - * maxBlockSize is the maximum size of any single block. It can have any value > 16 bytes. - * In which case, encoding and decoding buffers do not need to be synchronized. - * Actually, data can be produced by any source compliant with LZ4 format specification, and respecting maxBlockSize. - * - Synchronized mode : - * Decompression buffer size is _exactly_ the same as compression buffer size, - * and follows exactly same update rule (block boundaries at same positions), - * and decoding function is provided with exact decompressed size of each block (exception for last block of the stream), - * _then_ decoding & encoding ring buffer can have any size, including small ones ( < 64 KB). - * - Decompression buffer is larger than encoding buffer, by a minimum of maxBlockSize more bytes. - * In which case, encoding and decoding buffers do not need to be synchronized, - * and encoding ring buffer can have any size, including small ones ( < 64 KB). - * - * Whenever these conditions are not possible, - * save the last 64KB of decoded data into a safe buffer where it can't be modified during decompression, - * then indicate where this data is saved using LZ4_setStreamDecode(), before decompressing next block. -*/ -LZ4LIB_API int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst, int srcSize, int dstCapacity); -LZ4LIB_API int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst, int originalSize); - - -/*! LZ4_decompress_*_usingDict() : - * These decoding functions work the same as - * a combination of LZ4_setStreamDecode() followed by LZ4_decompress_*_continue() - * They are stand-alone, and don't need an LZ4_streamDecode_t structure. - * Dictionary is presumed stable : it must remain accessible and unmodified during next decompression. - */ -LZ4LIB_API int LZ4_decompress_safe_usingDict (const char* src, char* dst, int srcSize, int dstCapcity, const char* dictStart, int dictSize); -LZ4LIB_API int LZ4_decompress_fast_usingDict (const char* src, char* dst, int originalSize, const char* dictStart, int dictSize); - - -/*^********************************************** - * !!!!!! STATIC LINKING ONLY !!!!!! - ***********************************************/ - -/*-************************************ - * Unstable declarations - ************************************** - * Declarations in this section should be considered unstable. - * Use at your own peril, etc., etc. - * They may be removed in the future. - * Their signatures may change. - **************************************/ - -#ifdef LZ4_STATIC_LINKING_ONLY - -/*! LZ4_resetStream_fast() : - * Use this, like LZ4_resetStream(), to prepare a context for a new chain of - * calls to a streaming API (e.g., LZ4_compress_fast_continue()). - * - * Note: - * Using this in advance of a non- streaming-compression function is redundant, - * and potentially bad for performance, since they all perform their own custom - * reset internally. - * - * Differences from LZ4_resetStream(): - * When an LZ4_stream_t is known to be in a internally coherent state, - * it can often be prepared for a new compression with almost no work, only - * sometimes falling back to the full, expensive reset that is always required - * when the stream is in an indeterminate state (i.e., the reset performed by - * LZ4_resetStream()). - * - * LZ4_streams are guaranteed to be in a valid state when: - * - returned from LZ4_createStream() - * - reset by LZ4_resetStream() - * - memset(stream, 0, sizeof(LZ4_stream_t)), though this is discouraged - * - the stream was in a valid state and was reset by LZ4_resetStream_fast() - * - the stream was in a valid state and was then used in any compression call - * that returned success - * - the stream was in an indeterminate state and was used in a compression - * call that fully reset the state (e.g., LZ4_compress_fast_extState()) and - * that returned success - * - * When a stream isn't known to be in a valid state, it is not safe to pass to - * any fastReset or streaming function. It must first be cleansed by the full - * LZ4_resetStream(). - */ -LZ4LIB_API void LZ4_resetStream_fast (LZ4_stream_t* streamPtr); - -/*! LZ4_compress_fast_extState_fastReset() : - * A variant of LZ4_compress_fast_extState(). - * - * Using this variant avoids an expensive initialization step. It is only safe - * to call if the state buffer is known to be correctly initialized already - * (see above comment on LZ4_resetStream_fast() for a definition of "correctly - * initialized"). From a high level, the difference is that this function - * initializes the provided state with a call to something like - * LZ4_resetStream_fast() while LZ4_compress_fast_extState() starts with a - * call to LZ4_resetStream(). - */ -LZ4LIB_API int LZ4_compress_fast_extState_fastReset (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration); - -/*! LZ4_attach_dictionary() : - * This is an experimental API that allows for the efficient use of a - * static dictionary many times. - * - * Rather than re-loading the dictionary buffer into a working context before - * each compression, or copying a pre-loaded dictionary's LZ4_stream_t into a - * working LZ4_stream_t, this function introduces a no-copy setup mechanism, - * in which the working stream references the dictionary stream in-place. - * - * Several assumptions are made about the state of the dictionary stream. - * Currently, only streams which have been prepared by LZ4_loadDict() should - * be expected to work. - * - * Alternatively, the provided dictionary stream pointer may be NULL, in which - * case any existing dictionary stream is unset. - * - * If a dictionary is provided, it replaces any pre-existing stream history. - * The dictionary contents are the only history that can be referenced and - * logically immediately precede the data compressed in the first subsequent - * compression call. - * - * The dictionary will only remain attached to the working stream through the - * first compression call, at the end of which it is cleared. The dictionary - * stream (and source buffer) must remain in-place / accessible / unchanged - * through the completion of the first compression call on the stream. - */ -LZ4LIB_API void LZ4_attach_dictionary(LZ4_stream_t *working_stream, const LZ4_stream_t *dictionary_stream); - -#endif - -/*-************************************ - * Private definitions - ************************************** - * Do not use these definitions. - * They are exposed to allow static allocation of `LZ4_stream_t` and `LZ4_streamDecode_t`. - * Using these definitions will expose code to API and/or ABI break in future versions of the library. - **************************************/ -#define LZ4_HASHLOG (LZ4_MEMORY_USAGE-2) -#define LZ4_HASHTABLESIZE (1 << LZ4_MEMORY_USAGE) -#define LZ4_HASH_SIZE_U32 (1 << LZ4_HASHLOG) /* required as macro for static allocation */ - -#if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) -#include - -typedef struct LZ4_stream_t_internal LZ4_stream_t_internal; -struct LZ4_stream_t_internal { - uint32_t hashTable[LZ4_HASH_SIZE_U32]; - uint32_t currentOffset; - uint16_t initCheck; - uint16_t tableType; - const uint8_t* dictionary; - const LZ4_stream_t_internal* dictCtx; - uint32_t dictSize; -}; - -typedef struct { - const uint8_t* externalDict; - size_t extDictSize; - const uint8_t* prefixEnd; - size_t prefixSize; -} LZ4_streamDecode_t_internal; - -#else - -typedef struct LZ4_stream_t_internal LZ4_stream_t_internal; -struct LZ4_stream_t_internal { - unsigned int hashTable[LZ4_HASH_SIZE_U32]; - unsigned int currentOffset; - unsigned short initCheck; - unsigned short tableType; - const unsigned char* dictionary; - const LZ4_stream_t_internal* dictCtx; - unsigned int dictSize; -}; - -typedef struct { - const unsigned char* externalDict; - size_t extDictSize; - const unsigned char* prefixEnd; - size_t prefixSize; -} LZ4_streamDecode_t_internal; - -#endif - -/*! - * LZ4_stream_t : - * information structure to track an LZ4 stream. - * init this structure before first use. - * note : only use in association with static linking ! - * this definition is not API/ABI safe, - * it may change in a future version ! - */ -#define LZ4_STREAMSIZE_U64 ((1 << (LZ4_MEMORY_USAGE-3)) + 4) -#define LZ4_STREAMSIZE (LZ4_STREAMSIZE_U64 * sizeof(unsigned long long)) -union LZ4_stream_u { - unsigned long long table[LZ4_STREAMSIZE_U64]; - LZ4_stream_t_internal internal_donotuse; -} ; /* previously typedef'd to LZ4_stream_t */ - - -/*! - * LZ4_streamDecode_t : - * information structure to track an LZ4 stream during decompression. - * init this structure using LZ4_setStreamDecode (or memset()) before first use - * note : only use in association with static linking ! - * this definition is not API/ABI safe, - * and may change in a future version ! - */ -#define LZ4_STREAMDECODESIZE_U64 4 -#define LZ4_STREAMDECODESIZE (LZ4_STREAMDECODESIZE_U64 * sizeof(unsigned long long)) -union LZ4_streamDecode_u { - unsigned long long table[LZ4_STREAMDECODESIZE_U64]; - LZ4_streamDecode_t_internal internal_donotuse; -} ; /* previously typedef'd to LZ4_streamDecode_t */ - - -/*-************************************ -* Obsolete Functions -**************************************/ - -/*! Deprecation warnings - Should deprecation warnings be a problem, - it is generally possible to disable them, - typically with -Wno-deprecated-declarations for gcc - or _CRT_SECURE_NO_WARNINGS in Visual. - Otherwise, it's also possible to define LZ4_DISABLE_DEPRECATE_WARNINGS */ -#ifdef LZ4_DISABLE_DEPRECATE_WARNINGS -# define LZ4_DEPRECATED(message) /* disable deprecation warnings */ -#else -# define LZ4_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) -# if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */ -# define LZ4_DEPRECATED(message) [[deprecated(message)]] -# elif (LZ4_GCC_VERSION >= 405) || defined(__clang__) -# define LZ4_DEPRECATED(message) __attribute__((deprecated(message))) -# elif (LZ4_GCC_VERSION >= 301) -# define LZ4_DEPRECATED(message) __attribute__((deprecated)) -# elif defined(_MSC_VER) -# define LZ4_DEPRECATED(message) __declspec(deprecated(message)) -# else -# pragma message("WARNING: You need to implement LZ4_DEPRECATED for this compiler") -# define LZ4_DEPRECATED(message) -# endif -#endif /* LZ4_DISABLE_DEPRECATE_WARNINGS */ - -/* Obsolete compression functions */ -LZ4_DEPRECATED("use LZ4_compress_default() instead") LZ4LIB_API int LZ4_compress (const char* source, char* dest, int sourceSize); -LZ4_DEPRECATED("use LZ4_compress_default() instead") LZ4LIB_API int LZ4_compress_limitedOutput (const char* source, char* dest, int sourceSize, int maxOutputSize); -LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") LZ4LIB_API int LZ4_compress_withState (void* state, const char* source, char* dest, int inputSize); -LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") LZ4LIB_API int LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize); -LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") LZ4LIB_API int LZ4_compress_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize); -LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") LZ4LIB_API int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize, int maxOutputSize); - -/* Obsolete decompression functions */ -LZ4_DEPRECATED("use LZ4_decompress_fast() instead") LZ4LIB_API int LZ4_uncompress (const char* source, char* dest, int outputSize); -LZ4_DEPRECATED("use LZ4_decompress_safe() instead") LZ4LIB_API int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize); - -/* Obsolete streaming functions; degraded functionality; do not use! - * - * In order to perform streaming compression, these functions depended on data - * that is no longer tracked in the state. They have been preserved as well as - * possible: using them will still produce a correct output. However, they don't - * actually retain any history between compression calls. The compression ratio - * achieved will therefore be no better than compressing each chunk - * independently. - */ -LZ4_DEPRECATED("Use LZ4_createStream() instead") LZ4LIB_API void* LZ4_create (char* inputBuffer); -LZ4_DEPRECATED("Use LZ4_createStream() instead") LZ4LIB_API int LZ4_sizeofStreamState(void); -LZ4_DEPRECATED("Use LZ4_resetStream() instead") LZ4LIB_API int LZ4_resetStreamState(void* state, char* inputBuffer); -LZ4_DEPRECATED("Use LZ4_saveDict() instead") LZ4LIB_API char* LZ4_slideInputBuffer (void* state); - -/* Obsolete streaming decoding functions */ -LZ4_DEPRECATED("use LZ4_decompress_safe_usingDict() instead") LZ4LIB_API int LZ4_decompress_safe_withPrefix64k (const char* src, char* dst, int compressedSize, int maxDstSize); -LZ4_DEPRECATED("use LZ4_decompress_fast_usingDict() instead") LZ4LIB_API int LZ4_decompress_fast_withPrefix64k (const char* src, char* dst, int originalSize); - -#endif /* LZ4_H_2983827168210 */ - - -#if defined (__cplusplus) -} -#endif \ No newline at end of file diff --git a/lib/liblz4/liblz4.vcxproj b/lib/liblz4/liblz4.vcxproj deleted file mode 100644 index fc5c241..0000000 --- a/lib/liblz4/liblz4.vcxproj +++ /dev/null @@ -1,132 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 15.0 - {AB0C3362-63AB-480A-ADBC-2EF7D859778B} - 10.0.16299.0 - - - - StaticLibrary - true - v141 - MultiByte - - - StaticLibrary - false - v141 - true - MultiByte - - - StaticLibrary - true - v141 - MultiByte - - - StaticLibrary - false - v141 - true - MultiByte - - - - - - - - - - - - - - - - - - - - - - - Level3 - Disabled - true - true - ..\liblz4\include; - - - - - Level3 - Disabled - true - true - ..\liblz4\include; - - - - - Level3 - MaxSpeed - true - true - true - true - ..\liblz4\include; - - - true - true - - - - - Level3 - MaxSpeed - true - true - true - true - ..\liblz4\include; - - - true - true - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/lib/liblz4/liblz4.vcxproj.filters b/lib/liblz4/liblz4.vcxproj.filters deleted file mode 100644 index 20d2490..0000000 --- a/lib/liblz4/liblz4.vcxproj.filters +++ /dev/null @@ -1,30 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Header Files - - - - - Source Files - - - - - - \ No newline at end of file diff --git a/lib/liblz4/liblz4.vcxproj.user b/lib/liblz4/liblz4.vcxproj.user deleted file mode 100644 index be25078..0000000 --- a/lib/liblz4/liblz4.vcxproj.user +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/lib/liblz4/makefile b/lib/liblz4/makefile deleted file mode 100644 index ff57976..0000000 --- a/lib/liblz4/makefile +++ /dev/null @@ -1,45 +0,0 @@ -# Sources -SRC_DIR = source -OBJS = $(foreach dir,$(SRC_DIR),$(subst .cpp,.o,$(wildcard $(dir)/*.cpp))) $(foreach dir,$(SRC_DIR),$(subst .c,.o,$(wildcard $(dir)/*.c))) - -# External dependencies -DEPENDS = -LIB_DIR = .. -INCS = -I"include" $(foreach dep,$(DEPENDS), -I"$(LIB_DIR)/lib$(dep)/include") - -# Compiler Settings -CXXFLAGS = -std=c++11 $(INCS) -D__STDC_FORMAT_MACROS -Wall -Wno-unused-value -CFLAGS = -std=c11 $(INCS) -Wall -Wno-unused-value -ARFLAGS = cr -o -ifeq ($(OS),Windows_NT) - # Windows Only Flags/Libs - CC = x86_64-w64-mingw32-gcc - CXX = x86_64-w64-mingw32-g++ - CFLAGS += -Wno-unused-but-set-variable - CXXFLAGS += -Wno-unused-but-set-variable -else - UNAME = $(shell uname -s) - ifeq ($(UNAME), Darwin) - # MacOS Only Flags/Libs - CFLAGS += -arch x86_64 -Wno-unused-private-field - CXXFLAGS += -arch x86_64 -Wno-unused-private-field - ARFLAGS = rc - else - # *nix Only Flags/Libs - CFLAGS += -Wno-unused-but-set-variable - CXXFLAGS += -Wno-unused-but-set-variable - endif -endif - -# Output -OUTPUT = $(shell basename "$(CURDIR)").a - -main: build - -rebuild: clean build - -build: $(OBJS) - ar $(ARFLAGS) $(OUTPUT) $(OBJS) - -clean: - rm -rf $(OUTPUT) $(OBJS) \ No newline at end of file diff --git a/lib/liblz4/source/lz4.c b/lib/liblz4/source/lz4.c deleted file mode 100644 index 9db0e22..0000000 --- a/lib/liblz4/source/lz4.c +++ /dev/null @@ -1,1930 +0,0 @@ -/* - LZ4 - Fast LZ compression algorithm - Copyright (C) 2011-2017, Yann Collet. - - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - LZ4 homepage : http://www.lz4.org - - LZ4 source repository : https://github.com/lz4/lz4 -*/ - - -/*-************************************ -* Tuning parameters -**************************************/ -/* - * LZ4_HEAPMODE : - * Select how default compression functions will allocate memory for their hash table, - * in memory stack (0:default, fastest), or in memory heap (1:requires malloc()). - */ -#ifndef LZ4_HEAPMODE -# define LZ4_HEAPMODE 0 -#endif - -/* - * ACCELERATION_DEFAULT : - * Select "acceleration" for LZ4_compress_fast() when parameter value <= 0 - */ -#define ACCELERATION_DEFAULT 1 - - -/*-************************************ -* CPU Feature Detection -**************************************/ -/* LZ4_FORCE_MEMORY_ACCESS - * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable. - * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal. - * The below switch allow to select different access method for improved performance. - * Method 0 (default) : use `memcpy()`. Safe and portable. - * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable). - * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`. - * Method 2 : direct access. This method is portable but violate C standard. - * It can generate buggy code on targets which assembly generation depends on alignment. - * But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6) - * See https://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details. - * Prefer these methods in priority order (0 > 1 > 2) - */ -#ifndef LZ4_FORCE_MEMORY_ACCESS /* can be defined externally */ -# if defined(__GNUC__) && \ - ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) \ - || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) ) -# define LZ4_FORCE_MEMORY_ACCESS 2 -# elif (defined(__INTEL_COMPILER) && !defined(_WIN32)) || defined(__GNUC__) -# define LZ4_FORCE_MEMORY_ACCESS 1 -# endif -#endif - -/* - * LZ4_FORCE_SW_BITCOUNT - * Define this parameter if your target system or compiler does not support hardware bit count - */ -#if defined(_MSC_VER) && defined(_WIN32_WCE) /* Visual Studio for WinCE doesn't support Hardware bit count */ -# define LZ4_FORCE_SW_BITCOUNT -#endif - - - -/*-************************************ -* Dependency -**************************************/ -#define LZ4_STATIC_LINKING_ONLY -#define LZ4_DISABLE_DEPRECATE_WARNINGS /* due to LZ4_decompress_safe_withPrefix64k */ -#include "lz4.h" -/* see also "memory routines" below */ - - -/*-************************************ -* Compiler Options -**************************************/ -#ifdef _MSC_VER /* Visual Studio */ -# include -# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ -# pragma warning(disable : 4293) /* disable: C4293: too large shift (32-bits) */ -#endif /* _MSC_VER */ - -#ifndef LZ4_FORCE_INLINE -# ifdef _MSC_VER /* Visual Studio */ -# define LZ4_FORCE_INLINE static __forceinline -# else -# if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */ -# ifdef __GNUC__ -# define LZ4_FORCE_INLINE static inline __attribute__((always_inline)) -# else -# define LZ4_FORCE_INLINE static inline -# endif -# else -# define LZ4_FORCE_INLINE static -# endif /* __STDC_VERSION__ */ -# endif /* _MSC_VER */ -#endif /* LZ4_FORCE_INLINE */ - -/* LZ4_FORCE_O2_GCC_PPC64LE and LZ4_FORCE_O2_INLINE_GCC_PPC64LE - * Gcc on ppc64le generates an unrolled SIMDized loop for LZ4_wildCopy, - * together with a simple 8-byte copy loop as a fall-back path. - * However, this optimization hurts the decompression speed by >30%, - * because the execution does not go to the optimized loop - * for typical compressible data, and all of the preamble checks - * before going to the fall-back path become useless overhead. - * This optimization happens only with the -O3 flag, and -O2 generates - * a simple 8-byte copy loop. - * With gcc on ppc64le, all of the LZ4_decompress_* and LZ4_wildCopy - * functions are annotated with __attribute__((optimize("O2"))), - * and also LZ4_wildCopy is forcibly inlined, so that the O2 attribute - * of LZ4_wildCopy does not affect the compression speed. - */ -#if defined(__PPC64__) && defined(__LITTLE_ENDIAN__) && defined(__GNUC__) -# define LZ4_FORCE_O2_GCC_PPC64LE __attribute__((optimize("O2"))) -# define LZ4_FORCE_O2_INLINE_GCC_PPC64LE __attribute__((optimize("O2"))) LZ4_FORCE_INLINE -#else -# define LZ4_FORCE_O2_GCC_PPC64LE -# define LZ4_FORCE_O2_INLINE_GCC_PPC64LE static -#endif - -#if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__) -# define expect(expr,value) (__builtin_expect ((expr),(value)) ) -#else -# define expect(expr,value) (expr) -#endif - -#ifndef likely -#define likely(expr) expect((expr) != 0, 1) -#endif -#ifndef unlikely -#define unlikely(expr) expect((expr) != 0, 0) -#endif - - -/*-************************************ -* Memory routines -**************************************/ -#include /* malloc, calloc, free */ -#define ALLOC(s) malloc(s) -#define ALLOC_AND_ZERO(s) calloc(1,s) -#define FREEMEM(p) free(p) -#include /* memset, memcpy */ -#define MEM_INIT(p,v,s) memset((p),(v),(s)) - - -/*-************************************ -* Basic Types -**************************************/ -#if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) -# include - typedef uint8_t BYTE; - typedef uint16_t U16; - typedef uint32_t U32; - typedef int32_t S32; - typedef uint64_t U64; - typedef uintptr_t uptrval; -#else - typedef unsigned char BYTE; - typedef unsigned short U16; - typedef unsigned int U32; - typedef signed int S32; - typedef unsigned long long U64; - typedef size_t uptrval; /* generally true, except OpenVMS-64 */ -#endif - -#if defined(__x86_64__) - typedef U64 reg_t; /* 64-bits in x32 mode */ -#else - typedef size_t reg_t; /* 32-bits in x32 mode */ -#endif - -/*-************************************ -* Reading and writing into memory -**************************************/ -static unsigned LZ4_isLittleEndian(void) -{ - const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */ - return one.c[0]; -} - - -#if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2) -/* lie to the compiler about data alignment; use with caution */ - -static U16 LZ4_read16(const void* memPtr) { return *(const U16*) memPtr; } -static U32 LZ4_read32(const void* memPtr) { return *(const U32*) memPtr; } -static reg_t LZ4_read_ARCH(const void* memPtr) { return *(const reg_t*) memPtr; } - -static void LZ4_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; } -static void LZ4_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; } - -#elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==1) - -/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */ -/* currently only defined for gcc and icc */ -typedef union { U16 u16; U32 u32; reg_t uArch; } __attribute__((packed)) unalign; - -static U16 LZ4_read16(const void* ptr) { return ((const unalign*)ptr)->u16; } -static U32 LZ4_read32(const void* ptr) { return ((const unalign*)ptr)->u32; } -static reg_t LZ4_read_ARCH(const void* ptr) { return ((const unalign*)ptr)->uArch; } - -static void LZ4_write16(void* memPtr, U16 value) { ((unalign*)memPtr)->u16 = value; } -static void LZ4_write32(void* memPtr, U32 value) { ((unalign*)memPtr)->u32 = value; } - -#else /* safe and portable access through memcpy() */ - -static U16 LZ4_read16(const void* memPtr) -{ - U16 val; memcpy(&val, memPtr, sizeof(val)); return val; -} - -static U32 LZ4_read32(const void* memPtr) -{ - U32 val; memcpy(&val, memPtr, sizeof(val)); return val; -} - -static reg_t LZ4_read_ARCH(const void* memPtr) -{ - reg_t val; memcpy(&val, memPtr, sizeof(val)); return val; -} - -static void LZ4_write16(void* memPtr, U16 value) -{ - memcpy(memPtr, &value, sizeof(value)); -} - -static void LZ4_write32(void* memPtr, U32 value) -{ - memcpy(memPtr, &value, sizeof(value)); -} - -#endif /* LZ4_FORCE_MEMORY_ACCESS */ - - -static U16 LZ4_readLE16(const void* memPtr) -{ - if (LZ4_isLittleEndian()) { - return LZ4_read16(memPtr); - } else { - const BYTE* p = (const BYTE*)memPtr; - return (U16)((U16)p[0] + (p[1]<<8)); - } -} - -static void LZ4_writeLE16(void* memPtr, U16 value) -{ - if (LZ4_isLittleEndian()) { - LZ4_write16(memPtr, value); - } else { - BYTE* p = (BYTE*)memPtr; - p[0] = (BYTE) value; - p[1] = (BYTE)(value>>8); - } -} - -/* customized variant of memcpy, which can overwrite up to 8 bytes beyond dstEnd */ -LZ4_FORCE_O2_INLINE_GCC_PPC64LE -void LZ4_wildCopy(void* dstPtr, const void* srcPtr, void* dstEnd) -{ - BYTE* d = (BYTE*)dstPtr; - const BYTE* s = (const BYTE*)srcPtr; - BYTE* const e = (BYTE*)dstEnd; - - do { memcpy(d,s,8); d+=8; s+=8; } while (d=1) -# include -#else -# ifndef assert -# define assert(condition) ((void)0) -# endif -#endif - -#define LZ4_STATIC_ASSERT(c) { enum { LZ4_static_assert = 1/(int)(!!(c)) }; } /* use after variable declarations */ - -#if defined(LZ4_DEBUG) && (LZ4_DEBUG>=2) -# include -static int g_debuglog_enable = 1; -# define DEBUGLOG(l, ...) { \ - if ((g_debuglog_enable) && (l<=LZ4_DEBUG)) { \ - fprintf(stderr, __FILE__ ": "); \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stderr, " \n"); \ - } } -#else -# define DEBUGLOG(l, ...) {} /* disabled */ -#endif - - -/*-************************************ -* Common functions -**************************************/ -static unsigned LZ4_NbCommonBytes (reg_t val) -{ - if (LZ4_isLittleEndian()) { - if (sizeof(val)==8) { -# if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) - unsigned long r = 0; - _BitScanForward64( &r, (U64)val ); - return (int)(r>>3); -# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) - return (__builtin_ctzll((U64)val) >> 3); -# else - static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, - 0, 3, 1, 3, 1, 4, 2, 7, - 0, 2, 3, 6, 1, 5, 3, 5, - 1, 3, 4, 4, 2, 5, 6, 7, - 7, 0, 1, 2, 3, 3, 4, 6, - 2, 6, 5, 5, 3, 4, 5, 6, - 7, 1, 2, 4, 6, 4, 4, 5, - 7, 2, 6, 5, 7, 6, 7, 7 }; - return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58]; -# endif - } else /* 32 bits */ { -# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT) - unsigned long r; - _BitScanForward( &r, (U32)val ); - return (int)(r>>3); -# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) - return (__builtin_ctz((U32)val) >> 3); -# else - static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, - 3, 2, 2, 1, 3, 2, 0, 1, - 3, 3, 1, 2, 2, 2, 2, 0, - 3, 1, 2, 0, 1, 0, 1, 1 }; - return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27]; -# endif - } - } else /* Big Endian CPU */ { - if (sizeof(val)==8) { /* 64-bits */ -# if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) - unsigned long r = 0; - _BitScanReverse64( &r, val ); - return (unsigned)(r>>3); -# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) - return (__builtin_clzll((U64)val) >> 3); -# else - static const U32 by32 = sizeof(val)*4; /* 32 on 64 bits (goal), 16 on 32 bits. - Just to avoid some static analyzer complaining about shift by 32 on 32-bits target. - Note that this code path is never triggered in 32-bits mode. */ - unsigned r; - if (!(val>>by32)) { r=4; } else { r=0; val>>=by32; } - if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; } - r += (!val); - return r; -# endif - } else /* 32 bits */ { -# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT) - unsigned long r = 0; - _BitScanReverse( &r, (unsigned long)val ); - return (unsigned)(r>>3); -# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) - return (__builtin_clz((U32)val) >> 3); -# else - unsigned r; - if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; } - r += (!val); - return r; -# endif - } - } -} - -#define STEPSIZE sizeof(reg_t) -LZ4_FORCE_INLINE -unsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit) -{ - const BYTE* const pStart = pIn; - - if (likely(pIn < pInLimit-(STEPSIZE-1))) { - reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn); - if (!diff) { - pIn+=STEPSIZE; pMatch+=STEPSIZE; - } else { - return LZ4_NbCommonBytes(diff); - } } - - while (likely(pIn < pInLimit-(STEPSIZE-1))) { - reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn); - if (!diff) { pIn+=STEPSIZE; pMatch+=STEPSIZE; continue; } - pIn += LZ4_NbCommonBytes(diff); - return (unsigned)(pIn - pStart); - } - - if ((STEPSIZE==8) && (pIn<(pInLimit-3)) && (LZ4_read32(pMatch) == LZ4_read32(pIn))) { pIn+=4; pMatch+=4; } - if ((pIn<(pInLimit-1)) && (LZ4_read16(pMatch) == LZ4_read16(pIn))) { pIn+=2; pMatch+=2; } - if ((pIn compression run slower on incompressible data */ - - -/*-************************************ -* Local Structures and types -**************************************/ -typedef enum { notLimited = 0, limitedOutput = 1, fillOutput = 2 } limitedOutput_directive; -typedef enum { clearedTable = 0, byPtr, byU32, byU16 } tableType_t; - -/** - * This enum distinguishes several different modes of accessing previous - * content in the stream. - * - * - noDict : There is no preceding content. - * - withPrefix64k : Table entries up to ctx->dictSize before the current blob - * blob being compressed are valid and refer to the preceding - * content (of length ctx->dictSize), which is available - * contiguously preceding in memory the content currently - * being compressed. - * - usingExtDict : Like withPrefix64k, but the preceding content is somewhere - * else in memory, starting at ctx->dictionary with length - * ctx->dictSize. - * - usingDictCtx : Like usingExtDict, but everything concerning the preceding - * content is in a separate context, pointed to by - * ctx->dictCtx. ctx->dictionary, ctx->dictSize, and table - * entries in the current context that refer to positions - * preceding the beginning of the current compression are - * ignored. Instead, ctx->dictCtx->dictionary and ctx->dictCtx - * ->dictSize describe the location and size of the preceding - * content, and matches are found by looking in the ctx - * ->dictCtx->hashTable. - */ -typedef enum { noDict = 0, withPrefix64k, usingExtDict, usingDictCtx } dict_directive; -typedef enum { noDictIssue = 0, dictSmall } dictIssue_directive; - -typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive; -typedef enum { full = 0, partial = 1 } earlyEnd_directive; - - -/*-************************************ -* Local Utils -**************************************/ -int LZ4_versionNumber (void) { return LZ4_VERSION_NUMBER; } -const char* LZ4_versionString(void) { return LZ4_VERSION_STRING; } -int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); } -int LZ4_sizeofState() { return LZ4_STREAMSIZE; } - - -/*-************************************ -* Internal Definitions used in Tests -**************************************/ -#if defined (__cplusplus) -extern "C" { -#endif - -int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize); - -int LZ4_decompress_safe_forceExtDict(const char* in, char* out, int inSize, int outSize, const void* dict, size_t dictSize); - -#if defined (__cplusplus) -} -#endif - -/*-****************************** -* Compression functions -********************************/ -static U32 LZ4_hash4(U32 sequence, tableType_t const tableType) -{ - if (tableType == byU16) - return ((sequence * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1))); - else - return ((sequence * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG)); -} - -static U32 LZ4_hash5(U64 sequence, tableType_t const tableType) -{ - static const U64 prime5bytes = 889523592379ULL; - static const U64 prime8bytes = 11400714785074694791ULL; - const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG+1 : LZ4_HASHLOG; - if (LZ4_isLittleEndian()) - return (U32)(((sequence << 24) * prime5bytes) >> (64 - hashLog)); - else - return (U32)(((sequence >> 24) * prime8bytes) >> (64 - hashLog)); -} - -LZ4_FORCE_INLINE U32 LZ4_hashPosition(const void* const p, tableType_t const tableType) -{ - if ((sizeof(reg_t)==8) && (tableType != byU16)) return LZ4_hash5(LZ4_read_ARCH(p), tableType); - return LZ4_hash4(LZ4_read32(p), tableType); -} - -static void LZ4_putIndexOnHash(U32 idx, U32 h, void* tableBase, tableType_t const tableType) -{ - switch (tableType) - { - default: /* fallthrough */ - case clearedTable: /* fallthrough */ - case byPtr: { /* illegal! */ assert(0); return; } - case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = idx; return; } - case byU16: { U16* hashTable = (U16*) tableBase; assert(idx < 65536); hashTable[h] = (U16)idx; return; } - } -} - -static void LZ4_putPositionOnHash(const BYTE* p, U32 h, - void* tableBase, tableType_t const tableType, - const BYTE* srcBase) -{ - switch (tableType) - { - case clearedTable: { /* illegal! */ assert(0); return; } - case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = p; return; } - case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = (U32)(p-srcBase); return; } - case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = (U16)(p-srcBase); return; } - } -} - -LZ4_FORCE_INLINE void LZ4_putPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase) -{ - U32 const h = LZ4_hashPosition(p, tableType); - LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase); -} - -/* LZ4_getIndexOnHash() : - * Index of match position registered in hash table. - * hash position must be calculated by using base+index, or dictBase+index. - * Assumption 1 : only valid if tableType == byU32 or byU16. - * Assumption 2 : h is presumed valid (within limits of hash table) - */ -static U32 LZ4_getIndexOnHash(U32 h, const void* tableBase, tableType_t tableType) -{ - LZ4_STATIC_ASSERT(LZ4_MEMORY_USAGE > 2); - if (tableType == byU32) { - const U32* const hashTable = (const U32*) tableBase; - assert(h < (1U << (LZ4_MEMORY_USAGE-2))); - return hashTable[h]; - } - if (tableType == byU16) { - const U16* const hashTable = (const U16*) tableBase; - assert(h < (1U << (LZ4_MEMORY_USAGE-1))); - return hashTable[h]; - } - assert(0); return 0; /* forbidden case */ -} - -static const BYTE* LZ4_getPositionOnHash(U32 h, const void* tableBase, tableType_t tableType, const BYTE* srcBase) -{ - if (tableType == byPtr) { const BYTE* const* hashTable = (const BYTE* const*) tableBase; return hashTable[h]; } - if (tableType == byU32) { const U32* const hashTable = (const U32*) tableBase; return hashTable[h] + srcBase; } - { const U16* const hashTable = (const U16*) tableBase; return hashTable[h] + srcBase; } /* default, to ensure a return */ -} - -LZ4_FORCE_INLINE const BYTE* LZ4_getPosition(const BYTE* p, - const void* tableBase, tableType_t tableType, - const BYTE* srcBase) -{ - U32 const h = LZ4_hashPosition(p, tableType); - return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase); -} - -LZ4_FORCE_INLINE void LZ4_prepareTable( - LZ4_stream_t_internal* const cctx, - const int inputSize, - const tableType_t tableType) { - /* If the table hasn't been used, it's guaranteed to be zeroed out, and is - * therefore safe to use no matter what mode we're in. Otherwise, we figure - * out if it's safe to leave as is or whether it needs to be reset. - */ - if (cctx->tableType != clearedTable) { - if (cctx->tableType != tableType - || (tableType == byU16 && cctx->currentOffset + inputSize >= 0xFFFFU) - || (tableType == byU32 && cctx->currentOffset > 1 GB) - || tableType == byPtr - || inputSize >= 4 KB) - { - DEBUGLOG(4, "LZ4_prepareTable: Resetting table in %p", cctx); - MEM_INIT(cctx->hashTable, 0, LZ4_HASHTABLESIZE); - cctx->currentOffset = 0; - cctx->tableType = clearedTable; - } else { - DEBUGLOG(4, "LZ4_prepareTable: Re-use hash table (no reset)"); - } - } - - /* Adding a gap, so all previous entries are > MAX_DISTANCE back, is faster - * than compressing without a gap. However, compressing with - * currentOffset == 0 is faster still, so we preserve that case. - */ - if (cctx->currentOffset != 0 && tableType == byU32) { - DEBUGLOG(5, "LZ4_prepareTable: adding 64KB to currentOffset"); - cctx->currentOffset += 64 KB; - } - - /* Finally, clear history */ - cctx->dictCtx = NULL; - cctx->dictionary = NULL; - cctx->dictSize = 0; -} - -/** LZ4_compress_generic() : - inlined, to ensure branches are decided at compilation time */ -LZ4_FORCE_INLINE int LZ4_compress_generic( - LZ4_stream_t_internal* const cctx, - const char* const source, - char* const dest, - const int inputSize, - int *inputConsumed, /* only written when outputLimited == fillOutput */ - const int maxOutputSize, - const limitedOutput_directive outputLimited, - const tableType_t tableType, - const dict_directive dictDirective, - const dictIssue_directive dictIssue, - const U32 acceleration) -{ - const BYTE* ip = (const BYTE*) source; - - U32 const startIndex = cctx->currentOffset; - const BYTE* base = (const BYTE*) source - startIndex; - const BYTE* lowLimit; - - const LZ4_stream_t_internal* dictCtx = (const LZ4_stream_t_internal*) cctx->dictCtx; - const BYTE* const dictionary = - dictDirective == usingDictCtx ? dictCtx->dictionary : cctx->dictionary; - const U32 dictSize = - dictDirective == usingDictCtx ? dictCtx->dictSize : cctx->dictSize; - const U32 dictDelta = (dictDirective == usingDictCtx) ? startIndex - dictCtx->currentOffset : 0; /* make indexes in dictCtx comparable with index in current context */ - - int const maybe_extMem = (dictDirective == usingExtDict) || (dictDirective == usingDictCtx); - U32 const prefixIdxLimit = startIndex - dictSize; /* used when dictDirective == dictSmall */ - const BYTE* const dictEnd = dictionary + dictSize; - const BYTE* anchor = (const BYTE*) source; - const BYTE* const iend = ip + inputSize; - const BYTE* const mflimitPlusOne = iend - MFLIMIT + 1; - const BYTE* const matchlimit = iend - LASTLITERALS; - - /* the dictCtx currentOffset is indexed on the start of the dictionary, - * while a dictionary in the current context precedes the currentOffset */ - const BYTE* dictBase = dictDirective == usingDictCtx ? - dictionary + dictSize - dictCtx->currentOffset : - dictionary + dictSize - startIndex; - - BYTE* op = (BYTE*) dest; - BYTE* const olimit = op + maxOutputSize; - - U32 offset = 0; - U32 forwardH; - - DEBUGLOG(5, "LZ4_compress_generic: srcSize=%i, tableType=%u", inputSize, tableType); - /* Init conditions */ - if (outputLimited == fillOutput && maxOutputSize < 1) return 0; /* Impossible to store anything */ - if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported inputSize, too large (or negative) */ - if ((tableType == byU16) && (inputSize>=LZ4_64Klimit)) return 0; /* Size too large (not within 64K limit) */ - if (tableType==byPtr) assert(dictDirective==noDict); /* only supported use case with byPtr */ - assert(acceleration >= 1); - - lowLimit = (const BYTE*)source - (dictDirective == withPrefix64k ? dictSize : 0); - - /* Update context state */ - if (dictDirective == usingDictCtx) { - /* Subsequent linked blocks can't use the dictionary. */ - /* Instead, they use the block we just compressed. */ - cctx->dictCtx = NULL; - cctx->dictSize = (U32)inputSize; - } else { - cctx->dictSize += (U32)inputSize; - } - cctx->currentOffset += (U32)inputSize; - cctx->tableType = (U16)tableType; - - if (inputSizehashTable, tableType, base); - ip++; forwardH = LZ4_hashPosition(ip, tableType); - - /* Main Loop */ - for ( ; ; ) { - const BYTE* match; - BYTE* token; - - /* Find a match */ - if (tableType == byPtr) { - const BYTE* forwardIp = ip; - unsigned step = 1; - unsigned searchMatchNb = acceleration << LZ4_skipTrigger; - do { - U32 const h = forwardH; - ip = forwardIp; - forwardIp += step; - step = (searchMatchNb++ >> LZ4_skipTrigger); - - if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals; - assert(ip < mflimitPlusOne); - - match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType, base); - forwardH = LZ4_hashPosition(forwardIp, tableType); - LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType, base); - - } while ( (match+MAX_DISTANCE < ip) - || (LZ4_read32(match) != LZ4_read32(ip)) ); - - } else { /* byU32, byU16 */ - - const BYTE* forwardIp = ip; - unsigned step = 1; - unsigned searchMatchNb = acceleration << LZ4_skipTrigger; - do { - U32 const h = forwardH; - U32 const current = (U32)(forwardIp - base); - U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType); - assert(matchIndex <= current); - assert(forwardIp - base < (ptrdiff_t)(2 GB - 1)); - ip = forwardIp; - forwardIp += step; - step = (searchMatchNb++ >> LZ4_skipTrigger); - - if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals; - assert(ip < mflimitPlusOne); - - if (dictDirective == usingDictCtx) { - if (matchIndex < startIndex) { - /* there was no match, try the dictionary */ - assert(tableType == byU32); - matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32); - match = dictBase + matchIndex; - matchIndex += dictDelta; /* make dictCtx index comparable with current context */ - lowLimit = dictionary; - } else { - match = base + matchIndex; - lowLimit = (const BYTE*)source; - } - } else if (dictDirective==usingExtDict) { - if (matchIndex < startIndex) { - DEBUGLOG(7, "extDict candidate: matchIndex=%5u < startIndex=%5u", matchIndex, startIndex); - assert(startIndex - matchIndex >= MINMATCH); - match = dictBase + matchIndex; - lowLimit = dictionary; - } else { - match = base + matchIndex; - lowLimit = (const BYTE*)source; - } - } else { /* single continuous memory segment */ - match = base + matchIndex; - } - forwardH = LZ4_hashPosition(forwardIp, tableType); - LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType); - - if ((dictIssue == dictSmall) && (matchIndex < prefixIdxLimit)) continue; /* match outside of valid area */ - assert(matchIndex < current); - if ((tableType != byU16) && (matchIndex+MAX_DISTANCE < current)) continue; /* too far */ - if (tableType == byU16) assert((current - matchIndex) <= MAX_DISTANCE); /* too_far presumed impossible with byU16 */ - - if (LZ4_read32(match) == LZ4_read32(ip)) { - if (maybe_extMem) offset = current - matchIndex; - break; /* match found */ - } - - } while(1); - } - - /* Catch up */ - while (((ip>anchor) & (match > lowLimit)) && (unlikely(ip[-1]==match[-1]))) { ip--; match--; } - - /* Encode Literals */ - { unsigned const litLength = (unsigned)(ip - anchor); - token = op++; - if ((outputLimited == limitedOutput) && /* Check output buffer overflow */ - (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength/255) > olimit))) - return 0; - if ((outputLimited == fillOutput) && - (unlikely(op + (litLength+240)/255 /* litlen */ + litLength /* literals */ + 2 /* offset */ + 1 /* token */ + MFLIMIT - MINMATCH /* min last literals so last match is <= end - MFLIMIT */ > olimit))) { - op--; - goto _last_literals; - } - if (litLength >= RUN_MASK) { - int len = (int)litLength-RUN_MASK; - *token = (RUN_MASK<= 255 ; len-=255) *op++ = 255; - *op++ = (BYTE)len; - } - else *token = (BYTE)(litLength< olimit)) { - /* the match was too close to the end, rewind and go to last literals */ - op = token; - goto _last_literals; - } - - /* Encode Offset */ - if (maybe_extMem) { /* static test */ - DEBUGLOG(6, " with offset=%u (ext if > %i)", offset, (int)(ip - (const BYTE*)source)); - assert(offset <= MAX_DISTANCE && offset > 0); - LZ4_writeLE16(op, (U16)offset); op+=2; - } else { - DEBUGLOG(6, " with offset=%u (same segment)", (U32)(ip - match)); - assert(ip-match <= MAX_DISTANCE); - LZ4_writeLE16(op, (U16)(ip - match)); op+=2; - } - - /* Encode MatchLength */ - { unsigned matchCode; - - if ( (dictDirective==usingExtDict || dictDirective==usingDictCtx) - && (lowLimit==dictionary) /* match within extDict */ ) { - const BYTE* limit = ip + (dictEnd-match); - assert(dictEnd > match); - if (limit > matchlimit) limit = matchlimit; - matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, limit); - ip += MINMATCH + matchCode; - if (ip==limit) { - unsigned const more = LZ4_count(limit, (const BYTE*)source, matchlimit); - matchCode += more; - ip += more; - } - DEBUGLOG(6, " with matchLength=%u starting in extDict", matchCode+MINMATCH); - } else { - matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit); - ip += MINMATCH + matchCode; - DEBUGLOG(6, " with matchLength=%u", matchCode+MINMATCH); - } - - if ((outputLimited) && /* Check output buffer overflow */ - (unlikely(op + (1 + LASTLITERALS) + (matchCode>>8) > olimit)) ) { - if (outputLimited == limitedOutput) - return 0; - if (outputLimited == fillOutput) { - /* Match description too long : reduce it */ - U32 newMatchCode = 15 /* in token */ - 1 /* to avoid needing a zero byte */ + ((U32)(olimit - op) - 2 - 1 - LASTLITERALS) * 255; - ip -= matchCode - newMatchCode; - matchCode = newMatchCode; - } - } - if (matchCode >= ML_MASK) { - *token += ML_MASK; - matchCode -= ML_MASK; - LZ4_write32(op, 0xFFFFFFFF); - while (matchCode >= 4*255) { - op+=4; - LZ4_write32(op, 0xFFFFFFFF); - matchCode -= 4*255; - } - op += matchCode / 255; - *op++ = (BYTE)(matchCode % 255); - } else - *token += (BYTE)(matchCode); - } - - anchor = ip; - - /* Test end of chunk */ - if (ip >= mflimitPlusOne) break; - - /* Fill table */ - LZ4_putPosition(ip-2, cctx->hashTable, tableType, base); - - /* Test next position */ - if (tableType == byPtr) { - - match = LZ4_getPosition(ip, cctx->hashTable, tableType, base); - LZ4_putPosition(ip, cctx->hashTable, tableType, base); - if ( (match+MAX_DISTANCE >= ip) - && (LZ4_read32(match) == LZ4_read32(ip)) ) - { token=op++; *token=0; goto _next_match; } - - } else { /* byU32, byU16 */ - - U32 const h = LZ4_hashPosition(ip, tableType); - U32 const current = (U32)(ip-base); - U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType); - assert(matchIndex < current); - if (dictDirective == usingDictCtx) { - if (matchIndex < startIndex) { - /* there was no match, try the dictionary */ - matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32); - match = dictBase + matchIndex; - lowLimit = dictionary; /* required for match length counter */ - matchIndex += dictDelta; - } else { - match = base + matchIndex; - lowLimit = (const BYTE*)source; /* required for match length counter */ - } - } else if (dictDirective==usingExtDict) { - if (matchIndex < startIndex) { - match = dictBase + matchIndex; - lowLimit = dictionary; /* required for match length counter */ - } else { - match = base + matchIndex; - lowLimit = (const BYTE*)source; /* required for match length counter */ - } - } else { /* single memory segment */ - match = base + matchIndex; - } - LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType); - assert(matchIndex < current); - if ( ((dictIssue==dictSmall) ? (matchIndex >= prefixIdxLimit) : 1) - && ((tableType==byU16) ? 1 : (matchIndex+MAX_DISTANCE >= current)) - && (LZ4_read32(match) == LZ4_read32(ip)) ) { - token=op++; - *token=0; - if (maybe_extMem) offset = current - matchIndex; - DEBUGLOG(6, "seq.start:%i, literals=%u, match.start:%i", - (int)(anchor-(const BYTE*)source), 0, (int)(ip-(const BYTE*)source)); - goto _next_match; - } - } - - /* Prepare next loop */ - forwardH = LZ4_hashPosition(++ip, tableType); - - } - -_last_literals: - /* Encode Last Literals */ - { size_t lastRun = (size_t)(iend - anchor); - if ( (outputLimited) && /* Check output buffer overflow */ - (op + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > olimit)) { - if (outputLimited == fillOutput) { - /* adapt lastRun to fill 'dst' */ - lastRun = (olimit-op) - 1; - lastRun -= (lastRun+240)/255; - } - if (outputLimited == limitedOutput) - return 0; - } - if (lastRun >= RUN_MASK) { - size_t accumulator = lastRun - RUN_MASK; - *op++ = RUN_MASK << ML_BITS; - for(; accumulator >= 255 ; accumulator-=255) *op++ = 255; - *op++ = (BYTE) accumulator; - } else { - *op++ = (BYTE)(lastRun<internal_donotuse; - if (acceleration < 1) acceleration = ACCELERATION_DEFAULT; - LZ4_resetStream((LZ4_stream_t*)state); - if (maxOutputSize >= LZ4_compressBound(inputSize)) { - if (inputSize < LZ4_64Klimit) { - return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, byU16, noDict, noDictIssue, acceleration); - } else { - const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > MAX_DISTANCE)) ? byPtr : byU32; - return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration); - } - } else { - if (inputSize < LZ4_64Klimit) {; - return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration); - } else { - const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > MAX_DISTANCE)) ? byPtr : byU32; - return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, noDict, noDictIssue, acceleration); - } - } -} - -/** - * LZ4_compress_fast_extState_fastReset() : - * A variant of LZ4_compress_fast_extState(). - * - * Using this variant avoids an expensive initialization step. It is only safe - * to call if the state buffer is known to be correctly initialized already - * (see comment in lz4.h on LZ4_resetStream_fast() for a definition of - * "correctly initialized"). - */ -int LZ4_compress_fast_extState_fastReset(void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration) -{ - LZ4_stream_t_internal* ctx = &((LZ4_stream_t*)state)->internal_donotuse; - if (acceleration < 1) acceleration = ACCELERATION_DEFAULT; - - if (dstCapacity >= LZ4_compressBound(srcSize)) { - if (srcSize < LZ4_64Klimit) { - const tableType_t tableType = byU16; - LZ4_prepareTable(ctx, srcSize, tableType); - if (ctx->currentOffset) { - return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, dictSmall, acceleration); - } else { - return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration); - } - } else { - const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)src > MAX_DISTANCE)) ? byPtr : byU32; - LZ4_prepareTable(ctx, srcSize, tableType); - return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration); - } - } else { - if (srcSize < LZ4_64Klimit) { - const tableType_t tableType = byU16; - LZ4_prepareTable(ctx, srcSize, tableType); - if (ctx->currentOffset) { - return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, dictSmall, acceleration); - } else { - return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration); - } - } else { - const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)src > MAX_DISTANCE)) ? byPtr : byU32; - LZ4_prepareTable(ctx, srcSize, tableType); - return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration); - } - } -} - - -int LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) -{ - int result; -#if (LZ4_HEAPMODE) - LZ4_stream_t* ctxPtr = ALLOC(sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */ - if (ctxPtr == NULL) return 0; -#else - LZ4_stream_t ctx; - LZ4_stream_t* const ctxPtr = &ctx; -#endif - result = LZ4_compress_fast_extState(ctxPtr, source, dest, inputSize, maxOutputSize, acceleration); - -#if (LZ4_HEAPMODE) - FREEMEM(ctxPtr); -#endif - return result; -} - - -int LZ4_compress_default(const char* source, char* dest, int inputSize, int maxOutputSize) -{ - return LZ4_compress_fast(source, dest, inputSize, maxOutputSize, 1); -} - - -/* hidden debug function */ -/* strangely enough, gcc generates faster code when this function is uncommented, even if unused */ -int LZ4_compress_fast_force(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) -{ - LZ4_stream_t ctx; - LZ4_resetStream(&ctx); - - if (inputSize < LZ4_64Klimit) - return LZ4_compress_generic(&ctx.internal_donotuse, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration); - else - return LZ4_compress_generic(&ctx.internal_donotuse, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, sizeof(void*)==8 ? byU32 : byPtr, noDict, noDictIssue, acceleration); -} - - -/* Note!: This function leaves the stream in an unclean/broken state! - * It is not safe to subsequently use the same state with a _fastReset() or - * _continue() call without resetting it. */ -static int LZ4_compress_destSize_extState (LZ4_stream_t* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize) -{ - LZ4_resetStream(state); - - if (targetDstSize >= LZ4_compressBound(*srcSizePtr)) { /* compression success is guaranteed */ - return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, targetDstSize, 1); - } else { - if (*srcSizePtr < LZ4_64Klimit) { - return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, byU16, noDict, noDictIssue, 1); - } else { - tableType_t const tableType = ((sizeof(void*)==4) && ((uptrval)src > MAX_DISTANCE)) ? byPtr : byU32; - return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, tableType, noDict, noDictIssue, 1); - } } -} - - -int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targetDstSize) -{ -#if (LZ4_HEAPMODE) - LZ4_stream_t* ctx = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */ - if (ctx == NULL) return 0; -#else - LZ4_stream_t ctxBody; - LZ4_stream_t* ctx = &ctxBody; -#endif - - int result = LZ4_compress_destSize_extState(ctx, src, dst, srcSizePtr, targetDstSize); - -#if (LZ4_HEAPMODE) - FREEMEM(ctx); -#endif - return result; -} - - - -/*-****************************** -* Streaming functions -********************************/ - -LZ4_stream_t* LZ4_createStream(void) -{ - LZ4_stream_t* lz4s = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t)); - LZ4_STATIC_ASSERT(LZ4_STREAMSIZE >= sizeof(LZ4_stream_t_internal)); /* A compilation error here means LZ4_STREAMSIZE is not large enough */ - DEBUGLOG(4, "LZ4_createStream %p", lz4s); - if (lz4s == NULL) return NULL; - LZ4_resetStream(lz4s); - return lz4s; -} - -void LZ4_resetStream (LZ4_stream_t* LZ4_stream) -{ - DEBUGLOG(5, "LZ4_resetStream (ctx:%p)", LZ4_stream); - MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t)); -} - -void LZ4_resetStream_fast(LZ4_stream_t* ctx) { - LZ4_prepareTable(&(ctx->internal_donotuse), 0, byU32); -} - -int LZ4_freeStream (LZ4_stream_t* LZ4_stream) -{ - if (!LZ4_stream) return 0; /* support free on NULL */ - DEBUGLOG(5, "LZ4_freeStream %p", LZ4_stream); - FREEMEM(LZ4_stream); - return (0); -} - - -#define HASH_UNIT sizeof(reg_t) -int LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize) -{ - LZ4_stream_t_internal* dict = &LZ4_dict->internal_donotuse; - const tableType_t tableType = byU32; - const BYTE* p = (const BYTE*)dictionary; - const BYTE* const dictEnd = p + dictSize; - const BYTE* base; - - DEBUGLOG(4, "LZ4_loadDict (%i bytes from %p into %p)", dictSize, dictionary, LZ4_dict); - - /* It's necessary to reset the context, - * and not just continue it with prepareTable() - * to avoid any risk of generating overflowing matchIndex - * when compressing using this dictionary */ - LZ4_resetStream(LZ4_dict); - - /* We always increment the offset by 64 KB, since, if the dict is longer, - * we truncate it to the last 64k, and if it's shorter, we still want to - * advance by a whole window length so we can provide the guarantee that - * there are only valid offsets in the window, which allows an optimization - * in LZ4_compress_fast_continue() where it uses noDictIssue even when the - * dictionary isn't a full 64k. */ - - if ((dictEnd - p) > 64 KB) p = dictEnd - 64 KB; - base = dictEnd - 64 KB - dict->currentOffset; - dict->dictionary = p; - dict->dictSize = (U32)(dictEnd - p); - dict->currentOffset += 64 KB; - dict->tableType = tableType; - - if (dictSize < (int)HASH_UNIT) { - return 0; - } - - while (p <= dictEnd-HASH_UNIT) { - LZ4_putPosition(p, dict->hashTable, tableType, base); - p+=3; - } - - return dict->dictSize; -} - -void LZ4_attach_dictionary(LZ4_stream_t *working_stream, const LZ4_stream_t *dictionary_stream) { - if (dictionary_stream != NULL) { - /* If the current offset is zero, we will never look in the - * external dictionary context, since there is no value a table - * entry can take that indicate a miss. In that case, we need - * to bump the offset to something non-zero. - */ - if (working_stream->internal_donotuse.currentOffset == 0) { - working_stream->internal_donotuse.currentOffset = 64 KB; - } - working_stream->internal_donotuse.dictCtx = &(dictionary_stream->internal_donotuse); - } else { - working_stream->internal_donotuse.dictCtx = NULL; - } -} - - -static void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, int nextSize) -{ - if (LZ4_dict->currentOffset + nextSize > 0x80000000) { /* potential ptrdiff_t overflow (32-bits mode) */ - /* rescale hash table */ - U32 const delta = LZ4_dict->currentOffset - 64 KB; - const BYTE* dictEnd = LZ4_dict->dictionary + LZ4_dict->dictSize; - int i; - DEBUGLOG(4, "LZ4_renormDictT"); - for (i=0; ihashTable[i] < delta) LZ4_dict->hashTable[i]=0; - else LZ4_dict->hashTable[i] -= delta; - } - LZ4_dict->currentOffset = 64 KB; - if (LZ4_dict->dictSize > 64 KB) LZ4_dict->dictSize = 64 KB; - LZ4_dict->dictionary = dictEnd - LZ4_dict->dictSize; - } -} - - -int LZ4_compress_fast_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) -{ - const tableType_t tableType = byU32; - LZ4_stream_t_internal* streamPtr = &LZ4_stream->internal_donotuse; - const BYTE* dictEnd = streamPtr->dictionary + streamPtr->dictSize; - - DEBUGLOG(5, "LZ4_compress_fast_continue (inputSize=%i)", inputSize); - - if (streamPtr->initCheck) return 0; /* Uninitialized structure detected */ - LZ4_renormDictT(streamPtr, inputSize); /* avoid index overflow */ - if (acceleration < 1) acceleration = ACCELERATION_DEFAULT; - - /* invalidate tiny dictionaries */ - if ( (streamPtr->dictSize-1 < 4) /* intentional underflow */ - && (dictEnd != (const BYTE*)source) ) { - DEBUGLOG(5, "LZ4_compress_fast_continue: dictSize(%u) at addr:%p is too small", streamPtr->dictSize, streamPtr->dictionary); - streamPtr->dictSize = 0; - streamPtr->dictionary = (const BYTE*)source; - dictEnd = (const BYTE*)source; - } - - /* Check overlapping input/dictionary space */ - { const BYTE* sourceEnd = (const BYTE*) source + inputSize; - if ((sourceEnd > streamPtr->dictionary) && (sourceEnd < dictEnd)) { - streamPtr->dictSize = (U32)(dictEnd - sourceEnd); - if (streamPtr->dictSize > 64 KB) streamPtr->dictSize = 64 KB; - if (streamPtr->dictSize < 4) streamPtr->dictSize = 0; - streamPtr->dictionary = dictEnd - streamPtr->dictSize; - } - } - - /* prefix mode : source data follows dictionary */ - if (dictEnd == (const BYTE*)source) { - if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) - return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, dictSmall, acceleration); - else - return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, noDictIssue, acceleration); - } - - /* external dictionary mode */ - { int result; - if (streamPtr->dictCtx) { - /* We depend here on the fact that dictCtx'es (produced by - * LZ4_loadDict) guarantee that their tables contain no references - * to offsets between dictCtx->currentOffset - 64 KB and - * dictCtx->currentOffset - dictCtx->dictSize. This makes it safe - * to use noDictIssue even when the dict isn't a full 64 KB. - */ - if (inputSize > 4 KB) { - /* For compressing large blobs, it is faster to pay the setup - * cost to copy the dictionary's tables into the active context, - * so that the compression loop is only looking into one table. - */ - memcpy(streamPtr, streamPtr->dictCtx, sizeof(LZ4_stream_t)); - result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration); - } else { - result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingDictCtx, noDictIssue, acceleration); - } - } else { - if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) { - result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, dictSmall, acceleration); - } else { - result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration); - } - } - streamPtr->dictionary = (const BYTE*)source; - streamPtr->dictSize = (U32)inputSize; - return result; - } -} - - -/* Hidden debug function, to force-test external dictionary mode */ -int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int srcSize) -{ - LZ4_stream_t_internal* streamPtr = &LZ4_dict->internal_donotuse; - int result; - - LZ4_renormDictT(streamPtr, srcSize); - - if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) { - result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, dictSmall, 1); - } else { - result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, noDictIssue, 1); - } - - streamPtr->dictionary = (const BYTE*)source; - streamPtr->dictSize = (U32)srcSize; - - return result; -} - - -/*! LZ4_saveDict() : - * If previously compressed data block is not guaranteed to remain available at its memory location, - * save it into a safer place (char* safeBuffer). - * Note : you don't need to call LZ4_loadDict() afterwards, - * dictionary is immediately usable, you can therefore call LZ4_compress_fast_continue(). - * Return : saved dictionary size in bytes (necessarily <= dictSize), or 0 if error. - */ -int LZ4_saveDict (LZ4_stream_t* LZ4_dict, char* safeBuffer, int dictSize) -{ - LZ4_stream_t_internal* const dict = &LZ4_dict->internal_donotuse; - const BYTE* const previousDictEnd = dict->dictionary + dict->dictSize; - - if ((U32)dictSize > 64 KB) dictSize = 64 KB; /* useless to define a dictionary > 64 KB */ - if ((U32)dictSize > dict->dictSize) dictSize = dict->dictSize; - - memmove(safeBuffer, previousDictEnd - dictSize, dictSize); - - dict->dictionary = (const BYTE*)safeBuffer; - dict->dictSize = (U32)dictSize; - - return dictSize; -} - - - -/*-***************************** -* Decompression functions -*******************************/ -/*! LZ4_decompress_generic() : - * This generic decompression function covers all use cases. - * It shall be instantiated several times, using different sets of directives. - * Note that it is important for performance that this function really get inlined, - * in order to remove useless branches during compilation optimization. - */ -LZ4_FORCE_O2_GCC_PPC64LE -LZ4_FORCE_INLINE int LZ4_decompress_generic( - const char* const src, - char* const dst, - int srcSize, - int outputSize, /* If endOnInput==endOnInputSize, this value is `dstCapacity` */ - - int endOnInput, /* endOnOutputSize, endOnInputSize */ - int partialDecoding, /* full, partial */ - int targetOutputSize, /* only used if partialDecoding==partial */ - int dict, /* noDict, withPrefix64k, usingExtDict */ - const BYTE* const lowPrefix, /* always <= dst, == dst when no prefix */ - const BYTE* const dictStart, /* only if dict==usingExtDict */ - const size_t dictSize /* note : = 0 if noDict */ - ) -{ - const BYTE* ip = (const BYTE*) src; - const BYTE* const iend = ip + srcSize; - - BYTE* op = (BYTE*) dst; - BYTE* const oend = op + outputSize; - BYTE* cpy; - BYTE* oexit = op + targetOutputSize; - - const BYTE* const dictEnd = (const BYTE*)dictStart + dictSize; - const unsigned inc32table[8] = {0, 1, 2, 1, 0, 4, 4, 4}; - const int dec64table[8] = {0, 0, 0, -1, -4, 1, 2, 3}; - - const int safeDecode = (endOnInput==endOnInputSize); - const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB))); - - /* Set up the "end" pointers for the shortcut. */ - const BYTE* const shortiend = iend - (endOnInput ? 14 : 8) /*maxLL*/ - 2 /*offset*/; - const BYTE* const shortoend = oend - (endOnInput ? 14 : 8) /*maxLL*/ - 18 /*maxML*/; - - DEBUGLOG(5, "LZ4_decompress_generic (srcSize:%i)", srcSize); - - /* Special cases */ - if ((partialDecoding) && (oexit > oend-MFLIMIT)) oexit = oend-MFLIMIT; /* targetOutputSize too high => just decode everything */ - if ((endOnInput) && (unlikely(outputSize==0))) return ((srcSize==1) && (*ip==0)) ? 0 : -1; /* Empty output buffer */ - if ((!endOnInput) && (unlikely(outputSize==0))) return (*ip==0?1:-1); - if ((endOnInput) && unlikely(srcSize==0)) return -1; - - /* Main Loop : decode sequences */ - while (1) { - const BYTE* match; - size_t offset; - - unsigned const token = *ip++; - size_t length = token >> ML_BITS; /* literal length */ - - assert(!endOnInput || ip <= iend); /* ip < iend before the increment */ - - /* A two-stage shortcut for the most common case: - * 1) If the literal length is 0..14, and there is enough space, - * enter the shortcut and copy 16 bytes on behalf of the literals - * (in the fast mode, only 8 bytes can be safely copied this way). - * 2) Further if the match length is 4..18, copy 18 bytes in a similar - * manner; but we ensure that there's enough space in the output for - * those 18 bytes earlier, upon entering the shortcut (in other words, - * there is a combined check for both stages). - */ - if ( (endOnInput ? length != RUN_MASK : length <= 8) - /* strictly "less than" on input, to re-enter the loop with at least one byte */ - && likely((endOnInput ? ip < shortiend : 1) & (op <= shortoend)) ) { - /* Copy the literals */ - memcpy(op, ip, endOnInput ? 16 : 8); - op += length; ip += length; - - /* The second stage: prepare for match copying, decode full info. - * If it doesn't work out, the info won't be wasted. */ - length = token & ML_MASK; /* match length */ - offset = LZ4_readLE16(ip); ip += 2; - match = op - offset; - - /* Do not deal with overlapping matches. */ - if ( (length != ML_MASK) - && (offset >= 8) - && (dict==withPrefix64k || match >= lowPrefix) ) { - /* Copy the match. */ - memcpy(op + 0, match + 0, 8); - memcpy(op + 8, match + 8, 8); - memcpy(op +16, match +16, 2); - op += length + MINMATCH; - /* Both stages worked, load the next token. */ - continue; - } - - /* The second stage didn't work out, but the info is ready. - * Propel it right to the point of match copying. */ - goto _copy_match; - } - - /* decode literal length */ - if (length == RUN_MASK) { - unsigned s; - if (unlikely(endOnInput ? ip >= iend-RUN_MASK : 0)) goto _output_error; /* overflow detection */ - do { - s = *ip++; - length += s; - } while ( likely(endOnInput ? ip(partialDecoding?oexit:oend-MFLIMIT)) || (ip+length>iend-(2+1+LASTLITERALS))) ) - || ((!endOnInput) && (cpy>oend-WILDCOPYLENGTH)) ) - { - if (partialDecoding) { - if (cpy > oend) goto _output_error; /* Error : write attempt beyond end of output buffer */ - if ((endOnInput) && (ip+length > iend)) goto _output_error; /* Error : read attempt beyond end of input buffer */ - } else { - if ((!endOnInput) && (cpy != oend)) goto _output_error; /* Error : block decoding must stop exactly there */ - if ((endOnInput) && ((ip+length != iend) || (cpy > oend))) goto _output_error; /* Error : input must be consumed */ - } - memcpy(op, ip, length); - ip += length; - op += length; - break; /* Necessarily EOF, due to parsing restrictions */ - } - LZ4_wildCopy(op, ip, cpy); - ip += length; op = cpy; - - /* get offset */ - offset = LZ4_readLE16(ip); ip+=2; - match = op - offset; - - /* get matchlength */ - length = token & ML_MASK; - -_copy_match: - if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) goto _output_error; /* Error : offset outside buffers */ - LZ4_write32(op, (U32)offset); /* costs ~1%; silence an msan warning when offset==0 */ - - if (length == ML_MASK) { - unsigned s; - do { - s = *ip++; - if ((endOnInput) && (ip > iend-LASTLITERALS)) goto _output_error; - length += s; - } while (s==255); - if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) goto _output_error; /* overflow detection */ - } - length += MINMATCH; - - /* check external dictionary */ - if ((dict==usingExtDict) && (match < lowPrefix)) { - if (unlikely(op+length > oend-LASTLITERALS)) goto _output_error; /* doesn't respect parsing restriction */ - - if (length <= (size_t)(lowPrefix-match)) { - /* match can be copied as a single segment from external dictionary */ - memmove(op, dictEnd - (lowPrefix-match), length); - op += length; - } else { - /* match encompass external dictionary and current block */ - size_t const copySize = (size_t)(lowPrefix-match); - size_t const restSize = length - copySize; - memcpy(op, dictEnd - copySize, copySize); - op += copySize; - if (restSize > (size_t)(op-lowPrefix)) { /* overlap copy */ - BYTE* const endOfMatch = op + restSize; - const BYTE* copyFrom = lowPrefix; - while (op < endOfMatch) *op++ = *copyFrom++; - } else { - memcpy(op, lowPrefix, restSize); - op += restSize; - } } - continue; - } - - /* copy match within block */ - cpy = op + length; - if (unlikely(offset<8)) { - op[0] = match[0]; - op[1] = match[1]; - op[2] = match[2]; - op[3] = match[3]; - match += inc32table[offset]; - memcpy(op+4, match, 4); - match -= dec64table[offset]; - } else { memcpy(op, match, 8); match+=8; } - op += 8; - - if (unlikely(cpy>oend-12)) { - BYTE* const oCopyLimit = oend-(WILDCOPYLENGTH-1); - if (cpy > oend-LASTLITERALS) goto _output_error; /* Error : last LASTLITERALS bytes must be literals (uncompressed) */ - if (op < oCopyLimit) { - LZ4_wildCopy(op, match, oCopyLimit); - match += oCopyLimit - op; - op = oCopyLimit; - } - while (op16) LZ4_wildCopy(op+8, match+8, cpy); - } - op = cpy; /* correction */ - } - - /* end of decoding */ - if (endOnInput) - return (int) (((char*)op)-dst); /* Nb of output bytes decoded */ - else - return (int) (((const char*)ip)-src); /* Nb of input bytes read */ - - /* Overflow error detected */ -_output_error: - return (int) (-(((const char*)ip)-src))-1; -} - - -/*===== Instantiate the API decoding functions. =====*/ - -LZ4_FORCE_O2_GCC_PPC64LE -int LZ4_decompress_safe(const char* source, char* dest, int compressedSize, int maxDecompressedSize) -{ - return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize, - endOnInputSize, full, 0, noDict, - (BYTE*)dest, NULL, 0); -} - -LZ4_FORCE_O2_GCC_PPC64LE -int LZ4_decompress_safe_partial(const char* source, char* dest, int compressedSize, int targetOutputSize, int maxDecompressedSize) -{ - return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize, - endOnInputSize, partial, targetOutputSize, - noDict, (BYTE*)dest, NULL, 0); -} - -LZ4_FORCE_O2_GCC_PPC64LE -int LZ4_decompress_fast(const char* source, char* dest, int originalSize) -{ - return LZ4_decompress_generic(source, dest, 0, originalSize, - endOnOutputSize, full, 0, withPrefix64k, - (BYTE*)dest - 64 KB, NULL, 0); -} - -/*===== Instantiate a few more decoding cases, used more than once. =====*/ - -LZ4_FORCE_O2_GCC_PPC64LE /* Exported, an obsolete API function. */ -int LZ4_decompress_safe_withPrefix64k(const char* source, char* dest, int compressedSize, int maxOutputSize) -{ - return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, - endOnInputSize, full, 0, withPrefix64k, - (BYTE*)dest - 64 KB, NULL, 0); -} - -/* Another obsolete API function, paired with the previous one. */ -int LZ4_decompress_fast_withPrefix64k(const char* source, char* dest, int originalSize) -{ - /* LZ4_decompress_fast doesn't validate match offsets, - * and thus serves well with any prefixed dictionary. */ - return LZ4_decompress_fast(source, dest, originalSize); -} - -LZ4_FORCE_O2_GCC_PPC64LE -static int LZ4_decompress_safe_withSmallPrefix(const char* source, char* dest, int compressedSize, int maxOutputSize, - size_t prefixSize) -{ - return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, - endOnInputSize, full, 0, noDict, - (BYTE*)dest-prefixSize, NULL, 0); -} - -LZ4_FORCE_O2_GCC_PPC64LE -int LZ4_decompress_safe_forceExtDict(const char* source, char* dest, - int compressedSize, int maxOutputSize, - const void* dictStart, size_t dictSize) -{ - return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, - endOnInputSize, full, 0, usingExtDict, - (BYTE*)dest, (const BYTE*)dictStart, dictSize); -} - -LZ4_FORCE_O2_GCC_PPC64LE -static int LZ4_decompress_fast_extDict(const char* source, char* dest, int originalSize, - const void* dictStart, size_t dictSize) -{ - return LZ4_decompress_generic(source, dest, 0, originalSize, - endOnOutputSize, full, 0, usingExtDict, - (BYTE*)dest, (const BYTE*)dictStart, dictSize); -} - -/* The "double dictionary" mode, for use with e.g. ring buffers: the first part - * of the dictionary is passed as prefix, and the second via dictStart + dictSize. - * These routines are used only once, in LZ4_decompress_*_continue(). - */ -LZ4_FORCE_INLINE -int LZ4_decompress_safe_doubleDict(const char* source, char* dest, int compressedSize, int maxOutputSize, - size_t prefixSize, const void* dictStart, size_t dictSize) -{ - return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, - endOnInputSize, full, 0, usingExtDict, - (BYTE*)dest-prefixSize, (const BYTE*)dictStart, dictSize); -} - -LZ4_FORCE_INLINE -int LZ4_decompress_fast_doubleDict(const char* source, char* dest, int originalSize, - size_t prefixSize, const void* dictStart, size_t dictSize) -{ - return LZ4_decompress_generic(source, dest, 0, originalSize, - endOnOutputSize, full, 0, usingExtDict, - (BYTE*)dest-prefixSize, (const BYTE*)dictStart, dictSize); -} - -/*===== streaming decompression functions =====*/ - -LZ4_streamDecode_t* LZ4_createStreamDecode(void) -{ - LZ4_streamDecode_t* lz4s = (LZ4_streamDecode_t*) ALLOC_AND_ZERO(sizeof(LZ4_streamDecode_t)); - return lz4s; -} - -int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream) -{ - if (!LZ4_stream) return 0; /* support free on NULL */ - FREEMEM(LZ4_stream); - return 0; -} - -/*! LZ4_setStreamDecode() : - * Use this function to instruct where to find the dictionary. - * This function is not necessary if previous data is still available where it was decoded. - * Loading a size of 0 is allowed (same effect as no dictionary). - * @return : 1 if OK, 0 if error - */ -int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize) -{ - LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse; - lz4sd->prefixSize = (size_t) dictSize; - lz4sd->prefixEnd = (const BYTE*) dictionary + dictSize; - lz4sd->externalDict = NULL; - lz4sd->extDictSize = 0; - return 1; -} - -/*! LZ4_decoderRingBufferSize() : - * when setting a ring buffer for streaming decompression (optional scenario), - * provides the minimum size of this ring buffer - * to be compatible with any source respecting maxBlockSize condition. - * Note : in a ring buffer scenario, - * blocks are presumed decompressed next to each other. - * When not enough space remains for next block (remainingSize < maxBlockSize), - * decoding resumes from beginning of ring buffer. - * @return : minimum ring buffer size, - * or 0 if there is an error (invalid maxBlockSize). - */ -int LZ4_decoderRingBufferSize(int maxBlockSize) -{ - if (maxBlockSize < 0) return 0; - if (maxBlockSize > LZ4_MAX_INPUT_SIZE) return 0; - if (maxBlockSize < 16) maxBlockSize = 16; - return LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize); -} - -/* -*_continue() : - These decoding functions allow decompression of multiple blocks in "streaming" mode. - Previously decoded blocks must still be available at the memory position where they were decoded. - If it's not possible, save the relevant part of decoded data into a safe buffer, - and indicate where it stands using LZ4_setStreamDecode() -*/ -LZ4_FORCE_O2_GCC_PPC64LE -int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxOutputSize) -{ - LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse; - int result; - - if (lz4sd->prefixSize == 0) { - /* The first call, no dictionary yet. */ - assert(lz4sd->extDictSize == 0); - result = LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize); - if (result <= 0) return result; - lz4sd->prefixSize = result; - lz4sd->prefixEnd = (BYTE*)dest + result; - } else if (lz4sd->prefixEnd == (BYTE*)dest) { - /* They're rolling the current segment. */ - if (lz4sd->prefixSize >= 64 KB - 1) - result = LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize); - else if (lz4sd->extDictSize == 0) - result = LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize, - lz4sd->prefixSize); - else - result = LZ4_decompress_safe_doubleDict(source, dest, compressedSize, maxOutputSize, - lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize); - if (result <= 0) return result; - lz4sd->prefixSize += result; - lz4sd->prefixEnd += result; - } else { - /* The buffer wraps around, or they're switching to another buffer. */ - lz4sd->extDictSize = lz4sd->prefixSize; - lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize; - result = LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize, - lz4sd->externalDict, lz4sd->extDictSize); - if (result <= 0) return result; - lz4sd->prefixSize = result; - lz4sd->prefixEnd = (BYTE*)dest + result; - } - - return result; -} - -LZ4_FORCE_O2_GCC_PPC64LE -int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize) -{ - LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse; - int result; - - if (lz4sd->prefixSize == 0) { - assert(lz4sd->extDictSize == 0); - result = LZ4_decompress_fast(source, dest, originalSize); - if (result <= 0) return result; - lz4sd->prefixSize = originalSize; - lz4sd->prefixEnd = (BYTE*)dest + originalSize; - } else if (lz4sd->prefixEnd == (BYTE*)dest) { - if (lz4sd->prefixSize >= 64 KB - 1 || lz4sd->extDictSize == 0) - result = LZ4_decompress_fast(source, dest, originalSize); - else - result = LZ4_decompress_fast_doubleDict(source, dest, originalSize, - lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize); - if (result <= 0) return result; - lz4sd->prefixSize += originalSize; - lz4sd->prefixEnd += originalSize; - } else { - lz4sd->extDictSize = lz4sd->prefixSize; - lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize; - result = LZ4_decompress_fast_extDict(source, dest, originalSize, - lz4sd->externalDict, lz4sd->extDictSize); - if (result <= 0) return result; - lz4sd->prefixSize = originalSize; - lz4sd->prefixEnd = (BYTE*)dest + originalSize; - } - - return result; -} - - -/* -Advanced decoding functions : -*_usingDict() : - These decoding functions work the same as "_continue" ones, - the dictionary must be explicitly provided within parameters -*/ - -int LZ4_decompress_safe_usingDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize) -{ - if (dictSize==0) - return LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize); - if (dictStart+dictSize == dest) { - if (dictSize >= 64 KB - 1) - return LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize); - return LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize, dictSize); - } - return LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize, dictStart, dictSize); -} - -int LZ4_decompress_fast_usingDict(const char* source, char* dest, int originalSize, const char* dictStart, int dictSize) -{ - if (dictSize==0 || dictStart+dictSize == dest) - return LZ4_decompress_fast(source, dest, originalSize); - return LZ4_decompress_fast_extDict(source, dest, originalSize, dictStart, dictSize); -} - - -/*=************************************************* -* Obsolete Functions -***************************************************/ -/* obsolete compression functions */ -int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize) -{ - return LZ4_compress_default(source, dest, inputSize, maxOutputSize); -} -int LZ4_compress(const char* source, char* dest, int inputSize) -{ - return LZ4_compress_default(source, dest, inputSize, LZ4_compressBound(inputSize)); -} -int LZ4_compress_limitedOutput_withState (void* state, const char* src, char* dst, int srcSize, int dstSize) -{ - return LZ4_compress_fast_extState(state, src, dst, srcSize, dstSize, 1); -} -int LZ4_compress_withState (void* state, const char* src, char* dst, int srcSize) -{ - return LZ4_compress_fast_extState(state, src, dst, srcSize, LZ4_compressBound(srcSize), 1); -} -int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* src, char* dst, int srcSize, int dstCapacity) -{ - return LZ4_compress_fast_continue(LZ4_stream, src, dst, srcSize, dstCapacity, 1); -} -int LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize) -{ - return LZ4_compress_fast_continue(LZ4_stream, source, dest, inputSize, LZ4_compressBound(inputSize), 1); -} - -/* -These decompression functions are deprecated and should no longer be used. -They are only provided here for compatibility with older user programs. -- LZ4_uncompress is totally equivalent to LZ4_decompress_fast -- LZ4_uncompress_unknownOutputSize is totally equivalent to LZ4_decompress_safe -*/ -int LZ4_uncompress (const char* source, char* dest, int outputSize) -{ - return LZ4_decompress_fast(source, dest, outputSize); -} -int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize) -{ - return LZ4_decompress_safe(source, dest, isize, maxOutputSize); -} - -/* Obsolete Streaming functions */ - -int LZ4_sizeofStreamState() { return LZ4_STREAMSIZE; } - -int LZ4_resetStreamState(void* state, char* inputBuffer) -{ - (void)inputBuffer; - LZ4_resetStream((LZ4_stream_t*)state); - return 0; -} - -void* LZ4_create (char* inputBuffer) -{ - (void)inputBuffer; - return LZ4_createStream(); -} - -char* LZ4_slideInputBuffer (void* state) -{ - /* avoid const char * -> char * conversion warning */ - return (char *)(uptrval)((LZ4_stream_t*)state)->internal_donotuse.dictionary; -} - -#endif /* LZ4_COMMONDEFS_ONLY */ \ No newline at end of file diff --git a/lib/libpki/include/nn/pki/CertificateBody.h b/lib/libpki/include/nn/pki/CertificateBody.h deleted file mode 100644 index 68205e7..0000000 --- a/lib/libpki/include/nn/pki/CertificateBody.h +++ /dev/null @@ -1,67 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace pki -{ - class CertificateBody - : public fnd::IByteModel - { - public: - CertificateBody(); - CertificateBody(const CertificateBody& other); - - void operator=(const CertificateBody& other); - bool operator==(const CertificateBody& other) const; - bool operator!=(const CertificateBody& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* src, size_t size); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - const std::string& getIssuer() const; - void setIssuer(const std::string& issuer); - - pki::cert::PublicKeyType getPublicKeyType() const; - void setPublicKeyType(cert::PublicKeyType type); - - const std::string& getSubject() const; - void setSubject(const std::string& subject); - - uint32_t getCertId() const; - void setCertId(uint32_t id); - - const fnd::rsa::sRsa4096Key& getRsa4098PublicKey() const; - void setRsa4098PublicKey(const fnd::rsa::sRsa4096Key& key); - - const fnd::rsa::sRsa2048Key& getRsa2048PublicKey() const; - void setRsa2048PublicKey(const fnd::rsa::sRsa2048Key& key); - - const fnd::ecdsa::sEcdsa240Point& getEcdsa240PublicKey() const; - void setEcdsa240PublicKey(const fnd::ecdsa::sEcdsa240Point& key); - - private: - const std::string kModuleName = "CERTIFICATE_BODY"; - - // raw binary - fnd::Vec mRawBinary; - - // variables - std::string mIssuer; - std::string mSubject; - uint32_t mCertId; - cert::PublicKeyType mPublicKeyType; - - fnd::rsa::sRsa4096Key mRsa4096PublicKey; - fnd::rsa::sRsa2048Key mRsa2048PublicKey; - fnd::ecdsa::sEcdsa240Point mEcdsa240PublicKey; - }; -} -} \ No newline at end of file diff --git a/lib/libpki/include/nn/pki/SignUtils.h b/lib/libpki/include/nn/pki/SignUtils.h deleted file mode 100644 index c3035fd..0000000 --- a/lib/libpki/include/nn/pki/SignUtils.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once -#include -#include - -namespace nn -{ -namespace pki -{ - -namespace sign -{ - nn::pki::sign::SignatureAlgo getSignatureAlgo(pki::sign::SignatureId sign_id); - nn::pki::sign::HashAlgo getHashAlgo(pki::sign::SignatureId sign_id); -} - -} -} \ No newline at end of file diff --git a/lib/libpki/include/nn/pki/SignatureBlock.h b/lib/libpki/include/nn/pki/SignatureBlock.h deleted file mode 100644 index 42e41b3..0000000 --- a/lib/libpki/include/nn/pki/SignatureBlock.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace pki -{ - class SignatureBlock - : public fnd::IByteModel - { - public: - SignatureBlock(); - SignatureBlock(const SignatureBlock& other); - - void operator=(const SignatureBlock& other); - bool operator==(const SignatureBlock& other) const; - bool operator!=(const SignatureBlock& other) const; - - // IByteModel - void toBytes(); - void fromBytes(const byte_t* src, size_t size); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - pki::sign::SignatureId getSignType() const; - void setSignType(pki::sign::SignatureId type); - - bool isLittleEndian() const; - void setLittleEndian(bool isLE); - - const fnd::Vec& getSignature() const; - void setSignature(const fnd::Vec& signature); - - - private: - const std::string kModuleName = "SIGNATURE_BLOCK"; - - // raw binary - fnd::Vec mRawBinary; - - // variables - pki::sign::SignatureId mSignType; - bool mIsLittleEndian; - fnd::Vec mSignature; - }; -} -} \ No newline at end of file diff --git a/lib/libpki/include/nn/pki/SignedData.h b/lib/libpki/include/nn/pki/SignedData.h deleted file mode 100644 index 3180974..0000000 --- a/lib/libpki/include/nn/pki/SignedData.h +++ /dev/null @@ -1,139 +0,0 @@ -#pragma once -#include -#include -#include - -namespace nn -{ -namespace pki -{ - template - class SignedData - : public fnd::IByteModel - { - public: - SignedData(); - SignedData(const SignedData& other); - - void operator=(const SignedData& other); - bool operator==(const SignedData& other) const; - bool operator!=(const SignedData& other) const; - - // export/import - void toBytes(); - void fromBytes(const byte_t* src, size_t size); - const fnd::Vec& getBytes() const; - - // variables - void clear(); - - const pki::SignatureBlock& getSignature() const; - void setSignature(const SignatureBlock& signature); - - const T& getBody() const; - void setBody(const T& body); - private: - const std::string kModuleName = "SIGNED_DATA"; - - // raw binary - fnd::Vec mRawBinary; - - // variables - SignatureBlock mSignature; - T mBody; - }; - - template - inline SignedData::SignedData() - { - clear(); - } - - template - inline SignedData::SignedData(const SignedData& other) - { - *this = other; - } - - template - inline void SignedData::operator=(const SignedData& other) - { - mRawBinary = other.mRawBinary; - mSignature = other.mSignature; - mBody = other.mBody; - } - - template - inline bool SignedData::operator==(const SignedData& other) const - { - return (mSignature == other.mSignature) \ - && (mBody == other.mBody); - } - - template - inline bool SignedData::operator!=(const SignedData& other) const - { - return !(*this == other); - } - - template - inline void SignedData::toBytes() - { - mSignature.toBytes(); - mBody.toBytes(); - - mRawBinary.alloc(mSignature.getBytes().size() + mBody.getBytes().size()); - - memcpy(mRawBinary.data(), mSignature.getBytes().data(), mSignature.getBytes().size()); - memcpy(mRawBinary.data() + mSignature.getBytes().size(), mBody.getBytes().data(), mBody.getBytes().size()); - } - - template - inline void SignedData::fromBytes(const byte_t* src, size_t size) - { - mSignature.fromBytes(src, size); - mBody.fromBytes(src + mSignature.getBytes().size(), size - mSignature.getBytes().size()); - - mRawBinary.alloc(mSignature.getBytes().size() + mBody.getBytes().size()); - memcpy(mRawBinary.data(), src, mRawBinary.size()); - } - - template - inline const fnd::Vec& SignedData::getBytes() const - { - return mRawBinary; - } - - template - inline void SignedData::clear() - { - mRawBinary.clear(); - mSignature.clear(); - mBody.clear(); - } - - template - inline const pki::SignatureBlock& SignedData::getSignature() const - { - return mSignature; - } - - template - inline void SignedData::setSignature(const SignatureBlock& signature) - { - mSignature = signature; - } - - template - inline const T& SignedData::getBody() const - { - return mBody; - } - - template - inline void SignedData::setBody(const T& body) - { - mBody = body; - } -} -} \ No newline at end of file diff --git a/lib/libpki/include/nn/pki/cert.h b/lib/libpki/include/nn/pki/cert.h deleted file mode 100644 index fc2ea54..0000000 --- a/lib/libpki/include/nn/pki/cert.h +++ /dev/null @@ -1,54 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include - -namespace nn -{ -namespace pki -{ - namespace cert - { - enum PublicKeyType - { - RSA4096, - RSA2048, - ECDSA240 - }; - - static const size_t kIssuerSize = 0x40; - static const size_t kSubjectSize = 0x40; - } -#pragma pack(push,1) - struct sCertificateHeader - { - char issuer[cert::kIssuerSize]; - be_uint32_t key_type; - char subject[cert::kSubjectSize]; - be_uint32_t cert_id; - }; - - struct sRsa4096PublicKeyBlock - { - byte_t modulus[fnd::rsa::kRsa4096Size]; - byte_t public_exponent[fnd::rsa::kRsaPublicExponentSize]; - byte_t padding[0x34]; - }; - - struct sRsa2048PublicKeyBlock - { - byte_t modulus[fnd::rsa::kRsa2048Size]; - byte_t public_exponent[fnd::rsa::kRsaPublicExponentSize]; - byte_t padding[0x34]; - }; - - struct sEcdsa240PublicKeyBlock - { - fnd::ecdsa::sEcdsa240Point public_key; - byte_t padding[0x3C]; - }; -#pragma pack(pop) -} -} \ No newline at end of file diff --git a/lib/libpki/include/nn/pki/sign.h b/lib/libpki/include/nn/pki/sign.h deleted file mode 100644 index bc89d01..0000000 --- a/lib/libpki/include/nn/pki/sign.h +++ /dev/null @@ -1,65 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include - -namespace nn -{ -namespace pki -{ - namespace sign - { - enum SignatureId - { - SIGN_ID_RSA4096_SHA1 = 0x10000, - SIGN_ID_RSA2048_SHA1, - SIGN_ID_ECDSA240_SHA1, - SIGN_ID_RSA4096_SHA256, - SIGN_ID_RSA2048_SHA256, - SIGN_ID_ECDSA240_SHA256, - }; - - enum SignatureAlgo - { - SIGN_ALGO_RSA4096, - SIGN_ALGO_RSA2048, - SIGN_ALGO_ECDSA240 - }; - - enum HashAlgo - { - HASH_ALGO_SHA1, - HASH_ALGO_SHA256 - }; - - static const size_t kEcdsaSigSize = 0x3C; - - static const std::string kRootIssuerStr = "Root"; - static const std::string kIdentDelimiter = "-"; - } -#pragma pack(push,1) - struct sRsa4096SignBlock - { - be_uint32_t sign_type; - byte_t signature[fnd::rsa::kRsa4096Size]; - byte_t padding[0x3C]; - }; - - struct sRsa2048SignBlock - { - be_uint32_t sign_type; - byte_t signature[fnd::rsa::kRsa2048Size]; - byte_t padding[0x3C]; - }; - - struct sEcdsa240SignBlock - { - be_uint32_t sign_type; - byte_t signature[sign::kEcdsaSigSize]; - byte_t padding[0x40]; - }; -#pragma pack(pop) -} -} \ No newline at end of file diff --git a/lib/libpki/libpki.vcxproj b/lib/libpki/libpki.vcxproj deleted file mode 100644 index f638e1e..0000000 --- a/lib/libpki/libpki.vcxproj +++ /dev/null @@ -1,143 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 15.0 - {B9113734-6E84-44FF-8CF7-58199AA815C5} - 10.0.16299.0 - - - - StaticLibrary - true - v141 - MultiByte - - - StaticLibrary - false - v141 - true - MultiByte - - - StaticLibrary - true - v141 - MultiByte - - - StaticLibrary - false - v141 - true - MultiByte - - - - - - - - - - - - - - - - - - - - - - - Level3 - MaxSpeed - true - true - true - true - ..\libfnd\include;..\libpki\include; - _CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - true - true - - - - - Level3 - Disabled - true - true - ..\libfnd\include;..\libpki\include; - _CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - - - Level3 - Disabled - true - true - ..\libfnd\include;..\libpki\include; - _CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - - - Level3 - MaxSpeed - true - true - true - true - ..\libfnd\include;..\libpki\include; - _CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - true - true - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/lib/libpki/libpki.vcxproj.filters b/lib/libpki/libpki.vcxproj.filters deleted file mode 100644 index 2396670..0000000 --- a/lib/libpki/libpki.vcxproj.filters +++ /dev/null @@ -1,51 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;ipp;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - - - Source Files - - - Source Files - - - Source Files - - - - - - \ No newline at end of file diff --git a/lib/libpki/libpki.vcxproj.user b/lib/libpki/libpki.vcxproj.user deleted file mode 100644 index be25078..0000000 --- a/lib/libpki/libpki.vcxproj.user +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/lib/libpki/makefile b/lib/libpki/makefile deleted file mode 100644 index 045b0ab..0000000 --- a/lib/libpki/makefile +++ /dev/null @@ -1,45 +0,0 @@ -# Sources -SRC_DIR = source -OBJS = $(foreach dir,$(SRC_DIR),$(subst .cpp,.o,$(wildcard $(dir)/*.cpp))) $(foreach dir,$(SRC_DIR),$(subst .c,.o,$(wildcard $(dir)/*.c))) - -# External dependencies -DEPENDS = fnd crypto -LIB_DIR = .. -INCS = -I"include" $(foreach dep,$(DEPENDS), -I"$(LIB_DIR)/lib$(dep)/include") - -# Compiler Settings -CXXFLAGS = -std=c++11 $(INCS) -D__STDC_FORMAT_MACROS -Wall -Wno-unused-value -CFLAGS = -std=c11 $(INCS) -Wall -Wno-unused-value -ARFLAGS = cr -o -ifeq ($(OS),Windows_NT) - # Windows Only Flags/Libs - CC = x86_64-w64-mingw32-gcc - CXX = x86_64-w64-mingw32-g++ - CFLAGS += -Wno-unused-but-set-variable - CXXFLAGS += -Wno-unused-but-set-variable -else - UNAME = $(shell uname -s) - ifeq ($(UNAME), Darwin) - # MacOS Only Flags/Libs - CFLAGS += -arch x86_64 -Wno-unused-private-field - CXXFLAGS += -arch x86_64 -Wno-unused-private-field - ARFLAGS = rc - else - # *nix Only Flags/Libs - CFLAGS += -Wno-unused-but-set-variable - CXXFLAGS += -Wno-unused-but-set-variable - endif -endif - -# Output -OUTPUT = $(shell basename "$(CURDIR)").a - -main: build - -rebuild: clean build - -build: $(OBJS) - ar $(ARFLAGS) $(OUTPUT) $(OBJS) - -clean: - rm -rf $(OUTPUT) $(OBJS) \ No newline at end of file diff --git a/lib/libpki/source/CertificateBody.cpp b/lib/libpki/source/CertificateBody.cpp deleted file mode 100644 index 2c2b8c6..0000000 --- a/lib/libpki/source/CertificateBody.cpp +++ /dev/null @@ -1,254 +0,0 @@ -#include - -nn::pki::CertificateBody::CertificateBody() -{ - clear(); -} - -nn::pki::CertificateBody::CertificateBody(const CertificateBody& other) -{ - *this = other; -} - -void nn::pki::CertificateBody::operator=(const CertificateBody& other) -{ - mRawBinary = other.mRawBinary; - mIssuer = other.mIssuer; - mSubject = other.mSubject; - mCertId = other.mCertId; - mPublicKeyType = other.mPublicKeyType; - mRsa4096PublicKey = other.mRsa4096PublicKey; - mRsa2048PublicKey = other.mRsa2048PublicKey; - mEcdsa240PublicKey = other.mEcdsa240PublicKey; -} - -bool nn::pki::CertificateBody::operator==(const CertificateBody& other) const -{ - return (mIssuer == other.mIssuer) \ - && (mSubject == other.mSubject) \ - && (mCertId == other.mCertId) \ - && (mPublicKeyType == other.mPublicKeyType) \ - && (mRsa4096PublicKey == other.mRsa4096PublicKey) \ - && (mRsa2048PublicKey == other.mRsa2048PublicKey) \ - && (mEcdsa240PublicKey == other.mEcdsa240PublicKey); -} - -bool nn::pki::CertificateBody::operator!=(const CertificateBody& other) const -{ - return !(*this == other); -} - -void nn::pki::CertificateBody::toBytes() -{ - // get public key size - size_t pubkeySize = 0; - switch (mPublicKeyType) - { - case (cert::RSA4096): - pubkeySize = sizeof(sRsa4096PublicKeyBlock); - break; - case (cert::RSA2048): - pubkeySize = sizeof(sRsa2048PublicKeyBlock); - break; - case (cert::ECDSA240): - pubkeySize = sizeof(sEcdsa240PublicKeyBlock); - break; - default: - throw fnd::Exception(kModuleName, "Unknown public key type"); - } - - mRawBinary.alloc(sizeof(sCertificateHeader) + pubkeySize); - sCertificateHeader* hdr = (sCertificateHeader*)mRawBinary.data(); - - // copy header vars - strncpy(hdr->issuer, mIssuer.c_str(), cert::kIssuerSize); - hdr->key_type = mPublicKeyType; - strncpy(hdr->subject, mSubject.c_str(), cert::kSubjectSize); - hdr->cert_id = mCertId; - - // copy public key - if (mPublicKeyType == cert::RSA4096) - { - sRsa4096PublicKeyBlock* pubkey = (sRsa4096PublicKeyBlock*)(mRawBinary.data() + sizeof(sCertificateHeader)); - memcpy(pubkey->modulus, mRsa4096PublicKey.modulus, sizeof(mRsa4096PublicKey.modulus)); - memcpy(pubkey->public_exponent, mRsa4096PublicKey.public_exponent, sizeof(mRsa4096PublicKey.public_exponent)); - } - else if (mPublicKeyType == cert::RSA2048) - { - sRsa2048PublicKeyBlock* pubkey = (sRsa2048PublicKeyBlock*)(mRawBinary.data() + sizeof(sCertificateHeader)); - memcpy(pubkey->modulus, mRsa2048PublicKey.modulus, sizeof(mRsa2048PublicKey.modulus)); - memcpy(pubkey->public_exponent, mRsa2048PublicKey.public_exponent, sizeof(mRsa2048PublicKey.public_exponent)); - } - else if (mPublicKeyType == cert::ECDSA240) - { - sEcdsa240PublicKeyBlock* pubkey = (sEcdsa240PublicKeyBlock*)(mRawBinary.data() + sizeof(sCertificateHeader)); - pubkey->public_key = mEcdsa240PublicKey; - } -} - -void nn::pki::CertificateBody::fromBytes(const byte_t* src, size_t size) -{ - clear(); - - // check minimum size - if (size < sizeof(sCertificateHeader)) - { - throw fnd::Exception(kModuleName, "Certificate too small"); - } - - const sCertificateHeader* hdr = (const sCertificateHeader*)src; - - // get public key size - size_t pubkeySize = 0; - switch (hdr->key_type.get()) - { - case (cert::RSA4096): - pubkeySize = sizeof(sRsa4096PublicKeyBlock); - break; - case (cert::RSA2048): - pubkeySize = sizeof(sRsa2048PublicKeyBlock); - break; - case (cert::ECDSA240): - pubkeySize = sizeof(sEcdsa240PublicKeyBlock); - break; - default: - throw fnd::Exception(kModuleName, "Unknown public key type"); - } - - // check total size - if (size < (sizeof(sCertificateHeader) + pubkeySize)) - { - throw fnd::Exception(kModuleName, "Certificate too small"); - } - - // save raw binary - mRawBinary.alloc((sizeof(sCertificateHeader) + pubkeySize)); - memcpy(mRawBinary.data(), src, mRawBinary.size()); - - // save hdr variables - hdr = (const sCertificateHeader*)mRawBinary.data(); - - if (hdr->issuer[0] != 0) - mIssuer = std::string(hdr->issuer, _MIN(strlen(hdr->issuer), cert::kIssuerSize)); - mPublicKeyType = (cert::PublicKeyType)hdr->key_type.get(); - if (hdr->subject[0] != 0) - mSubject = std::string(hdr->subject, _MIN(strlen(hdr->subject), cert::kSubjectSize)); - mCertId = hdr->cert_id.get(); - - // save public key - if (mPublicKeyType == cert::RSA4096) - { - const sRsa4096PublicKeyBlock* pubkey = (const sRsa4096PublicKeyBlock*)(mRawBinary.data() + sizeof(sCertificateHeader)); - memcpy(mRsa4096PublicKey.modulus, pubkey->modulus, sizeof(mRsa4096PublicKey.modulus)); - memcpy(mRsa4096PublicKey.public_exponent, pubkey->public_exponent, sizeof(mRsa4096PublicKey.public_exponent)); - } - else if (mPublicKeyType == cert::RSA2048) - { - const sRsa2048PublicKeyBlock* pubkey = (const sRsa2048PublicKeyBlock*)(mRawBinary.data() + sizeof(sCertificateHeader)); - memcpy(mRsa2048PublicKey.modulus, pubkey->modulus, sizeof(mRsa2048PublicKey.modulus)); - memcpy(mRsa2048PublicKey.public_exponent, pubkey->public_exponent, sizeof(mRsa2048PublicKey.public_exponent)); - } - else if (mPublicKeyType == cert::ECDSA240) - { - const sEcdsa240PublicKeyBlock* pubkey = (const sEcdsa240PublicKeyBlock*)(mRawBinary.data() + sizeof(sCertificateHeader)); - mEcdsa240PublicKey = pubkey->public_key; - } -} - -const fnd::Vec& nn::pki::CertificateBody::getBytes() const -{ - return mRawBinary; -} - - -void nn::pki::CertificateBody::clear() -{ - mIssuer.clear(); - mSubject.clear(); - mCertId = 0; - mPublicKeyType = cert::RSA2048; - - memset(&mRsa4096PublicKey, 0, sizeof(fnd::rsa::sRsa4096Key)); - memset(&mRsa2048PublicKey, 0, sizeof(fnd::rsa::sRsa2048Key)); - memset(&mEcdsa240PublicKey, 0, sizeof(fnd::ecdsa::sEcdsa240Point)); -} - -const std::string& nn::pki::CertificateBody::getIssuer() const -{ - return mIssuer; -} - -void nn::pki::CertificateBody::setIssuer(const std::string& issuer) -{ - if (issuer.size() > cert::kIssuerSize) - { - throw fnd::Exception(kModuleName, "Issuer name too long"); - } - - mIssuer = issuer; -} - -nn::pki::cert::PublicKeyType nn::pki::CertificateBody::getPublicKeyType() const -{ - return mPublicKeyType; -} - -void nn::pki::CertificateBody::setPublicKeyType(cert::PublicKeyType type) -{ - mPublicKeyType = type; -} - -const std::string& nn::pki::CertificateBody::getSubject() const -{ - return mSubject; -} - -void nn::pki::CertificateBody::setSubject(const std::string& subject) -{ - if (subject.size() > cert::kSubjectSize) - { - throw fnd::Exception(kModuleName, "Subject name too long"); - } - - mSubject = subject; -} - -uint32_t nn::pki::CertificateBody::getCertId() const -{ - return mCertId; -} - -void nn::pki::CertificateBody::setCertId(uint32_t id) -{ - mCertId = id; -} - -const fnd::rsa::sRsa4096Key& nn::pki::CertificateBody::getRsa4098PublicKey() const -{ - return mRsa4096PublicKey; -} - -void nn::pki::CertificateBody::setRsa4098PublicKey(const fnd::rsa::sRsa4096Key& key) -{ - mRsa4096PublicKey = key; -} - -const fnd::rsa::sRsa2048Key& nn::pki::CertificateBody::getRsa2048PublicKey() const -{ - return mRsa2048PublicKey; -} - -void nn::pki::CertificateBody::setRsa2048PublicKey(const fnd::rsa::sRsa2048Key& key) -{ - mRsa2048PublicKey = key; -} - -const fnd::ecdsa::sEcdsa240Point& nn::pki::CertificateBody::getEcdsa240PublicKey() const -{ - return mEcdsa240PublicKey; -} - -void nn::pki::CertificateBody::setEcdsa240PublicKey(const fnd::ecdsa::sEcdsa240Point& key) -{ - mEcdsa240PublicKey = key; -} \ No newline at end of file diff --git a/lib/libpki/source/SignUtils.cpp b/lib/libpki/source/SignUtils.cpp deleted file mode 100644 index 56ff86d..0000000 --- a/lib/libpki/source/SignUtils.cpp +++ /dev/null @@ -1,45 +0,0 @@ -#include - -nn::pki::sign::SignatureAlgo nn::pki::sign::getSignatureAlgo(nn::pki::sign::SignatureId sign_id) -{ - SignatureAlgo sign_algo = SIGN_ALGO_RSA4096; - - switch (sign_id) - { - case (nn::pki::sign::SIGN_ID_RSA4096_SHA1): - case (nn::pki::sign::SIGN_ID_RSA4096_SHA256): - sign_algo = SIGN_ALGO_RSA4096; - break; - case (nn::pki::sign::SIGN_ID_RSA2048_SHA1): - case (nn::pki::sign::SIGN_ID_RSA2048_SHA256): - sign_algo = SIGN_ALGO_RSA2048; - break; - case (nn::pki::sign::SIGN_ID_ECDSA240_SHA1): - case (nn::pki::sign::SIGN_ID_ECDSA240_SHA256): - sign_algo = SIGN_ALGO_ECDSA240; - break; - }; - - return sign_algo; -} - -nn::pki::sign::HashAlgo nn::pki::sign::getHashAlgo(nn::pki::sign::SignatureId sign_id) -{ - HashAlgo hash_algo = HASH_ALGO_SHA1; - - switch (sign_id) - { - case (nn::pki::sign::SIGN_ID_RSA4096_SHA1): - case (nn::pki::sign::SIGN_ID_RSA2048_SHA1): - case (nn::pki::sign::SIGN_ID_ECDSA240_SHA1): - hash_algo = HASH_ALGO_SHA1; - break; - case (nn::pki::sign::SIGN_ID_RSA4096_SHA256): - case (nn::pki::sign::SIGN_ID_RSA2048_SHA256): - case (nn::pki::sign::SIGN_ID_ECDSA240_SHA256): - hash_algo = HASH_ALGO_SHA256; - break; - }; - - return hash_algo; -} \ No newline at end of file diff --git a/lib/libpki/source/SignatureBlock.cpp b/lib/libpki/source/SignatureBlock.cpp deleted file mode 100644 index 1088ea4..0000000 --- a/lib/libpki/source/SignatureBlock.cpp +++ /dev/null @@ -1,182 +0,0 @@ -#include - -nn::pki::SignatureBlock::SignatureBlock() -{ - clear(); -} - -nn::pki::SignatureBlock::SignatureBlock(const SignatureBlock& other) -{ - *this = other; -} - -void nn::pki::SignatureBlock::operator=(const SignatureBlock& other) -{ - mRawBinary = other.mRawBinary; - mSignType = other.mSignType; - mIsLittleEndian = other.mIsLittleEndian; - mSignature = other.mSignature; -} - -bool nn::pki::SignatureBlock::operator==(const SignatureBlock& other) const -{ - return (mSignType == other.mSignType) \ - && (mIsLittleEndian == other.mIsLittleEndian) \ - && (mSignature == other.mSignature); -} - -bool nn::pki::SignatureBlock::operator!=(const SignatureBlock& other) const -{ - return !(*this == other); -} - -void nn::pki::SignatureBlock::toBytes() -{ - size_t totalSize = 0; - size_t sigSize = 0; - - switch (mSignType) - { - case (sign::SIGN_ID_RSA4096_SHA1): - case (sign::SIGN_ID_RSA4096_SHA256): - totalSize = sizeof(sRsa4096SignBlock); - sigSize = fnd::rsa::kRsa4096Size; - break; - case (sign::SIGN_ID_RSA2048_SHA1): - case (sign::SIGN_ID_RSA2048_SHA256): - totalSize = sizeof(sRsa2048SignBlock); - sigSize = fnd::rsa::kRsa2048Size; - break; - case (sign::SIGN_ID_ECDSA240_SHA1): - case (sign::SIGN_ID_ECDSA240_SHA256): - totalSize = sizeof(sEcdsa240SignBlock); - sigSize = sign::kEcdsaSigSize; - break; - default: - throw fnd::Exception(kModuleName, "Unknown signature type"); - } - - if (mSignature.size() != sigSize) - throw fnd::Exception(kModuleName, "Signature size is incorrect"); - - // commit to binary - mRawBinary.alloc(totalSize); - if (mIsLittleEndian) - *(le_uint32_t*)(mRawBinary.data()) = mSignType; - else - *(be_uint32_t*)(mRawBinary.data()) = mSignType; - memcpy(mRawBinary.data() + 4, mSignature.data(), sigSize); -} - -void nn::pki::SignatureBlock::fromBytes(const byte_t* src, size_t size) -{ - clear(); - - size_t totalSize = 0; - size_t sigSize = 0; - uint32_t signType = 0; - - // try Big Endian sign type - signType = ((be_uint32_t*)src)->get(); - switch (signType) - { - case (sign::SIGN_ID_RSA4096_SHA1): - case (sign::SIGN_ID_RSA4096_SHA256): - totalSize = sizeof(sRsa4096SignBlock); - sigSize = fnd::rsa::kRsa4096Size; - break; - case (sign::SIGN_ID_RSA2048_SHA1): - case (sign::SIGN_ID_RSA2048_SHA256): - totalSize = sizeof(sRsa2048SignBlock); - sigSize = fnd::rsa::kRsa2048Size; - break; - case (sign::SIGN_ID_ECDSA240_SHA1): - case (sign::SIGN_ID_ECDSA240_SHA256): - totalSize = sizeof(sEcdsa240SignBlock); - sigSize = sign::kEcdsaSigSize; - break; - } - - // try Big Endian sign type - if (totalSize == 0) - { - signType = ((le_uint32_t*)src)->get(); - switch (signType) - { - case (sign::SIGN_ID_RSA4096_SHA1): - case (sign::SIGN_ID_RSA4096_SHA256): - totalSize = sizeof(sRsa4096SignBlock); - sigSize = fnd::rsa::kRsa4096Size; - break; - case (sign::SIGN_ID_RSA2048_SHA1): - case (sign::SIGN_ID_RSA2048_SHA256): - totalSize = sizeof(sRsa2048SignBlock); - sigSize = fnd::rsa::kRsa2048Size; - break; - case (sign::SIGN_ID_ECDSA240_SHA1): - case (sign::SIGN_ID_ECDSA240_SHA256): - totalSize = sizeof(sEcdsa240SignBlock); - sigSize = sign::kEcdsaSigSize; - break; - default: - throw fnd::Exception(kModuleName, "Unknown signature type"); - } - - mIsLittleEndian = true; - } - - if (totalSize > size) - { - throw fnd::Exception(kModuleName, "Certificate too small"); - } - - mRawBinary.alloc(totalSize); - memcpy(mRawBinary.data(), src, totalSize); - - mSignType = (sign::SignatureId)signType; - mSignature.alloc(sigSize); - memcpy(mSignature.data(), mRawBinary.data() + 4, sigSize); -} - -const fnd::Vec& nn::pki::SignatureBlock::getBytes() const -{ - return mRawBinary; -} - -void nn::pki::SignatureBlock::clear() -{ - mRawBinary.clear(); - mSignType = sign::SIGN_ID_RSA4096_SHA1; - mIsLittleEndian = false; - mSignature.clear(); -} - -nn::pki::sign::SignatureId nn::pki::SignatureBlock::getSignType() const -{ - return mSignType; -} - -void nn::pki::SignatureBlock::setSignType(nn::pki::sign::SignatureId type) -{ - mSignType = type; -} - -bool nn::pki::SignatureBlock::isLittleEndian() const -{ - return mIsLittleEndian; -} - -void nn::pki::SignatureBlock::setLittleEndian(bool isLE) -{ - mIsLittleEndian = isLE; -} - -const fnd::Vec& nn::pki::SignatureBlock::getSignature() const -{ - return mSignature; -} - -void nn::pki::SignatureBlock::setSignature(const fnd::Vec& signature) -{ - mSignature = signature; -} diff --git a/lib/libpolarssl/include/polarssl/aes.h b/lib/libpolarssl/include/polarssl/aes.h deleted file mode 100644 index f78fbd9..0000000 --- a/lib/libpolarssl/include/polarssl/aes.h +++ /dev/null @@ -1,203 +0,0 @@ -/** - * \file aes.h - * - * \brief AES block cipher - * - * Copyright (C) 2006-2013, Brainspark B.V. - * - * This file is part of PolarSSL (http://www.polarssl.org) - * Lead Maintainer: Paul Bakker - * - * All rights reserved. - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ -#ifndef POLARSSL_AES_H -#define POLARSSL_AES_H - -#include "config.h" - -#include - -#ifdef _MSC_VER -#include -typedef UINT32 uint32_t; -typedef UINT64 uint64_t; -#else -#include -#endif - -#define AES_ENCRYPT 1 -#define AES_DECRYPT 0 - -#define POLARSSL_ERR_AES_INVALID_KEY_LENGTH -0x0020 /**< Invalid key length. */ -#define POLARSSL_ERR_AES_INVALID_INPUT_LENGTH -0x0022 /**< Invalid data input length. */ - -#if !defined(POLARSSL_AES_ALT) -// Regular implementation -// - -/** - * \brief AES context structure - */ -typedef struct -{ - int nr; /*!< number of rounds */ - uint32_t *rk; /*!< AES round keys */ - uint32_t buf[68]; /*!< unaligned data */ -} -aes_context; - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \brief AES key schedule (encryption) - * - * \param ctx AES context to be initialized - * \param key encryption key - * \param keysize must be 128, 192 or 256 - * - * \return 0 if successful, or POLARSSL_ERR_AES_INVALID_KEY_LENGTH - */ -int aes_setkey_enc( aes_context *ctx, const unsigned char *key, unsigned int keysize ); - -/** - * \brief AES key schedule (decryption) - * - * \param ctx AES context to be initialized - * \param key decryption key - * \param keysize must be 128, 192 or 256 - * - * \return 0 if successful, or POLARSSL_ERR_AES_INVALID_KEY_LENGTH - */ -int aes_setkey_dec( aes_context *ctx, const unsigned char *key, unsigned int keysize ); - -/** - * \brief AES-ECB block encryption/decryption - * - * \param ctx AES context - * \param mode AES_ENCRYPT or AES_DECRYPT - * \param input 16-byte input block - * \param output 16-byte output block - * - * \return 0 if successful - */ -int aes_crypt_ecb( aes_context *ctx, - int mode, - const unsigned char input[16], - unsigned char output[16] ); - -/** - * \brief AES-CBC buffer encryption/decryption - * Length should be a multiple of the block - * size (16 bytes) - * - * \param ctx AES context - * \param mode AES_ENCRYPT or AES_DECRYPT - * \param length length of the input data - * \param iv initialization vector (updated after use) - * \param input buffer holding the input data - * \param output buffer holding the output data - * - * \return 0 if successful, or POLARSSL_ERR_AES_INVALID_INPUT_LENGTH - */ -int aes_crypt_cbc( aes_context *ctx, - int mode, - uint64_t length, - unsigned char iv[16], - const unsigned char *input, - unsigned char *output ); - -/** - * \brief AES-CFB128 buffer encryption/decryption. - * - * Note: Due to the nature of CFB you should use the same key schedule for - * both encryption and decryption. So a context initialized with - * aes_setkey_enc() for both AES_ENCRYPT and AES_DECRYPT. - * - * both - * \param ctx AES context - * \param mode AES_ENCRYPT or AES_DECRYPT - * \param length length of the input data - * \param iv_off offset in IV (updated after use) - * \param iv initialization vector (updated after use) - * \param input buffer holding the input data - * \param output buffer holding the output data - * - * \return 0 if successful - */ -int aes_crypt_cfb128( aes_context *ctx, - int mode, - uint64_t length, - size_t *iv_off, - unsigned char iv[16], - const unsigned char *input, - unsigned char *output ); - -/** - * \brief AES-CTR buffer encryption/decryption - * - * Warning: You have to keep the maximum use of your counter in mind! - * - * Note: Due to the nature of CTR you should use the same key schedule for - * both encryption and decryption. So a context initialized with - * aes_setkey_enc() for both AES_ENCRYPT and AES_DECRYPT. - * - * \param length The length of the data - * \param nc_off The offset in the current stream_block (for resuming - * within current cipher stream). The offset pointer to - * should be 0 at the start of a stream. - * \param nonce_counter The 128-bit nonce and counter. - * \param stream_block The saved stream-block for resuming. Is overwritten - * by the function. - * \param input The input data stream - * \param output The output data stream - * - * \return 0 if successful - */ -int aes_crypt_ctr( aes_context *ctx, - uint64_t length, - size_t *nc_off, - unsigned char nonce_counter[16], - unsigned char stream_block[16], - const unsigned char *input, - unsigned char *output ); - -#ifdef __cplusplus -} -#endif - -#else /* POLARSSL_AES_ALT */ -#include "polarssl/aes_alt.h" -#endif /* POLARSSL_AES_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \brief Checkup routine - * - * \return 0 if successful, or 1 if the test failed - */ -int aes_self_test( int verbose ); - -#ifdef __cplusplus -} -#endif - -#endif /* aes.h */ diff --git a/lib/libpolarssl/include/polarssl/base64.h b/lib/libpolarssl/include/polarssl/base64.h deleted file mode 100644 index 604893e..0000000 --- a/lib/libpolarssl/include/polarssl/base64.h +++ /dev/null @@ -1,88 +0,0 @@ -/** - * \file base64.h - * - * \brief RFC 1521 base64 encoding/decoding - * - * Copyright (C) 2006-2010, Brainspark B.V. - * - * This file is part of PolarSSL (http://www.polarssl.org) - * Lead Maintainer: Paul Bakker - * - * All rights reserved. - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ -#ifndef POLARSSL_BASE64_H -#define POLARSSL_BASE64_H - -#include -#include - -#define POLARSSL_ERR_BASE64_BUFFER_TOO_SMALL -0x002A /**< Output buffer too small. */ -#define POLARSSL_ERR_BASE64_INVALID_CHARACTER -0x002C /**< Invalid character in input. */ - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \brief Encode a buffer into base64 format - * - * \param dst destination buffer - * \param dlen size of the buffer - * \param src source buffer - * \param slen amount of data to be encoded - * - * \return 0 if successful, or POLARSSL_ERR_BASE64_BUFFER_TOO_SMALL. - * *dlen is always updated to reflect the amount - * of data that has (or would have) been written. - * - * \note Call this function with *dlen = 0 to obtain the - * required buffer size in *dlen - */ -int base64_encode( unsigned char *dst, size_t *dlen, - const unsigned char *src, size_t slen ); - -/** - * \brief Decode a base64-formatted buffer - * - * \param dst destination buffer - * \param dlen size of the buffer - * \param src source buffer - * \param slen amount of data to be decoded - * - * \return 0 if successful, POLARSSL_ERR_BASE64_BUFFER_TOO_SMALL, or - * POLARSSL_ERR_BASE64_INVALID_CHARACTER if the input data is - * not correct. *dlen is always updated to reflect the amount - * of data that has (or would have) been written. - * - * \note Call this function with *dlen = 0 to obtain the - * required buffer size in *dlen - */ -int base64_decode( unsigned char *dst, size_t *dlen, - const unsigned char *src, size_t slen ); - -/** - * \brief Checkup routine - * - * \return 0 if successful, or 1 if the test failed - */ -int base64_self_test( int verbose ); - -#ifdef __cplusplus -} -#endif - -#endif /* base64.h */ diff --git a/lib/libpolarssl/include/polarssl/bignum.h b/lib/libpolarssl/include/polarssl/bignum.h deleted file mode 100644 index afa9e61..0000000 --- a/lib/libpolarssl/include/polarssl/bignum.h +++ /dev/null @@ -1,685 +0,0 @@ -/** - * \file bignum.h - * - * \brief Multi-precision integer library - * - * Copyright (C) 2006-2013, Brainspark B.V. - * - * This file is part of PolarSSL (http://www.polarssl.org) - * Lead Maintainer: Paul Bakker - * - * All rights reserved. - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ -#ifndef POLARSSL_BIGNUM_H -#define POLARSSL_BIGNUM_H - -#include -#include - -#include "config.h" - -#ifdef _MSC_VER -#include -#if (_MSC_VER <= 1200) -typedef signed short int16_t; -typedef unsigned short uint16_t; -#else -typedef INT16 int16_t; -typedef UINT16 uint16_t; -#endif -typedef INT32 int32_t; -typedef INT64 int64_t; -typedef UINT32 uint32_t; -typedef UINT64 uint64_t; -#else -#include -#endif - -#define POLARSSL_ERR_MPI_FILE_IO_ERROR -0x0002 /**< An error occurred while reading from or writing to a file. */ -#define POLARSSL_ERR_MPI_BAD_INPUT_DATA -0x0004 /**< Bad input parameters to function. */ -#define POLARSSL_ERR_MPI_INVALID_CHARACTER -0x0006 /**< There is an invalid character in the digit string. */ -#define POLARSSL_ERR_MPI_BUFFER_TOO_SMALL -0x0008 /**< The buffer is too small to write to. */ -#define POLARSSL_ERR_MPI_NEGATIVE_VALUE -0x000A /**< The input arguments are negative or result in illegal output. */ -#define POLARSSL_ERR_MPI_DIVISION_BY_ZERO -0x000C /**< The input argument for division is zero, which is not allowed. */ -#define POLARSSL_ERR_MPI_NOT_ACCEPTABLE -0x000E /**< The input arguments are not acceptable. */ -#define POLARSSL_ERR_MPI_MALLOC_FAILED -0x0010 /**< Memory allocation failed. */ - -#define MPI_CHK(f) if( ( ret = f ) != 0 ) goto cleanup - -/* - * Maximum size MPIs are allowed to grow to in number of limbs. - */ -#define POLARSSL_MPI_MAX_LIMBS 10000 - -#if !defined(POLARSSL_CONFIG_OPTIONS) -/* - * Maximum window size used for modular exponentiation. Default: 6 - * Minimum value: 1. Maximum value: 6. - * - * Result is an array of ( 2 << POLARSSL_MPI_WINDOW_SIZE ) MPIs used - * for the sliding window calculation. (So 64 by default) - * - * Reduction in size, reduces speed. - */ -#define POLARSSL_MPI_WINDOW_SIZE 6 /**< Maximum windows size used. */ - -/* - * Maximum size of MPIs allowed in bits and bytes for user-MPIs. - * ( Default: 512 bytes => 4096 bits, Maximum tested: 2048 bytes => 16384 bits ) - * - * Note: Calculations can results temporarily in larger MPIs. So the number - * of limbs required (POLARSSL_MPI_MAX_LIMBS) is higher. - */ -#define POLARSSL_MPI_MAX_SIZE 512 /**< Maximum number of bytes for usable MPIs. */ - -#endif /* !POLARSSL_CONFIG_OPTIONS */ - -#define POLARSSL_MPI_MAX_BITS ( 8 * POLARSSL_MPI_MAX_SIZE ) /**< Maximum number of bits for usable MPIs. */ - -/* - * When reading from files with mpi_read_file() and writing to files with - * mpi_write_file() the buffer should have space - * for a (short) label, the MPI (in the provided radix), the newline - * characters and the '\0'. - * - * By default we assume at least a 10 char label, a minimum radix of 10 - * (decimal) and a maximum of 4096 bit numbers (1234 decimal chars). - * Autosized at compile time for at least a 10 char label, a minimum radix - * of 10 (decimal) for a number of POLARSSL_MPI_MAX_BITS size. - * - * This used to be statically sized to 1250 for a maximum of 4096 bit - * numbers (1234 decimal chars). - * - * Calculate using the formula: - * POLARSSL_MPI_RW_BUFFER_SIZE = ceil(POLARSSL_MPI_MAX_BITS / ln(10) * ln(2)) + - * LabelSize + 6 - */ -#define POLARSSL_MPI_MAX_BITS_SCALE100 ( 100 * POLARSSL_MPI_MAX_BITS ) -#define LN_2_DIV_LN_10_SCALE100 332 -#define POLARSSL_MPI_RW_BUFFER_SIZE ( ((POLARSSL_MPI_MAX_BITS_SCALE100 + LN_2_DIV_LN_10_SCALE100 - 1) / LN_2_DIV_LN_10_SCALE100) + 10 + 6 ) - -/* - * Define the base integer type, architecture-wise - */ -#if defined(POLARSSL_HAVE_INT8) -typedef signed char t_sint; -typedef unsigned char t_uint; -typedef uint16_t t_udbl; -#define POLARSSL_HAVE_UDBL -#else -#if defined(POLARSSL_HAVE_INT16) -typedef int16_t t_sint; -typedef uint16_t t_uint; -typedef uint32_t t_udbl; -#define POLARSSL_HAVE_UDBL -#else - #if ( defined(_MSC_VER) && defined(_M_AMD64) ) - typedef int64_t t_sint; - typedef uint64_t t_uint; - #else - #if ( defined(__GNUC__) && ( \ - defined(__amd64__) || defined(__x86_64__) || \ - defined(__ppc64__) || defined(__powerpc64__) || \ - defined(__ia64__) || defined(__alpha__) || \ - (defined(__sparc__) && defined(__arch64__)) || \ - defined(__s390x__) ) ) - typedef int64_t t_sint; - typedef uint64_t t_uint; - typedef unsigned int t_udbl __attribute__((mode(TI))); - #define POLARSSL_HAVE_UDBL - #else - typedef int32_t t_sint; - typedef uint32_t t_uint; - #if ( defined(_MSC_VER) && defined(_M_IX86) ) - typedef uint64_t t_udbl; - #define POLARSSL_HAVE_UDBL - #else - #if defined( POLARSSL_HAVE_LONGLONG ) - typedef unsigned long long t_udbl; - #define POLARSSL_HAVE_UDBL - #endif - #endif - #endif - #endif -#endif /* POLARSSL_HAVE_INT16 */ -#endif /* POLARSSL_HAVE_INT8 */ - -/** - * \brief MPI structure - */ -typedef struct -{ - int s; /*!< integer sign */ - size_t n; /*!< total # of limbs */ - t_uint *p; /*!< pointer to limbs */ -} -mpi; - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \brief Initialize one MPI - * - * \param X One MPI to initialize. - */ -void mpi_init( mpi *X ); - -/** - * \brief Unallocate one MPI - * - * \param X One MPI to unallocate. - */ -void mpi_free( mpi *X ); - -/** - * \brief Enlarge to the specified number of limbs - * - * \param X MPI to grow - * \param nblimbs The target number of limbs - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed - */ -int mpi_grow( mpi *X, size_t nblimbs ); - -/** - * \brief Copy the contents of Y into X - * - * \param X Destination MPI - * \param Y Source MPI - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed - */ -int mpi_copy( mpi *X, const mpi *Y ); - -/** - * \brief Swap the contents of X and Y - * - * \param X First MPI value - * \param Y Second MPI value - */ -void mpi_swap( mpi *X, mpi *Y ); - -/** - * \brief Set value from integer - * - * \param X MPI to set - * \param z Value to use - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed - */ -int mpi_lset( mpi *X, t_sint z ); - -/** - * \brief Get a specific bit from X - * - * \param X MPI to use - * \param pos Zero-based index of the bit in X - * - * \return Either a 0 or a 1 - */ -int mpi_get_bit( const mpi *X, size_t pos ); - -/** - * \brief Set a bit of X to a specific value of 0 or 1 - * - * \note Will grow X if necessary to set a bit to 1 in a not yet - * existing limb. Will not grow if bit should be set to 0 - * - * \param X MPI to use - * \param pos Zero-based index of the bit in X - * \param val The value to set the bit to (0 or 1) - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed, - * POLARSSL_ERR_MPI_BAD_INPUT_DATA if val is not 0 or 1 - */ -int mpi_set_bit( mpi *X, size_t pos, unsigned char val ); - -/** - * \brief Return the number of zero-bits before the least significant - * '1' bit - * - * Note: Thus also the zero-based index of the least significant '1' bit - * - * \param X MPI to use - */ -size_t mpi_lsb( const mpi *X ); - -/** - * \brief Return the number of bits up to and including the most - * significant '1' bit' - * - * Note: Thus also the one-based index of the most significant '1' bit - * - * \param X MPI to use - */ -size_t mpi_msb( const mpi *X ); - -/** - * \brief Return the total size in bytes - * - * \param X MPI to use - */ -size_t mpi_size( const mpi *X ); - -/** - * \brief Import from an ASCII string - * - * \param X Destination MPI - * \param radix Input numeric base - * \param s Null-terminated string buffer - * - * \return 0 if successful, or a POLARSSL_ERR_MPI_XXX error code - */ -int mpi_read_string( mpi *X, int radix, const char *s ); - -/** - * \brief Export into an ASCII string - * - * \param X Source MPI - * \param radix Output numeric base - * \param s String buffer - * \param slen String buffer size - * - * \return 0 if successful, or a POLARSSL_ERR_MPI_XXX error code. - * *slen is always updated to reflect the amount - * of data that has (or would have) been written. - * - * \note Call this function with *slen = 0 to obtain the - * minimum required buffer size in *slen. - */ -int mpi_write_string( const mpi *X, int radix, char *s, size_t *slen ); - -#if defined(POLARSSL_FS_IO) -/** - * \brief Read X from an opened file - * - * \param X Destination MPI - * \param radix Input numeric base - * \param fin Input file handle - * - * \return 0 if successful, POLARSSL_ERR_MPI_BUFFER_TOO_SMALL if - * the file read buffer is too small or a - * POLARSSL_ERR_MPI_XXX error code - */ -int mpi_read_file( mpi *X, int radix, FILE *fin ); - -/** - * \brief Write X into an opened file, or stdout if fout is NULL - * - * \param p Prefix, can be NULL - * \param X Source MPI - * \param radix Output numeric base - * \param fout Output file handle (can be NULL) - * - * \return 0 if successful, or a POLARSSL_ERR_MPI_XXX error code - * - * \note Set fout == NULL to print X on the console. - */ -int mpi_write_file( const char *p, const mpi *X, int radix, FILE *fout ); -#endif /* POLARSSL_FS_IO */ - -/** - * \brief Import X from unsigned binary data, big endian - * - * \param X Destination MPI - * \param buf Input buffer - * \param buflen Input buffer size - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed - */ -int mpi_read_binary( mpi *X, const unsigned char *buf, size_t buflen ); - -/** - * \brief Export X into unsigned binary data, big endian - * - * \param X Source MPI - * \param buf Output buffer - * \param buflen Output buffer size - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_BUFFER_TOO_SMALL if buf isn't large enough - */ -int mpi_write_binary( const mpi *X, unsigned char *buf, size_t buflen ); - -/** - * \brief Left-shift: X <<= count - * - * \param X MPI to shift - * \param count Amount to shift - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed - */ -int mpi_shift_l( mpi *X, size_t count ); - -/** - * \brief Right-shift: X >>= count - * - * \param X MPI to shift - * \param count Amount to shift - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed - */ -int mpi_shift_r( mpi *X, size_t count ); - -/** - * \brief Compare unsigned values - * - * \param X Left-hand MPI - * \param Y Right-hand MPI - * - * \return 1 if |X| is greater than |Y|, - * -1 if |X| is lesser than |Y| or - * 0 if |X| is equal to |Y| - */ -int mpi_cmp_abs( const mpi *X, const mpi *Y ); - -/** - * \brief Compare signed values - * - * \param X Left-hand MPI - * \param Y Right-hand MPI - * - * \return 1 if X is greater than Y, - * -1 if X is lesser than Y or - * 0 if X is equal to Y - */ -int mpi_cmp_mpi( const mpi *X, const mpi *Y ); - -/** - * \brief Compare signed values - * - * \param X Left-hand MPI - * \param z The integer value to compare to - * - * \return 1 if X is greater than z, - * -1 if X is lesser than z or - * 0 if X is equal to z - */ -int mpi_cmp_int( const mpi *X, t_sint z ); - -/** - * \brief Unsigned addition: X = |A| + |B| - * - * \param X Destination MPI - * \param A Left-hand MPI - * \param B Right-hand MPI - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed - */ -int mpi_add_abs( mpi *X, const mpi *A, const mpi *B ); - -/** - * \brief Unsigned substraction: X = |A| - |B| - * - * \param X Destination MPI - * \param A Left-hand MPI - * \param B Right-hand MPI - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_NEGATIVE_VALUE if B is greater than A - */ -int mpi_sub_abs( mpi *X, const mpi *A, const mpi *B ); - -/** - * \brief Signed addition: X = A + B - * - * \param X Destination MPI - * \param A Left-hand MPI - * \param B Right-hand MPI - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed - */ -int mpi_add_mpi( mpi *X, const mpi *A, const mpi *B ); - -/** - * \brief Signed substraction: X = A - B - * - * \param X Destination MPI - * \param A Left-hand MPI - * \param B Right-hand MPI - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed - */ -int mpi_sub_mpi( mpi *X, const mpi *A, const mpi *B ); - -/** - * \brief Signed addition: X = A + b - * - * \param X Destination MPI - * \param A Left-hand MPI - * \param b The integer value to add - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed - */ -int mpi_add_int( mpi *X, const mpi *A, t_sint b ); - -/** - * \brief Signed substraction: X = A - b - * - * \param X Destination MPI - * \param A Left-hand MPI - * \param b The integer value to subtract - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed - */ -int mpi_sub_int( mpi *X, const mpi *A, t_sint b ); - -/** - * \brief Baseline multiplication: X = A * B - * - * \param X Destination MPI - * \param A Left-hand MPI - * \param B Right-hand MPI - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed - */ -int mpi_mul_mpi( mpi *X, const mpi *A, const mpi *B ); - -/** - * \brief Baseline multiplication: X = A * b - * Note: b is an unsigned integer type, thus - * Negative values of b are ignored. - * - * \param X Destination MPI - * \param A Left-hand MPI - * \param b The integer value to multiply with - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed - */ -int mpi_mul_int( mpi *X, const mpi *A, t_sint b ); - -/** - * \brief Division by mpi: A = Q * B + R - * - * \param Q Destination MPI for the quotient - * \param R Destination MPI for the rest value - * \param A Left-hand MPI - * \param B Right-hand MPI - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed, - * POLARSSL_ERR_MPI_DIVISION_BY_ZERO if B == 0 - * - * \note Either Q or R can be NULL. - */ -int mpi_div_mpi( mpi *Q, mpi *R, const mpi *A, const mpi *B ); - -/** - * \brief Division by int: A = Q * b + R - * - * \param Q Destination MPI for the quotient - * \param R Destination MPI for the rest value - * \param A Left-hand MPI - * \param b Integer to divide by - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed, - * POLARSSL_ERR_MPI_DIVISION_BY_ZERO if b == 0 - * - * \note Either Q or R can be NULL. - */ -int mpi_div_int( mpi *Q, mpi *R, const mpi *A, t_sint b ); - -/** - * \brief Modulo: R = A mod B - * - * \param R Destination MPI for the rest value - * \param A Left-hand MPI - * \param B Right-hand MPI - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed, - * POLARSSL_ERR_MPI_DIVISION_BY_ZERO if B == 0, - * POLARSSL_ERR_MPI_NEGATIVE_VALUE if B < 0 - */ -int mpi_mod_mpi( mpi *R, const mpi *A, const mpi *B ); - -/** - * \brief Modulo: r = A mod b - * - * \param r Destination t_uint - * \param A Left-hand MPI - * \param b Integer to divide by - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed, - * POLARSSL_ERR_MPI_DIVISION_BY_ZERO if b == 0, - * POLARSSL_ERR_MPI_NEGATIVE_VALUE if b < 0 - */ -int mpi_mod_int( t_uint *r, const mpi *A, t_sint b ); - -/** - * \brief Sliding-window exponentiation: X = A^E mod N - * - * \param X Destination MPI - * \param A Left-hand MPI - * \param E Exponent MPI - * \param N Modular MPI - * \param _RR Speed-up MPI used for recalculations - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed, - * POLARSSL_ERR_MPI_BAD_INPUT_DATA if N is negative or even or if - * E is negative - * - * \note _RR is used to avoid re-computing R*R mod N across - * multiple calls, which speeds up things a bit. It can - * be set to NULL if the extra performance is unneeded. - */ -int mpi_exp_mod( mpi *X, const mpi *A, const mpi *E, const mpi *N, mpi *_RR ); - -/** - * \brief Fill an MPI X with size bytes of random - * - * \param X Destination MPI - * \param size Size in bytes - * \param f_rng RNG function - * \param p_rng RNG parameter - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed - */ -int mpi_fill_random( mpi *X, size_t size, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng ); - -/** - * \brief Greatest common divisor: G = gcd(A, B) - * - * \param G Destination MPI - * \param A Left-hand MPI - * \param B Right-hand MPI - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed - */ -int mpi_gcd( mpi *G, const mpi *A, const mpi *B ); - -/** - * \brief Modular inverse: X = A^-1 mod N - * - * \param X Destination MPI - * \param A Left-hand MPI - * \param N Right-hand MPI - * - * \return 0 if successful, - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed, - * POLARSSL_ERR_MPI_BAD_INPUT_DATA if N is negative or nil - POLARSSL_ERR_MPI_NOT_ACCEPTABLE if A has no inverse mod N - */ -int mpi_inv_mod( mpi *X, const mpi *A, const mpi *N ); - -/** - * \brief Miller-Rabin primality test - * - * \param X MPI to check - * \param f_rng RNG function - * \param p_rng RNG parameter - * - * \return 0 if successful (probably prime), - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed, - * POLARSSL_ERR_MPI_NOT_ACCEPTABLE if X is not prime - */ -int mpi_is_prime( mpi *X, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng ); - -/** - * \brief Prime number generation - * - * \param X Destination MPI - * \param nbits Required size of X in bits ( 3 <= nbits <= POLARSSL_MPI_MAX_BITS ) - * \param dh_flag If 1, then (X-1)/2 will be prime too - * \param f_rng RNG function - * \param p_rng RNG parameter - * - * \return 0 if successful (probably prime), - * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed, - * POLARSSL_ERR_MPI_BAD_INPUT_DATA if nbits is < 3 - */ -int mpi_gen_prime( mpi *X, size_t nbits, int dh_flag, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng ); - -/** - * \brief Checkup routine - * - * \return 0 if successful, or 1 if the test failed - */ -int mpi_self_test( int verbose ); - -#ifdef __cplusplus -} -#endif - -#endif /* bignum.h */ diff --git a/lib/libpolarssl/include/polarssl/bn_mul.h b/lib/libpolarssl/include/polarssl/bn_mul.h deleted file mode 100644 index 7c7b4f7..0000000 --- a/lib/libpolarssl/include/polarssl/bn_mul.h +++ /dev/null @@ -1,864 +0,0 @@ -/** - * \file bn_mul.h - * - * \brief Multi-precision integer library - * - * Copyright (C) 2006-2010, Brainspark B.V. - * - * This file is part of PolarSSL (http://www.polarssl.org) - * Lead Maintainer: Paul Bakker - * - * All rights reserved. - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ -/* - * Multiply source vector [s] with b, add result - * to destination vector [d] and set carry c. - * - * Currently supports: - * - * . IA-32 (386+) . AMD64 / EM64T - * . IA-32 (SSE2) . Motorola 68000 - * . PowerPC, 32-bit . MicroBlaze - * . PowerPC, 64-bit . TriCore - * . SPARC v8 . ARM v3+ - * . Alpha . MIPS32 - * . C, longlong . C, generic - */ -#ifndef POLARSSL_BN_MUL_H -#define POLARSSL_BN_MUL_H - -#include "bignum.h" - -#if defined(POLARSSL_HAVE_ASM) - -#if defined(__GNUC__) -#if defined(__i386__) - -#define MULADDC_INIT \ - __asm__( " \ - movl %%ebx, %0; \ - movl %5, %%esi; \ - movl %6, %%edi; \ - movl %7, %%ecx; \ - movl %8, %%ebx; \ - " - -#define MULADDC_CORE \ - " \ - lodsl; \ - mull %%ebx; \ - addl %%ecx, %%eax; \ - adcl $0, %%edx; \ - addl (%%edi), %%eax; \ - adcl $0, %%edx; \ - movl %%edx, %%ecx; \ - stosl; \ - " - -#if defined(POLARSSL_HAVE_SSE2) - -#define MULADDC_HUIT \ - " \ - movd %%ecx, %%mm1; \ - movd %%ebx, %%mm0; \ - movd (%%edi), %%mm3; \ - paddq %%mm3, %%mm1; \ - movd (%%esi), %%mm2; \ - pmuludq %%mm0, %%mm2; \ - movd 4(%%esi), %%mm4; \ - pmuludq %%mm0, %%mm4; \ - movd 8(%%esi), %%mm6; \ - pmuludq %%mm0, %%mm6; \ - movd 12(%%esi), %%mm7; \ - pmuludq %%mm0, %%mm7; \ - paddq %%mm2, %%mm1; \ - movd 4(%%edi), %%mm3; \ - paddq %%mm4, %%mm3; \ - movd 8(%%edi), %%mm5; \ - paddq %%mm6, %%mm5; \ - movd 12(%%edi), %%mm4; \ - paddq %%mm4, %%mm7; \ - movd %%mm1, (%%edi); \ - movd 16(%%esi), %%mm2; \ - pmuludq %%mm0, %%mm2; \ - psrlq $32, %%mm1; \ - movd 20(%%esi), %%mm4; \ - pmuludq %%mm0, %%mm4; \ - paddq %%mm3, %%mm1; \ - movd 24(%%esi), %%mm6; \ - pmuludq %%mm0, %%mm6; \ - movd %%mm1, 4(%%edi); \ - psrlq $32, %%mm1; \ - movd 28(%%esi), %%mm3; \ - pmuludq %%mm0, %%mm3; \ - paddq %%mm5, %%mm1; \ - movd 16(%%edi), %%mm5; \ - paddq %%mm5, %%mm2; \ - movd %%mm1, 8(%%edi); \ - psrlq $32, %%mm1; \ - paddq %%mm7, %%mm1; \ - movd 20(%%edi), %%mm5; \ - paddq %%mm5, %%mm4; \ - movd %%mm1, 12(%%edi); \ - psrlq $32, %%mm1; \ - paddq %%mm2, %%mm1; \ - movd 24(%%edi), %%mm5; \ - paddq %%mm5, %%mm6; \ - movd %%mm1, 16(%%edi); \ - psrlq $32, %%mm1; \ - paddq %%mm4, %%mm1; \ - movd 28(%%edi), %%mm5; \ - paddq %%mm5, %%mm3; \ - movd %%mm1, 20(%%edi); \ - psrlq $32, %%mm1; \ - paddq %%mm6, %%mm1; \ - movd %%mm1, 24(%%edi); \ - psrlq $32, %%mm1; \ - paddq %%mm3, %%mm1; \ - movd %%mm1, 28(%%edi); \ - addl $32, %%edi; \ - addl $32, %%esi; \ - psrlq $32, %%mm1; \ - movd %%mm1, %%ecx; \ - " - -#define MULADDC_STOP \ - " \ - emms; \ - movl %4, %%ebx; \ - movl %%ecx, %1; \ - movl %%edi, %2; \ - movl %%esi, %3; \ - " \ - : "=m" (t), "=m" (c), "=m" (d), "=m" (s) \ - : "m" (t), "m" (s), "m" (d), "m" (c), "m" (b) \ - : "eax", "ecx", "edx", "esi", "edi" \ - ); - -#else - -#define MULADDC_STOP \ - " \ - movl %4, %%ebx; \ - movl %%ecx, %1; \ - movl %%edi, %2; \ - movl %%esi, %3; \ - " \ - : "=m" (t), "=m" (c), "=m" (d), "=m" (s) \ - : "m" (t), "m" (s), "m" (d), "m" (c), "m" (b) \ - : "eax", "ecx", "edx", "esi", "edi" \ - ); -#endif /* SSE2 */ -#endif /* i386 */ - -#if defined(__amd64__) || defined (__x86_64__) - -#define MULADDC_INIT \ - __asm__( "movq %0, %%rsi " :: "m" (s)); \ - __asm__( "movq %0, %%rdi " :: "m" (d)); \ - __asm__( "movq %0, %%rcx " :: "m" (c)); \ - __asm__( "movq %0, %%rbx " :: "m" (b)); \ - __asm__( "xorq %r8, %r8 " ); - -#define MULADDC_CORE \ - __asm__( "movq (%rsi),%rax " ); \ - __asm__( "mulq %rbx " ); \ - __asm__( "addq $8, %rsi " ); \ - __asm__( "addq %rcx, %rax " ); \ - __asm__( "movq %r8, %rcx " ); \ - __asm__( "adcq $0, %rdx " ); \ - __asm__( "nop " ); \ - __asm__( "addq %rax, (%rdi) " ); \ - __asm__( "adcq %rdx, %rcx " ); \ - __asm__( "addq $8, %rdi " ); - -#define MULADDC_STOP \ - __asm__( "movq %%rcx, %0 " : "=m" (c)); \ - __asm__( "movq %%rdi, %0 " : "=m" (d)); \ - __asm__( "movq %%rsi, %0 " : "=m" (s) :: \ - "rax", "rcx", "rdx", "rbx", "rsi", "rdi", "r8" ); - -#endif /* AMD64 */ - -#if defined(__mc68020__) || defined(__mcpu32__) - -#define MULADDC_INIT \ - __asm__( "movl %0, %%a2 " :: "m" (s)); \ - __asm__( "movl %0, %%a3 " :: "m" (d)); \ - __asm__( "movl %0, %%d3 " :: "m" (c)); \ - __asm__( "movl %0, %%d2 " :: "m" (b)); \ - __asm__( "moveq #0, %d0 " ); - -#define MULADDC_CORE \ - __asm__( "movel %a2@+, %d1 " ); \ - __asm__( "mulul %d2, %d4:%d1 " ); \ - __asm__( "addl %d3, %d1 " ); \ - __asm__( "addxl %d0, %d4 " ); \ - __asm__( "moveq #0, %d3 " ); \ - __asm__( "addl %d1, %a3@+ " ); \ - __asm__( "addxl %d4, %d3 " ); - -#define MULADDC_STOP \ - __asm__( "movl %%d3, %0 " : "=m" (c)); \ - __asm__( "movl %%a3, %0 " : "=m" (d)); \ - __asm__( "movl %%a2, %0 " : "=m" (s) :: \ - "d0", "d1", "d2", "d3", "d4", "a2", "a3" ); - -#define MULADDC_HUIT \ - __asm__( "movel %a2@+, %d1 " ); \ - __asm__( "mulul %d2, %d4:%d1 " ); \ - __asm__( "addxl %d3, %d1 " ); \ - __asm__( "addxl %d0, %d4 " ); \ - __asm__( "addl %d1, %a3@+ " ); \ - __asm__( "movel %a2@+, %d1 " ); \ - __asm__( "mulul %d2, %d3:%d1 " ); \ - __asm__( "addxl %d4, %d1 " ); \ - __asm__( "addxl %d0, %d3 " ); \ - __asm__( "addl %d1, %a3@+ " ); \ - __asm__( "movel %a2@+, %d1 " ); \ - __asm__( "mulul %d2, %d4:%d1 " ); \ - __asm__( "addxl %d3, %d1 " ); \ - __asm__( "addxl %d0, %d4 " ); \ - __asm__( "addl %d1, %a3@+ " ); \ - __asm__( "movel %a2@+, %d1 " ); \ - __asm__( "mulul %d2, %d3:%d1 " ); \ - __asm__( "addxl %d4, %d1 " ); \ - __asm__( "addxl %d0, %d3 " ); \ - __asm__( "addl %d1, %a3@+ " ); \ - __asm__( "movel %a2@+, %d1 " ); \ - __asm__( "mulul %d2, %d4:%d1 " ); \ - __asm__( "addxl %d3, %d1 " ); \ - __asm__( "addxl %d0, %d4 " ); \ - __asm__( "addl %d1, %a3@+ " ); \ - __asm__( "movel %a2@+, %d1 " ); \ - __asm__( "mulul %d2, %d3:%d1 " ); \ - __asm__( "addxl %d4, %d1 " ); \ - __asm__( "addxl %d0, %d3 " ); \ - __asm__( "addl %d1, %a3@+ " ); \ - __asm__( "movel %a2@+, %d1 " ); \ - __asm__( "mulul %d2, %d4:%d1 " ); \ - __asm__( "addxl %d3, %d1 " ); \ - __asm__( "addxl %d0, %d4 " ); \ - __asm__( "addl %d1, %a3@+ " ); \ - __asm__( "movel %a2@+, %d1 " ); \ - __asm__( "mulul %d2, %d3:%d1 " ); \ - __asm__( "addxl %d4, %d1 " ); \ - __asm__( "addxl %d0, %d3 " ); \ - __asm__( "addl %d1, %a3@+ " ); \ - __asm__( "addxl %d0, %d3 " ); - -#endif /* MC68000 */ - -#if defined(__powerpc__) || defined(__ppc__) -#if defined(__powerpc64__) || defined(__ppc64__) - -#if defined(__MACH__) && defined(__APPLE__) - -#define MULADDC_INIT \ - __asm__( "ld r3, %0 " :: "m" (s)); \ - __asm__( "ld r4, %0 " :: "m" (d)); \ - __asm__( "ld r5, %0 " :: "m" (c)); \ - __asm__( "ld r6, %0 " :: "m" (b)); \ - __asm__( "addi r3, r3, -8 " ); \ - __asm__( "addi r4, r4, -8 " ); \ - __asm__( "addic r5, r5, 0 " ); - -#define MULADDC_CORE \ - __asm__( "ldu r7, 8(r3) " ); \ - __asm__( "mulld r8, r7, r6 " ); \ - __asm__( "mulhdu r9, r7, r6 " ); \ - __asm__( "adde r8, r8, r5 " ); \ - __asm__( "ld r7, 8(r4) " ); \ - __asm__( "addze r5, r9 " ); \ - __asm__( "addc r8, r8, r7 " ); \ - __asm__( "stdu r8, 8(r4) " ); - -#define MULADDC_STOP \ - __asm__( "addze r5, r5 " ); \ - __asm__( "addi r4, r4, 8 " ); \ - __asm__( "addi r3, r3, 8 " ); \ - __asm__( "std r5, %0 " : "=m" (c)); \ - __asm__( "std r4, %0 " : "=m" (d)); \ - __asm__( "std r3, %0 " : "=m" (s) :: \ - "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); - -#else - -#define MULADDC_INIT \ - __asm__( "ld %%r3, %0 " :: "m" (s)); \ - __asm__( "ld %%r4, %0 " :: "m" (d)); \ - __asm__( "ld %%r5, %0 " :: "m" (c)); \ - __asm__( "ld %%r6, %0 " :: "m" (b)); \ - __asm__( "addi %r3, %r3, -8 " ); \ - __asm__( "addi %r4, %r4, -8 " ); \ - __asm__( "addic %r5, %r5, 0 " ); - -#define MULADDC_CORE \ - __asm__( "ldu %r7, 8(%r3) " ); \ - __asm__( "mulld %r8, %r7, %r6 " ); \ - __asm__( "mulhdu %r9, %r7, %r6 " ); \ - __asm__( "adde %r8, %r8, %r5 " ); \ - __asm__( "ld %r7, 8(%r4) " ); \ - __asm__( "addze %r5, %r9 " ); \ - __asm__( "addc %r8, %r8, %r7 " ); \ - __asm__( "stdu %r8, 8(%r4) " ); - -#define MULADDC_STOP \ - __asm__( "addze %r5, %r5 " ); \ - __asm__( "addi %r4, %r4, 8 " ); \ - __asm__( "addi %r3, %r3, 8 " ); \ - __asm__( "std %%r5, %0 " : "=m" (c)); \ - __asm__( "std %%r4, %0 " : "=m" (d)); \ - __asm__( "std %%r3, %0 " : "=m" (s) :: \ - "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); - -#endif - -#else /* PPC32 */ - -#if defined(__MACH__) && defined(__APPLE__) - -#define MULADDC_INIT \ - __asm__( "lwz r3, %0 " :: "m" (s)); \ - __asm__( "lwz r4, %0 " :: "m" (d)); \ - __asm__( "lwz r5, %0 " :: "m" (c)); \ - __asm__( "lwz r6, %0 " :: "m" (b)); \ - __asm__( "addi r3, r3, -4 " ); \ - __asm__( "addi r4, r4, -4 " ); \ - __asm__( "addic r5, r5, 0 " ); - -#define MULADDC_CORE \ - __asm__( "lwzu r7, 4(r3) " ); \ - __asm__( "mullw r8, r7, r6 " ); \ - __asm__( "mulhwu r9, r7, r6 " ); \ - __asm__( "adde r8, r8, r5 " ); \ - __asm__( "lwz r7, 4(r4) " ); \ - __asm__( "addze r5, r9 " ); \ - __asm__( "addc r8, r8, r7 " ); \ - __asm__( "stwu r8, 4(r4) " ); - -#define MULADDC_STOP \ - __asm__( "addze r5, r5 " ); \ - __asm__( "addi r4, r4, 4 " ); \ - __asm__( "addi r3, r3, 4 " ); \ - __asm__( "stw r5, %0 " : "=m" (c)); \ - __asm__( "stw r4, %0 " : "=m" (d)); \ - __asm__( "stw r3, %0 " : "=m" (s) :: \ - "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); - -#else - -#define MULADDC_INIT \ - __asm__( "lwz %%r3, %0 " :: "m" (s)); \ - __asm__( "lwz %%r4, %0 " :: "m" (d)); \ - __asm__( "lwz %%r5, %0 " :: "m" (c)); \ - __asm__( "lwz %%r6, %0 " :: "m" (b)); \ - __asm__( "addi %r3, %r3, -4 " ); \ - __asm__( "addi %r4, %r4, -4 " ); \ - __asm__( "addic %r5, %r5, 0 " ); - -#define MULADDC_CORE \ - __asm__( "lwzu %r7, 4(%r3) " ); \ - __asm__( "mullw %r8, %r7, %r6 " ); \ - __asm__( "mulhwu %r9, %r7, %r6 " ); \ - __asm__( "adde %r8, %r8, %r5 " ); \ - __asm__( "lwz %r7, 4(%r4) " ); \ - __asm__( "addze %r5, %r9 " ); \ - __asm__( "addc %r8, %r8, %r7 " ); \ - __asm__( "stwu %r8, 4(%r4) " ); - -#define MULADDC_STOP \ - __asm__( "addze %r5, %r5 " ); \ - __asm__( "addi %r4, %r4, 4 " ); \ - __asm__( "addi %r3, %r3, 4 " ); \ - __asm__( "stw %%r5, %0 " : "=m" (c)); \ - __asm__( "stw %%r4, %0 " : "=m" (d)); \ - __asm__( "stw %%r3, %0 " : "=m" (s) :: \ - "r3", "r4", "r5", "r6", "r7", "r8", "r9" ); - -#endif - -#endif /* PPC32 */ -#endif /* PPC64 */ - -#if defined(__sparc__) && defined(__sparc64__) - -#define MULADDC_INIT \ - __asm__( \ - " \ - ldx %3, %%o0; \ - ldx %4, %%o1; \ - ld %5, %%o2; \ - ld %6, %%o3; \ - " - -#define MULADDC_CORE \ - " \ - ld [%%o0], %%o4; \ - inc 4, %%o0; \ - ld [%%o1], %%o5; \ - umul %%o3, %%o4, %%o4; \ - addcc %%o4, %%o2, %%o4; \ - rd %%y, %%g1; \ - addx %%g1, 0, %%g1; \ - addcc %%o4, %%o5, %%o4; \ - st %%o4, [%%o1]; \ - addx %%g1, 0, %%o2; \ - inc 4, %%o1; \ - " - -#define MULADDC_STOP \ - " \ - st %%o2, %0; \ - stx %%o1, %1; \ - stx %%o0, %2; \ - " \ - : "=m" (c), "=m" (d), "=m" (s) \ - : "m" (s), "m" (d), "m" (c), "m" (b) \ - : "g1", "o0", "o1", "o2", "o3", "o4", \ - "o5" \ - ); -#endif /* SPARCv9 */ - -#if defined(__sparc__) && !defined(__sparc64__) - -#define MULADDC_INIT \ - __asm__( \ - " \ - ld %3, %%o0; \ - ld %4, %%o1; \ - ld %5, %%o2; \ - ld %6, %%o3; \ - " - -#define MULADDC_CORE \ - " \ - ld [%%o0], %%o4; \ - inc 4, %%o0; \ - ld [%%o1], %%o5; \ - umul %%o3, %%o4, %%o4; \ - addcc %%o4, %%o2, %%o4; \ - rd %%y, %%g1; \ - addx %%g1, 0, %%g1; \ - addcc %%o4, %%o5, %%o4; \ - st %%o4, [%%o1]; \ - addx %%g1, 0, %%o2; \ - inc 4, %%o1; \ - " - -#define MULADDC_STOP \ - " \ - st %%o2, %0; \ - st %%o1, %1; \ - st %%o0, %2; \ - " \ - : "=m" (c), "=m" (d), "=m" (s) \ - : "m" (s), "m" (d), "m" (c), "m" (b) \ - : "g1", "o0", "o1", "o2", "o3", "o4", \ - "o5" \ - ); - -#endif /* SPARCv8 */ - -#if defined(__microblaze__) || defined(microblaze) - -#define MULADDC_INIT \ - __asm__( "lwi r3, %0 " :: "m" (s)); \ - __asm__( "lwi r4, %0 " :: "m" (d)); \ - __asm__( "lwi r5, %0 " :: "m" (c)); \ - __asm__( "lwi r6, %0 " :: "m" (b)); \ - __asm__( "andi r7, r6, 0xffff" ); \ - __asm__( "bsrli r6, r6, 16 " ); - -#define MULADDC_CORE \ - __asm__( "lhui r8, r3, 0 " ); \ - __asm__( "addi r3, r3, 2 " ); \ - __asm__( "lhui r9, r3, 0 " ); \ - __asm__( "addi r3, r3, 2 " ); \ - __asm__( "mul r10, r9, r6 " ); \ - __asm__( "mul r11, r8, r7 " ); \ - __asm__( "mul r12, r9, r7 " ); \ - __asm__( "mul r13, r8, r6 " ); \ - __asm__( "bsrli r8, r10, 16 " ); \ - __asm__( "bsrli r9, r11, 16 " ); \ - __asm__( "add r13, r13, r8 " ); \ - __asm__( "add r13, r13, r9 " ); \ - __asm__( "bslli r10, r10, 16 " ); \ - __asm__( "bslli r11, r11, 16 " ); \ - __asm__( "add r12, r12, r10 " ); \ - __asm__( "addc r13, r13, r0 " ); \ - __asm__( "add r12, r12, r11 " ); \ - __asm__( "addc r13, r13, r0 " ); \ - __asm__( "lwi r10, r4, 0 " ); \ - __asm__( "add r12, r12, r10 " ); \ - __asm__( "addc r13, r13, r0 " ); \ - __asm__( "add r12, r12, r5 " ); \ - __asm__( "addc r5, r13, r0 " ); \ - __asm__( "swi r12, r4, 0 " ); \ - __asm__( "addi r4, r4, 4 " ); - -#define MULADDC_STOP \ - __asm__( "swi r5, %0 " : "=m" (c)); \ - __asm__( "swi r4, %0 " : "=m" (d)); \ - __asm__( "swi r3, %0 " : "=m" (s) :: \ - "r3", "r4" , "r5" , "r6" , "r7" , "r8" , \ - "r9", "r10", "r11", "r12", "r13" ); - -#endif /* MicroBlaze */ - -#if defined(__tricore__) - -#define MULADDC_INIT \ - __asm__( "ld.a %%a2, %0 " :: "m" (s)); \ - __asm__( "ld.a %%a3, %0 " :: "m" (d)); \ - __asm__( "ld.w %%d4, %0 " :: "m" (c)); \ - __asm__( "ld.w %%d1, %0 " :: "m" (b)); \ - __asm__( "xor %d5, %d5 " ); - -#define MULADDC_CORE \ - __asm__( "ld.w %d0, [%a2+] " ); \ - __asm__( "madd.u %e2, %e4, %d0, %d1 " ); \ - __asm__( "ld.w %d0, [%a3] " ); \ - __asm__( "addx %d2, %d2, %d0 " ); \ - __asm__( "addc %d3, %d3, 0 " ); \ - __asm__( "mov %d4, %d3 " ); \ - __asm__( "st.w [%a3+], %d2 " ); - -#define MULADDC_STOP \ - __asm__( "st.w %0, %%d4 " : "=m" (c)); \ - __asm__( "st.a %0, %%a3 " : "=m" (d)); \ - __asm__( "st.a %0, %%a2 " : "=m" (s) :: \ - "d0", "d1", "e2", "d4", "a2", "a3" ); - -#endif /* TriCore */ - -#if defined(__arm__) - -#if defined(__thumb__) && !defined(__thumb2__) - -#define MULADDC_INIT \ - __asm__( \ - " \ - ldr r0, %3; \ - ldr r1, %4; \ - ldr r2, %5; \ - ldr r3, %6; \ - lsr r7, r3, #16; \ - mov r9, r7; \ - lsl r7, r3, #16; \ - lsr r7, r7, #16; \ - mov r8, r7; \ - " - -#define MULADDC_CORE \ - " \ - ldmia r0!, {r6}; \ - lsr r7, r6, #16; \ - lsl r6, r6, #16; \ - lsr r6, r6, #16; \ - mov r4, r8; \ - mul r4, r6; \ - mov r3, r9; \ - mul r6, r3; \ - mov r5, r9; \ - mul r5, r7; \ - mov r3, r8; \ - mul r7, r3; \ - lsr r3, r6, #16; \ - add r5, r5, r3; \ - lsr r3, r7, #16; \ - add r5, r5, r3; \ - add r4, r4, r2; \ - mov r2, #0; \ - adc r5, r2; \ - lsl r3, r6, #16; \ - add r4, r4, r3; \ - adc r5, r2; \ - lsl r3, r7, #16; \ - add r4, r4, r3; \ - adc r5, r2; \ - ldr r3, [r1]; \ - add r4, r4, r3; \ - adc r2, r5; \ - stmia r1!, {r4}; \ - " - -#define MULADDC_STOP \ - " \ - str r2, %0; \ - str r1, %1; \ - str r0, %2; \ - " \ - : "=m" (c), "=m" (d), "=m" (s) \ - : "m" (s), "m" (d), "m" (c), "m" (b) \ - : "r0", "r1", "r2", "r3", "r4", "r5", \ - "r6", "r7", "r8", "r9", "cc" \ - ); - -#else - -#define MULADDC_INIT \ - __asm__( \ - " \ - ldr r0, %3; \ - ldr r1, %4; \ - ldr r2, %5; \ - ldr r3, %6; \ - " - -#define MULADDC_CORE \ - " \ - ldr r4, [r0], #4; \ - mov r5, #0; \ - ldr r6, [r1]; \ - umlal r2, r5, r3, r4; \ - adds r7, r6, r2; \ - adc r2, r5, #0; \ - str r7, [r1], #4; \ - " - -#define MULADDC_STOP \ - " \ - str r2, %0; \ - str r1, %1; \ - str r0, %2; \ - " \ - : "=m" (c), "=m" (d), "=m" (s) \ - : "m" (s), "m" (d), "m" (c), "m" (b) \ - : "r0", "r1", "r2", "r3", "r4", "r5", \ - "r6", "r7", "cc" \ - ); - -#endif /* Thumb */ - -#endif /* ARMv3 */ - -#if defined(__alpha__) - -#define MULADDC_INIT \ - __asm__( "ldq $1, %0 " :: "m" (s)); \ - __asm__( "ldq $2, %0 " :: "m" (d)); \ - __asm__( "ldq $3, %0 " :: "m" (c)); \ - __asm__( "ldq $4, %0 " :: "m" (b)); - -#define MULADDC_CORE \ - __asm__( "ldq $6, 0($1) " ); \ - __asm__( "addq $1, 8, $1 " ); \ - __asm__( "mulq $6, $4, $7 " ); \ - __asm__( "umulh $6, $4, $6 " ); \ - __asm__( "addq $7, $3, $7 " ); \ - __asm__( "cmpult $7, $3, $3 " ); \ - __asm__( "ldq $5, 0($2) " ); \ - __asm__( "addq $7, $5, $7 " ); \ - __asm__( "cmpult $7, $5, $5 " ); \ - __asm__( "stq $7, 0($2) " ); \ - __asm__( "addq $2, 8, $2 " ); \ - __asm__( "addq $6, $3, $3 " ); \ - __asm__( "addq $5, $3, $3 " ); - -#define MULADDC_STOP \ - __asm__( "stq $3, %0 " : "=m" (c)); \ - __asm__( "stq $2, %0 " : "=m" (d)); \ - __asm__( "stq $1, %0 " : "=m" (s) :: \ - "$1", "$2", "$3", "$4", "$5", "$6", "$7" ); - -#endif /* Alpha */ - -#if defined(__mips__) - -#define MULADDC_INIT \ - __asm__( "lw $10, %0 " :: "m" (s)); \ - __asm__( "lw $11, %0 " :: "m" (d)); \ - __asm__( "lw $12, %0 " :: "m" (c)); \ - __asm__( "lw $13, %0 " :: "m" (b)); - -#define MULADDC_CORE \ - __asm__( "lw $14, 0($10) " ); \ - __asm__( "multu $13, $14 " ); \ - __asm__( "addi $10, $10, 4 " ); \ - __asm__( "mflo $14 " ); \ - __asm__( "mfhi $9 " ); \ - __asm__( "addu $14, $12, $14 " ); \ - __asm__( "lw $15, 0($11) " ); \ - __asm__( "sltu $12, $14, $12 " ); \ - __asm__( "addu $15, $14, $15 " ); \ - __asm__( "sltu $14, $15, $14 " ); \ - __asm__( "addu $12, $12, $9 " ); \ - __asm__( "sw $15, 0($11) " ); \ - __asm__( "addu $12, $12, $14 " ); \ - __asm__( "addi $11, $11, 4 " ); - -#define MULADDC_STOP \ - __asm__( "sw $12, %0 " : "=m" (c)); \ - __asm__( "sw $11, %0 " : "=m" (d)); \ - __asm__( "sw $10, %0 " : "=m" (s) :: \ - "$9", "$10", "$11", "$12", "$13", "$14", "$15" ); - -#endif /* MIPS */ -#endif /* GNUC */ - -#if (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__) - -#define MULADDC_INIT \ - ____asm__ mov esi, s \ - ____asm__ mov edi, d \ - ____asm__ mov ecx, c \ - ____asm__ mov ebx, b - -#define MULADDC_CORE \ - ____asm__ lodsd \ - ____asm__ mul ebx \ - ____asm__ add eax, ecx \ - ____asm__ adc edx, 0 \ - ____asm__ add eax, [edi] \ - ____asm__ adc edx, 0 \ - ____asm__ mov ecx, edx \ - ____asm__ stosd - -#if defined(POLARSSL_HAVE_SSE2) - -#define EMIT ____asm__ _emit - -#define MULADDC_HUIT \ - EMIT 0x0F EMIT 0x6E EMIT 0xC9 \ - EMIT 0x0F EMIT 0x6E EMIT 0xC3 \ - EMIT 0x0F EMIT 0x6E EMIT 0x1F \ - EMIT 0x0F EMIT 0xD4 EMIT 0xCB \ - EMIT 0x0F EMIT 0x6E EMIT 0x16 \ - EMIT 0x0F EMIT 0xF4 EMIT 0xD0 \ - EMIT 0x0F EMIT 0x6E EMIT 0x66 EMIT 0x04 \ - EMIT 0x0F EMIT 0xF4 EMIT 0xE0 \ - EMIT 0x0F EMIT 0x6E EMIT 0x76 EMIT 0x08 \ - EMIT 0x0F EMIT 0xF4 EMIT 0xF0 \ - EMIT 0x0F EMIT 0x6E EMIT 0x7E EMIT 0x0C \ - EMIT 0x0F EMIT 0xF4 EMIT 0xF8 \ - EMIT 0x0F EMIT 0xD4 EMIT 0xCA \ - EMIT 0x0F EMIT 0x6E EMIT 0x5F EMIT 0x04 \ - EMIT 0x0F EMIT 0xD4 EMIT 0xDC \ - EMIT 0x0F EMIT 0x6E EMIT 0x6F EMIT 0x08 \ - EMIT 0x0F EMIT 0xD4 EMIT 0xEE \ - EMIT 0x0F EMIT 0x6E EMIT 0x67 EMIT 0x0C \ - EMIT 0x0F EMIT 0xD4 EMIT 0xFC \ - EMIT 0x0F EMIT 0x7E EMIT 0x0F \ - EMIT 0x0F EMIT 0x6E EMIT 0x56 EMIT 0x10 \ - EMIT 0x0F EMIT 0xF4 EMIT 0xD0 \ - EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \ - EMIT 0x0F EMIT 0x6E EMIT 0x66 EMIT 0x14 \ - EMIT 0x0F EMIT 0xF4 EMIT 0xE0 \ - EMIT 0x0F EMIT 0xD4 EMIT 0xCB \ - EMIT 0x0F EMIT 0x6E EMIT 0x76 EMIT 0x18 \ - EMIT 0x0F EMIT 0xF4 EMIT 0xF0 \ - EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x04 \ - EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \ - EMIT 0x0F EMIT 0x6E EMIT 0x5E EMIT 0x1C \ - EMIT 0x0F EMIT 0xF4 EMIT 0xD8 \ - EMIT 0x0F EMIT 0xD4 EMIT 0xCD \ - EMIT 0x0F EMIT 0x6E EMIT 0x6F EMIT 0x10 \ - EMIT 0x0F EMIT 0xD4 EMIT 0xD5 \ - EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x08 \ - EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \ - EMIT 0x0F EMIT 0xD4 EMIT 0xCF \ - EMIT 0x0F EMIT 0x6E EMIT 0x6F EMIT 0x14 \ - EMIT 0x0F EMIT 0xD4 EMIT 0xE5 \ - EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x0C \ - EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \ - EMIT 0x0F EMIT 0xD4 EMIT 0xCA \ - EMIT 0x0F EMIT 0x6E EMIT 0x6F EMIT 0x18 \ - EMIT 0x0F EMIT 0xD4 EMIT 0xF5 \ - EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x10 \ - EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \ - EMIT 0x0F EMIT 0xD4 EMIT 0xCC \ - EMIT 0x0F EMIT 0x6E EMIT 0x6F EMIT 0x1C \ - EMIT 0x0F EMIT 0xD4 EMIT 0xDD \ - EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x14 \ - EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \ - EMIT 0x0F EMIT 0xD4 EMIT 0xCE \ - EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x18 \ - EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \ - EMIT 0x0F EMIT 0xD4 EMIT 0xCB \ - EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x1C \ - EMIT 0x83 EMIT 0xC7 EMIT 0x20 \ - EMIT 0x83 EMIT 0xC6 EMIT 0x20 \ - EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \ - EMIT 0x0F EMIT 0x7E EMIT 0xC9 - -#define MULADDC_STOP \ - EMIT 0x0F EMIT 0x77 \ - ____asm__ mov c, ecx \ - ____asm__ mov d, edi \ - ____asm__ mov s, esi \ - -#else - -#define MULADDC_STOP \ - ____asm__ mov c, ecx \ - ____asm__ mov d, edi \ - ____asm__ mov s, esi \ - -#endif /* SSE2 */ -#endif /* MSVC */ - -#endif /* POLARSSL_HAVE_ASM */ - -#if !defined(MULADDC_CORE) -#if defined(POLARSSL_HAVE_UDBL) - -#define MULADDC_INIT \ -{ \ - t_udbl r; \ - t_uint r0, r1; - -#define MULADDC_CORE \ - r = *(s++) * (t_udbl) b; \ - r0 = r; \ - r1 = r >> biL; \ - r0 += c; r1 += (r0 < c); \ - r0 += *d; r1 += (r0 < *d); \ - c = r1; *(d++) = r0; - -#define MULADDC_STOP \ -} - -#else -#define MULADDC_INIT \ -{ \ - t_uint s0, s1, b0, b1; \ - t_uint r0, r1, rx, ry; \ - b0 = ( b << biH ) >> biH; \ - b1 = ( b >> biH ); - -#define MULADDC_CORE \ - s0 = ( *s << biH ) >> biH; \ - s1 = ( *s >> biH ); s++; \ - rx = s0 * b1; r0 = s0 * b0; \ - ry = s1 * b0; r1 = s1 * b1; \ - r1 += ( rx >> biH ); \ - r1 += ( ry >> biH ); \ - rx <<= biH; ry <<= biH; \ - r0 += rx; r1 += (r0 < rx); \ - r0 += ry; r1 += (r0 < ry); \ - r0 += c; r1 += (r0 < c); \ - r0 += *d; r1 += (r0 < *d); \ - c = r1; *(d++) = r0; - -#define MULADDC_STOP \ -} - -#endif /* C (generic) */ -#endif /* C (longlong) */ - -#endif /* bn_mul.h */ diff --git a/lib/libpolarssl/include/polarssl/config.h b/lib/libpolarssl/include/polarssl/config.h deleted file mode 100644 index 035238b..0000000 --- a/lib/libpolarssl/include/polarssl/config.h +++ /dev/null @@ -1,1013 +0,0 @@ -/** - * \file config.h - * - * \brief Configuration options (set of defines) - * - * Copyright (C) 2006-2013, Brainspark B.V. - * - * This file is part of PolarSSL (http://www.polarssl.org) - * Lead Maintainer: Paul Bakker - * - * All rights reserved. - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * - * This set of compile-time options may be used to enable - * or disable features selectively, and reduce the global - * memory footprint. - */ -#ifndef POLARSSL_CONFIG_H -#define POLARSSL_CONFIG_H - -#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) -#define _CRT_SECURE_NO_DEPRECATE 1 -#endif - -/** - * \name SECTION: System support - * - * This section sets system specific settings. - * \{ - */ - -/** - * \def POLARSSL_HAVE_INT8 - * - * The system uses 8-bit wide native integers. - * - * Uncomment if native integers are 8-bit wide. -#define POLARSSL_HAVE_INT8 - */ - -/** - * \def POLARSSL_HAVE_INT16 - * - * The system uses 16-bit wide native integers. - * - * Uncomment if native integers are 16-bit wide. -#define POLARSSL_HAVE_INT16 - */ - -/** - * \def POLARSSL_HAVE_LONGLONG - * - * The compiler supports the 'long long' type. - * (Only used on 32-bit platforms) - */ -#define POLARSSL_HAVE_LONGLONG - -/** - * \def POLARSSL_HAVE_ASM - * - * The compiler has support for asm() - * - * Uncomment to enable the use of assembly code. - * - * Requires support for asm() in compiler. - * - * Used in: - * library/timing.c - * library/padlock.c - * include/polarssl/bn_mul.h - * - */ -//#define POLARSSL_HAVE_ASM - -/** - * \def POLARSSL_HAVE_SSE2 - * - * CPU supports SSE2 instruction set. - * - * Uncomment if the CPU supports SSE2 (IA-32 specific). - * -#define POLARSSL_HAVE_SSE2 - */ -/* \} name */ - -/** - * \name SECTION: PolarSSL feature support - * - * This section sets support for features that are or are not needed - * within the modules that are enabled. - * \{ - */ - -/** - * \def POLARSSL_XXX_ALT - * - * Uncomment a macro to let PolarSSL use your alternate core implementation of - * a symmetric or hash algorithm (e.g. platform specific assembly optimized - * implementations). Keep in mind that the function prototypes should remain - * the same. - * - * Example: In case you uncomment POLARSSL_AES_ALT, PolarSSL will no longer - * provide the "struct aes_context" definition and omit the base function - * declarations and implementations. "aes_alt.h" will be included from - * "aes.h" to include the new function definitions. - * - * Uncomment a macro to enable alternate implementation for core algorithm - * functions -#define POLARSSL_AES_ALT -#define POLARSSL_ARC4_ALT -#define POLARSSL_BLOWFISH_ALT -#define POLARSSL_CAMELLIA_ALT -#define POLARSSL_DES_ALT -#define POLARSSL_XTEA_ALT -#define POLARSSL_MD2_ALT -#define POLARSSL_MD4_ALT -#define POLARSSL_MD5_ALT -#define POLARSSL_SHA1_ALT -#define POLARSSL_SHA2_ALT -#define POLARSSL_SHA4_ALT - */ - -/** - * \def POLARSSL_AES_ROM_TABLES - * - * Store the AES tables in ROM. - * - * Uncomment this macro to store the AES tables in ROM. - * -#define POLARSSL_AES_ROM_TABLES - */ - -/** - * \def POLARSSL_CIPHER_MODE_CFB - * - * Enable Cipher Feedback mode (CFB) for symmetric ciphers. - */ -//#define POLARSSL_CIPHER_MODE_CFB - -/** - * \def POLARSSL_CIPHER_MODE_CTR - * - * Enable Counter Block Cipher mode (CTR) for symmetric ciphers. - */ -#define POLARSSL_CIPHER_MODE_CTR - -/** - * \def POLARSSL_CIPHER_NULL_CIPHER - * - * Enable NULL cipher. - * Warning: Only do so when you know what you are doing. This allows for - * encryption or channels without any security! - * - * Requires POLARSSL_ENABLE_WEAK_CIPHERSUITES as well to enable - * the following ciphersuites: - * TLS_RSA_WITH_NULL_MD5 - * TLS_RSA_WITH_NULL_SHA - * TLS_RSA_WITH_NULL_SHA256 - * - * Uncomment this macro to enable the NULL cipher and ciphersuites -#define POLARSSL_CIPHER_NULL_CIPHER - */ - -/** - * \def POLARSSL_ENABLE_WEAK_CIPHERSUITES - * - * Enable weak ciphersuites in SSL / TLS - * Warning: Only do so when you know what you are doing. This allows for - * channels with virtually no security at all! - * - * This enables the following ciphersuites: - * TLS_RSA_WITH_DES_CBC_SHA - * TLS_DHE_RSA_WITH_DES_CBC_SHA - * - * Uncomment this macro to enable weak ciphersuites -#define POLARSSL_ENABLE_WEAK_CIPHERSUITES - */ - -/** - * \def POLARSSL_ERROR_STRERROR_DUMMY - * - * Enable a dummy error function to make use of error_strerror() in - * third party libraries easier. - * - * Disable if you run into name conflicts and want to really remove the - * error_strerror() - */ -//#define POLARSSL_ERROR_STRERROR_DUMMY - -/** - * \def POLARSSL_GENPRIME - * - * Requires: POLARSSL_BIGNUM_C, POLARSSL_RSA_C - * - * Enable the RSA prime-number generation code. - */ -//#define POLARSSL_GENPRIME - -/** - * \def POLARSSL_FS_IO - * - * Enable functions that use the filesystem. - */ -//#define POLARSSL_FS_IO - -/** - * \def POLARSSL_NO_DEFAULT_ENTROPY_SOURCES - * - * Do not add default entropy sources. These are the platform specific, - * hardclock and HAVEGE based poll functions. - * - * This is useful to have more control over the added entropy sources in an - * application. - * - * Uncomment this macro to prevent loading of default entropy functions. -#define POLARSSL_NO_DEFAULT_ENTROPY_SOURCES - */ - -/** - * \def POLARSSL_NO_PLATFORM_ENTROPY - * - * Do not use built-in platform entropy functions. - * This is useful if your platform does not support - * standards like the /dev/urandom or Windows CryptoAPI. - * - * Uncomment this macro to disable the built-in platform entropy functions. -#define POLARSSL_NO_PLATFORM_ENTROPY - */ - -/** - * \def POLARSSL_PKCS1_V21 - * - * Requires: POLARSSL_MD_C, POLARSSL_RSA_C - * - * Enable support for PKCS#1 v2.1 encoding. - * This enables support for RSAES-OAEP and RSASSA-PSS operations. - */ -#define POLARSSL_PKCS1_V21 - -/** - * \def POLARSSL_RSA_NO_CRT - * - * Do not use the Chinese Remainder Theorem for the RSA private operation. - * - * Uncomment this macro to disable the use of CRT in RSA. - * - */ -#define POLARSSL_RSA_NO_CRT - - -/** - * \def POLARSSL_SELF_TEST - * - * Enable the checkup functions (*_self_test). - */ -//#define POLARSSL_SELF_TEST - -/** - * \def POLARSSL_SSL_ALL_ALERT_MESSAGES - * - * Enable sending of alert messages in case of encountered errors as per RFC. - * If you choose not to send the alert messages, PolarSSL can still communicate - * with other servers, only debugging of failures is harder. - * - * The advantage of not sending alert messages, is that no information is given - * about reasons for failures thus preventing adversaries of gaining intel. - * - * Enable sending of all alert messages - */ -//#define POLARSSL_SSL_ALERT_MESSAGES - -/** - * \def POLARSSL_SSL_DEBUG_ALL - * - * Enable the debug messages in SSL module for all issues. - * Debug messages have been disabled in some places to prevent timing - * attacks due to (unbalanced) debugging function calls. - * - * If you need all error reporting you should enable this during debugging, - * but remove this for production servers that should log as well. - * - * Uncomment this macro to report all debug messages on errors introducing - * a timing side-channel. - * -#define POLARSSL_SSL_DEBUG_ALL - */ - -/** - * \def POLARSSL_SSL_HW_RECORD_ACCEL - * - * Enable hooking functions in SSL module for hardware acceleration of - * individual records. - * - * Uncomment this macro to enable hooking functions. -#define POLARSSL_SSL_HW_RECORD_ACCEL - */ - -/** - * \def POLARSSL_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO - * - * Enable support for receiving and parsing SSLv2 Client Hello messages for the - * SSL Server module (POLARSSL_SSL_SRV_C) - * - * Comment this macro to disable support for SSLv2 Client Hello messages. - */ -//#define POLARSSL_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO - -/** - * \def POLARSSL_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION - * - * If set, the X509 parser will not break-off when parsing an X509 certificate - * and encountering an unknown critical extension. - * - * Uncomment to prevent an error. - * -#define POLARSSL_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION - */ - -/** - * \def POLARSSL_ZLIB_SUPPORT - * - * If set, the SSL/TLS module uses ZLIB to support compression and - * decompression of packet data. - * - * Used in: library/ssl_tls.c - * library/ssl_cli.c - * library/ssl_srv.c - * - * This feature requires zlib library and headers to be present. - * - * Uncomment to enable use of ZLIB -#define POLARSSL_ZLIB_SUPPORT - */ -/* \} name */ - -/** - * \name SECTION: PolarSSL modules - * - * This section enables or disables entire modules in PolarSSL - * \{ - */ - -/** - * \def POLARSSL_AES_C - * - * Enable the AES block cipher. - * - * Module: library/aes.c - * Caller: library/ssl_tls.c - * library/pem.c - * library/ctr_drbg.c - * - * This module enables the following ciphersuites (if other requisites are - * enabled as well): - * TLS_RSA_WITH_AES_128_CBC_SHA - * TLS_RSA_WITH_AES_256_CBC_SHA - * TLS_DHE_RSA_WITH_AES_128_CBC_SHA - * TLS_DHE_RSA_WITH_AES_256_CBC_SHA - * TLS_RSA_WITH_AES_128_CBC_SHA256 - * TLS_RSA_WITH_AES_256_CBC_SHA256 - * TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 - * TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 - * TLS_RSA_WITH_AES_128_GCM_SHA256 - * TLS_RSA_WITH_AES_256_GCM_SHA384 - * - * PEM uses AES for decrypting encrypted keys. - */ -#define POLARSSL_AES_C - -/** - * \def POLARSSL_ARC4_C - * - * Enable the ARCFOUR stream cipher. - * - * Module: library/arc4.c - * Caller: library/ssl_tls.c - * - * This module enables the following ciphersuites: - * TLS_RSA_WITH_RC4_128_MD5 - * TLS_RSA_WITH_RC4_128_SHA - */ -//#define POLARSSL_ARC4_C - -/** - * \def POLARSSL_ASN1_PARSE_C - * - * Enable the generic ASN1 parser. - * - * Module: library/asn1.c - * Caller: library/x509parse.c - */ -//#define POLARSSL_ASN1_PARSE_C - -/** - * \def POLARSSL_ASN1_WRITE_C - * - * Enable the generic ASN1 writer. - * - * Module: library/asn1write.c - */ -//#define POLARSSL_ASN1_WRITE_C - -/** - * \def POLARSSL_BASE64_C - * - * Enable the Base64 module. - * - * Module: library/base64.c - * Caller: library/pem.c - * - * This module is required for PEM support (required by X.509). - */ -#define POLARSSL_BASE64_C - -/** - * \def POLARSSL_BIGNUM_C - * - * Enable the multi-precision integer library. - * - * Module: library/bignum.c - * Caller: library/dhm.c - * library/rsa.c - * library/ssl_tls.c - * library/x509parse.c - * - * This module is required for RSA and DHM support. - */ -#define POLARSSL_BIGNUM_C - -/** - * \def POLARSSL_BLOWFISH_C - * - * Enable the Blowfish block cipher. - * - * Module: library/blowfish.c - */ -//#define POLARSSL_BLOWFISH_C - -/** - * \def POLARSSL_CAMELLIA_C - * - * Enable the Camellia block cipher. - * - * Module: library/camellia.c - * Caller: library/ssl_tls.c - * - * This module enables the following ciphersuites (if other requisites are - * enabled as well): - * TLS_RSA_WITH_CAMELLIA_128_CBC_SHA - * TLS_RSA_WITH_CAMELLIA_256_CBC_SHA - * TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA - * TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA - * TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 - * TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 - * TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 - * TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 - */ -//#define POLARSSL_CAMELLIA_C - -/** - * \def POLARSSL_CERTS_C - * - * Enable the test certificates. - * - * Module: library/certs.c - * Caller: - * - * This module is used for testing (ssl_client/server). - */ -//#define POLARSSL_CERTS_C - -/** - * \def POLARSSL_CIPHER_C - * - * Enable the generic cipher layer. - * - * Module: library/cipher.c - * Caller: - * - * Uncomment to enable generic cipher wrappers. - */ -//#define POLARSSL_CIPHER_C - -/** - * \def POLARSSL_CTR_DRBG_C - * - * Enable the CTR_DRBG AES-256-based random generator - * - * Module: library/ctr_drbg.c - * Caller: - * - * Requires: POLARSSL_AES_C - * - * This module provides the CTR_DRBG AES-256 random number generator. - */ -#define POLARSSL_CTR_DRBG_C - -/** - * \def POLARSSL_DEBUG_C - * - * Enable the debug functions. - * - * Module: library/debug.c - * Caller: library/ssl_cli.c - * library/ssl_srv.c - * library/ssl_tls.c - * - * This module provides debugging functions. - */ -//#define POLARSSL_DEBUG_C - -/** - * \def POLARSSL_DES_C - * - * Enable the DES block cipher. - * - * Module: library/des.c - * Caller: library/pem.c - * library/ssl_tls.c - * - * This module enables the following ciphersuites (if other requisites are - * enabled as well): - * TLS_RSA_WITH_3DES_EDE_CBC_SHA - * TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA - * - * PEM uses DES/3DES for decrypting encrypted keys. - */ -//#define POLARSSL_DES_C - -/** - * \def POLARSSL_DHM_C - * - * Enable the Diffie-Hellman-Merkle key exchange. - * - * Module: library/dhm.c - * Caller: library/ssl_cli.c - * library/ssl_srv.c - * - * This module enables the following ciphersuites (if other requisites are - * enabled as well): - * TLS_DHE_RSA_WITH_DES_CBC_SHA - * TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA - * TLS_DHE_RSA_WITH_AES_128_CBC_SHA - * TLS_DHE_RSA_WITH_AES_256_CBC_SHA - * TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 - * TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 - * TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA - * TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA - * TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 - * TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 - * TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 - * TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 - */ -//#define POLARSSL_DHM_C - -/** - * \def POLARSSL_ENTROPY_C - * - * Enable the platform-specific entropy code. - * - * Module: library/entropy.c - * Caller: - * - * Requires: POLARSSL_SHA4_C - * - * This module provides a generic entropy pool - */ -#define POLARSSL_ENTROPY_C - -/** - * \def POLARSSL_ERROR_C - * - * Enable error code to error string conversion. - * - * Module: library/error.c - * Caller: - * - * This module enables err_strerror(). - */ -//#define POLARSSL_ERROR_C - -/** - * \def POLARSSL_GCM_C - * - * Enable the Galois/Counter Mode (GCM) for AES - * - * Module: library/gcm.c - * - * Requires: POLARSSL_AES_C - * - * This module enables the following ciphersuites (if other requisites are - * enabled as well): - * TLS_RSA_WITH_AES_128_GCM_SHA256 - * TLS_RSA_WITH_AES_256_GCM_SHA384 - */ -//#define POLARSSL_GCM_C - -/** - * \def POLARSSL_HAVEGE_C - * - * Enable the HAVEGE random generator. - * - * Warning: the HAVEGE random generator is not suitable for virtualized - * environments - * - * Warning: the HAVEGE random generator is dependent on timing and specific - * processor traits. It is therefore not advised to use HAVEGE as - * your applications primary random generator or primary entropy pool - * input. As a secondary input to your entropy pool, it IS able add - * the (limited) extra entropy it provides. - * - * Module: library/havege.c - * Caller: - * - * Requires: POLARSSL_TIMING_C - * - * Uncomment to enable the HAVEGE random generator. -#define POLARSSL_HAVEGE_C - */ - -/** - * \def POLARSSL_MD_C - * - * Enable the generic message digest layer. - * - * Module: library/md.c - * Caller: - * - * Uncomment to enable generic message digest wrappers. - */ -#define POLARSSL_MD_C - -/** - * \def POLARSSL_MD2_C - * - * Enable the MD2 hash algorithm - * - * Module: library/md2.c - * Caller: library/x509parse.c - * - * Uncomment to enable support for (rare) MD2-signed X.509 certs. - * -#define POLARSSL_MD2_C - */ - -/** - * \def POLARSSL_MD4_C - * - * Enable the MD4 hash algorithm - * - * Module: library/md4.c - * Caller: library/x509parse.c - * - * Uncomment to enable support for (rare) MD4-signed X.509 certs. - * -#define POLARSSL_MD4_C - */ - -/** - * \def POLARSSL_MD5_C - * - * Enable the MD5 hash algorithm - * - * Module: library/md5.c - * Caller: library/pem.c - * library/ssl_tls.c - * library/x509parse.c - * - * This module is required for SSL/TLS and X.509. - * PEM uses MD5 for decrypting encrypted keys. - */ -//#define POLARSSL_MD5_C - -/** - * \def POLARSSL_NET_C - * - * Enable the TCP/IP networking routines. - * - * Module: library/net.c - * Caller: - * - * This module provides TCP/IP networking routines. - */ -//#define POLARSSL_NET_C - -/** - * \def POLARSSL_PADLOCK_C - * - * Enable VIA Padlock support on x86. - * - * Module: library/padlock.c - * Caller: library/aes.c - * - * This modules adds support for the VIA PadLock on x86. - */ -//#define POLARSSL_PADLOCK_C - -/** - * \def POLARSSL_PBKDF2_C - * - * Enable PKCS#5 PBKDF2 key derivation function - * DEPRECATED: Use POLARSSL_PKCS5_C instead - * - * Module: library/pbkdf2.c - * - * Requires: POLARSSL_PKCS5_C - * - * This module adds support for the PKCS#5 PBKDF2 key derivation function. -#define POLARSSL_PBKDF2_C - */ - -/** - * \def POLARSSL_PEM_C - * - * Enable PEM decoding - * - * Module: library/pem.c - * Caller: library/x509parse.c - * - * Requires: POLARSSL_BASE64_C - * - * This modules adds support for decoding PEM files. - */ -//#define POLARSSL_PEM_C - -/** - * \def POLARSSL_PKCS5_C - * - * Enable PKCS#5 functions - * - * Module: library/pkcs5.c - * - * Requires: POLARSSL_MD_C - * - * This module adds support for the PKCS#5 functions. - */ -//#define POLARSSL_PKCS5_C - -/** - * \def POLARSSL_PKCS11_C - * - * Enable wrapper for PKCS#11 smartcard support. - * - * Module: library/ssl_srv.c - * Caller: library/ssl_cli.c - * library/ssl_srv.c - * - * Requires: POLARSSL_SSL_TLS_C - * - * This module enables SSL/TLS PKCS #11 smartcard support. - * Requires the presence of the PKCS#11 helper library (libpkcs11-helper) -#define POLARSSL_PKCS11_C - */ - -/** - * \def POLARSSL_PKCS12_C - * - * Enable PKCS#12 PBE functions - * Adds algorithms for parsing PKCS#8 encrypted private keys - * - * Module: library/pkcs12.c - * Caller: library/x509parse.c - * - * Requires: POLARSSL_ASN1_PARSE_C, POLARSSL_CIPHER_C, POLARSSL_MD_C - * Can use: POLARSSL_ARC4_C - * - * This module enables PKCS#12 functions. - */ -//#define POLARSSL_PKCS12_C - -/** - * \def POLARSSL_RSA_C - * - * Enable the RSA public-key cryptosystem. - * - * Module: library/rsa.c - * Caller: library/ssl_cli.c - * library/ssl_srv.c - * library/ssl_tls.c - * library/x509.c - * - * Requires: POLARSSL_BIGNUM_C - * - * This module is required for SSL/TLS and MD5-signed certificates. - */ -#define POLARSSL_RSA_C - -/** - * \def POLARSSL_SHA1_C - * - * Enable the SHA1 cryptographic hash algorithm. - * - * Module: library/sha1.c - * Caller: library/ssl_cli.c - * library/ssl_srv.c - * library/ssl_tls.c - * library/x509parse.c - * - * This module is required for SSL/TLS and SHA1-signed certificates. - */ -#define POLARSSL_SHA1_C - -/** - * \def POLARSSL_SHA2_C - * - * Enable the SHA-224 and SHA-256 cryptographic hash algorithms. - * - * Module: library/sha2.c - * Caller: library/md_wrap.c - * library/x509parse.c - * - * This module adds support for SHA-224 and SHA-256. - * This module is required for the SSL/TLS 1.2 PRF function. - */ -#define POLARSSL_SHA2_C - -/** - * \def POLARSSL_SHA4_C - * - * Enable the SHA-384 and SHA-512 cryptographic hash algorithms. - * - * Module: library/sha4.c - * Caller: library/md_wrap.c - * library/x509parse.c - * - * This module adds support for SHA-384 and SHA-512. - */ -#define POLARSSL_SHA4_C - -/** - * \def POLARSSL_SSL_CACHE_C - * - * Enable simple SSL cache implementation. - * - * Module: library/ssl_cache.c - * Caller: - * - * Requires: POLARSSL_SSL_CACHE_C - */ -//#define POLARSSL_SSL_CACHE_C - -/** - * \def POLARSSL_SSL_CLI_C - * - * Enable the SSL/TLS client code. - * - * Module: library/ssl_cli.c - * Caller: - * - * Requires: POLARSSL_SSL_TLS_C - * - * This module is required for SSL/TLS client support. - */ -//#define POLARSSL_SSL_CLI_C - -/** - * \def POLARSSL_SSL_SRV_C - * - * Enable the SSL/TLS server code. - * - * Module: library/ssl_srv.c - * Caller: - * - * Requires: POLARSSL_SSL_TLS_C - * - * This module is required for SSL/TLS server support. - */ -//#define POLARSSL_SSL_SRV_C - -/** - * \def POLARSSL_SSL_TLS_C - * - * Enable the generic SSL/TLS code. - * - * Module: library/ssl_tls.c - * Caller: library/ssl_cli.c - * library/ssl_srv.c - * - * Requires: POLARSSL_MD5_C, POLARSSL_SHA1_C, POLARSSL_X509_PARSE_C - * - * This module is required for SSL/TLS. - */ -//#define POLARSSL_SSL_TLS_C - -/** - * \def POLARSSL_TIMING_C - * - * Enable the portable timing interface. - * - * Module: library/timing.c - * Caller: library/havege.c - * - * This module is used by the HAVEGE random number generator. - */ -//#define POLARSSL_TIMING_C - -/** - * \def POLARSSL_VERSION_C - * - * Enable run-time version information. - * - * Module: library/version.c - * - * This module provides run-time version information. - */ -//#define POLARSSL_VERSION_C - -/** - * \def POLARSSL_X509_PARSE_C - * - * Enable X.509 certificate parsing. - * - * Module: library/x509parse.c - * Caller: library/ssl_cli.c - * library/ssl_srv.c - * library/ssl_tls.c - * - * Requires: POLARSSL_ASN1_PARSE_C, POLARSSL_BIGNUM_C, POLARSSL_RSA_C - * - * This module is required for X.509 certificate parsing. - */ -//#define POLARSSL_X509_PARSE_C - -/** - * \def POLARSSL_X509_WRITE_C - * - * Enable X.509 buffer writing. - * - * Module: library/x509write.c - * - * Requires: POLARSSL_BIGNUM_C, POLARSSL_RSA_C - * - * This module is required for X.509 certificate request writing. - */ -//#define POLARSSL_X509_WRITE_C - -/** - * \def POLARSSL_XTEA_C - * - * Enable the XTEA block cipher. - * - * Module: library/xtea.c - * Caller: - */ -//#define POLARSSL_XTEA_C -/* \} name */ - -/** - * \name SECTION: Module configuration options - * - * This section allows for the setting of module specific sizes and - * configuration options. The default values are already present in the - * relevant header files and should suffice for the regular use cases. - * Our advice is to enable POLARSSL_CONFIG_OPTIONS and change values here - * only if you have a good reason and know the consequences. - * - * If POLARSSL_CONFIG_OPTIONS is undefined here the options in the module - * header file take precedence. - * - * Please check the respective header file for documentation on these - * parameters (to prevent duplicate documentation). - * - * Uncomment POLARSSL_CONFIG_OPTIONS to enable using the values defined here. - * \{ - */ -//#define POLARSSL_CONFIG_OPTIONS /**< Enable config.h module value configuration */ - -#if defined(POLARSSL_CONFIG_OPTIONS) - -// MPI / BIGNUM options -// -#define POLARSSL_MPI_WINDOW_SIZE 6 /**< Maximum windows size used. */ -#define POLARSSL_MPI_MAX_SIZE 512 /**< Maximum number of bytes for usable MPIs. */ - -// CTR_DRBG options -// -#define CTR_DRBG_ENTROPY_LEN 48 /**< Amount of entropy used per seed by default */ -#define CTR_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is performed by default */ -#define CTR_DRBG_MAX_INPUT 256 /**< Maximum number of additional input bytes */ -#define CTR_DRBG_MAX_REQUEST 1024 /**< Maximum number of requested bytes per call */ -#define CTR_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */ - -// Entropy options -// -#define ENTROPY_MAX_SOURCES 20 /**< Maximum number of sources supported */ -#define ENTROPY_MAX_GATHER 128 /**< Maximum amount requested from entropy sources */ - -// SSL Cache options -// -#define SSL_CACHE_DEFAULT_TIMEOUT 86400 /**< 1 day */ -#define SSL_CACHE_DEFAULT_MAX_ENTRIES 50 /**< Maximum entries in cache */ - -// SSL options -// -#define SSL_MAX_CONTENT_LEN 16384 /**< Size of the input / output buffer */ - -#endif /* POLARSSL_CONFIG_OPTIONS */ - -/* \} name */ -#endif /* config.h */ diff --git a/lib/libpolarssl/include/polarssl/ctr_drbg.h b/lib/libpolarssl/include/polarssl/ctr_drbg.h deleted file mode 100644 index 6f81af8..0000000 --- a/lib/libpolarssl/include/polarssl/ctr_drbg.h +++ /dev/null @@ -1,234 +0,0 @@ -/** - * \file ctr_drbg.h - * - * \brief CTR_DRBG based on AES-256 (NIST SP 800-90) - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved - * - * This file is part of mbed TLS (https://polarssl.org) - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ -#ifndef POLARSSL_CTR_DRBG_H -#define POLARSSL_CTR_DRBG_H - -#include - -#include "aes.h" - -#define POLARSSL_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED -0x0034 /**< The entropy source failed. */ -#define POLARSSL_ERR_CTR_DRBG_REQUEST_TOO_BIG -0x0036 /**< Too many random requested in single call. */ -#define POLARSSL_ERR_CTR_DRBG_INPUT_TOO_BIG -0x0038 /**< Input too large (Entropy + additional). */ -#define POLARSSL_ERR_CTR_DRBG_FILE_IO_ERROR -0x003A /**< Read/write error in file. */ - -#define CTR_DRBG_BLOCKSIZE 16 /**< Block size used by the cipher */ -#define CTR_DRBG_KEYSIZE 32 /**< Key size used by the cipher */ -#define CTR_DRBG_KEYBITS ( CTR_DRBG_KEYSIZE * 8 ) -#define CTR_DRBG_SEEDLEN ( CTR_DRBG_KEYSIZE + CTR_DRBG_BLOCKSIZE ) - /**< The seed length (counter + AES key) */ - -#if !defined(POLARSSL_CONFIG_OPTIONS) -#define CTR_DRBG_ENTROPY_LEN 48 /**< Amount of entropy used per seed by default */ -#define CTR_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is performed by default */ -#define CTR_DRBG_MAX_INPUT 256 /**< Maximum number of additional input bytes */ -#define CTR_DRBG_MAX_REQUEST 1024 /**< Maximum number of requested bytes per call */ -#define CTR_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */ -#endif /* !POLARSSL_CONFIG_OPTIONS */ - -#define CTR_DRBG_PR_OFF 0 /**< No prediction resistance */ -#define CTR_DRBG_PR_ON 1 /**< Prediction resistance enabled */ - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \brief CTR_DRBG context structure - */ -typedef struct -{ - unsigned char counter[16]; /*!< counter (V) */ - int reseed_counter; /*!< reseed counter */ - int prediction_resistance; /*!< enable prediction resistance (Automatic - reseed before every random generation) */ - size_t entropy_len; /*!< amount of entropy grabbed on each (re)seed */ - int reseed_interval; /*!< reseed interval */ - - aes_context aes_ctx; /*!< AES context */ - - /* - * Callbacks (Entropy) - */ - int (*f_entropy)(void *, unsigned char *, size_t); - - void *p_entropy; /*!< context for the entropy function */ -} -ctr_drbg_context; - -/** - * \brief CTR_DRBG initialization - * - * Note: Personalization data can be provided in addition to the more generic - * entropy source to make this instantiation as unique as possible. - * - * \param ctx CTR_DRBG context to be initialized - * \param f_entropy Entropy callback (p_entropy, buffer to fill, buffer - * length) - * \param p_entropy Entropy context - * \param custom Personalization data (Device specific identifiers) - * (Can be NULL) - * \param len Length of personalization data - * - * \return 0 if successful, or - * POLARSSL_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED - */ -int ctr_drbg_init( ctr_drbg_context *ctx, - int (*f_entropy)(void *, unsigned char *, size_t), - void *p_entropy, - const unsigned char *custom, - size_t len ); - -/** - * \brief Enable / disable prediction resistance (Default: Off) - * - * Note: If enabled, entropy is used for ctx->entropy_len before each call! - * Only use this if you have ample supply of good entropy! - * - * \param ctx CTR_DRBG context - * \param resistance CTR_DRBG_PR_ON or CTR_DRBG_PR_OFF - */ -void ctr_drbg_set_prediction_resistance( ctr_drbg_context *ctx, - int resistance ); - -/** - * \brief Set the amount of entropy grabbed on each (re)seed - * (Default: CTR_DRBG_ENTROPY_LEN) - * - * \param ctx CTR_DRBG context - * \param len Amount of entropy to grab - */ -void ctr_drbg_set_entropy_len( ctr_drbg_context *ctx, - size_t len ); - -/** - * \brief Set the reseed interval - * (Default: CTR_DRBG_RESEED_INTERVAL) - * - * \param ctx CTR_DRBG context - * \param interval Reseed interval - */ -void ctr_drbg_set_reseed_interval( ctr_drbg_context *ctx, - int interval ); - -/** - * \brief CTR_DRBG reseeding (extracts data from entropy source) - * - * \param ctx CTR_DRBG context - * \param additional Additional data to add to state (Can be NULL) - * \param len Length of additional data - * - * \return 0 if successful, or - * POLARSSL_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED - */ -int ctr_drbg_reseed( ctr_drbg_context *ctx, - const unsigned char *additional, size_t len ); - -/** - * \brief CTR_DRBG update state - * - * \param ctx CTR_DRBG context - * \param additional Additional data to update state with - * \param add_len Length of additional data - * - * \note If add_len is greater than CTR_DRBG_MAX_SEED_INPUT, - * only the first CTR_DRBG_MAX_SEED_INPUT bytes are used, - * the remaining ones are silently discarded. - */ -void ctr_drbg_update( ctr_drbg_context *ctx, - const unsigned char *additional, size_t add_len ); - -/** - * \brief CTR_DRBG generate random with additional update input - * - * Note: Automatically reseeds if reseed_counter is reached. - * - * \param p_rng CTR_DRBG context - * \param output Buffer to fill - * \param output_len Length of the buffer - * \param additional Additional data to update with (Can be NULL) - * \param add_len Length of additional data - * - * \return 0 if successful, or - * POLARSSL_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED, or - * POLARSSL_ERR_CTR_DRBG_REQUEST_TOO_BIG - */ -int ctr_drbg_random_with_add( void *p_rng, - unsigned char *output, size_t output_len, - const unsigned char *additional, size_t add_len ); - -/** - * \brief CTR_DRBG generate random - * - * Note: Automatically reseeds if reseed_counter is reached. - * - * \param p_rng CTR_DRBG context - * \param output Buffer to fill - * \param output_len Length of the buffer - * - * \return 0 if successful, or - * POLARSSL_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED, or - * POLARSSL_ERR_CTR_DRBG_REQUEST_TOO_BIG - */ -int ctr_drbg_random( void *p_rng, - unsigned char *output, size_t output_len ); - -#if defined(POLARSSL_FS_IO) -/** - * \brief Write a seed file - * - * \param path Name of the file - * - * \return 0 if successful, - * POLARSSL_ERR_CTR_DRBG_FILE_IO_ERROR on file error, or - * POLARSSL_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED - */ -int ctr_drbg_write_seed_file( ctr_drbg_context *ctx, const char *path ); - -/** - * \brief Read and update a seed file. Seed is added to this - * instance - * - * \param path Name of the file - * - * \return 0 if successful, - * POLARSSL_ERR_CTR_DRBG_FILE_IO_ERROR on file error, - * POLARSSL_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or - * POLARSSL_ERR_CTR_DRBG_INPUT_TOO_BIG - */ -int ctr_drbg_update_seed_file( ctr_drbg_context *ctx, const char *path ); -#endif - -/** - * \brief Checkup routine - * - * \return 0 if successful, or 1 if the test failed - */ -int ctr_drbg_self_test( int verbose ); - -#ifdef __cplusplus -} -#endif - -#endif /* ctr_drbg.h */ diff --git a/lib/libpolarssl/include/polarssl/entropy.h b/lib/libpolarssl/include/polarssl/entropy.h deleted file mode 100644 index 7ce7a5a..0000000 --- a/lib/libpolarssl/include/polarssl/entropy.h +++ /dev/null @@ -1,180 +0,0 @@ -/** - * \file entropy.h - * - * \brief Entropy accumulator implementation - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved - * - * This file is part of mbed TLS (https://polarssl.org) - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ -#ifndef POLARSSL_ENTROPY_H -#define POLARSSL_ENTROPY_H - -#include - -#include "config.h" - -#include "sha4.h" -#if defined(POLARSSL_HAVEGE_C) -#include "havege.h" -#endif - -#define POLARSSL_ERR_ENTROPY_SOURCE_FAILED -0x003C /**< Critical entropy source failure. */ -#define POLARSSL_ERR_ENTROPY_MAX_SOURCES -0x003E /**< No more sources can be added. */ -#define POLARSSL_ERR_ENTROPY_NO_SOURCES_DEFINED -0x0040 /**< No sources have been added to poll. */ -#define POLARSSL_ERR_ENTROPY_FILE_IO_ERROR -0x0058 /**< Read/write error in file. */ - -#if !defined(POLARSSL_CONFIG_OPTIONS) -#define ENTROPY_MAX_SOURCES 20 /**< Maximum number of sources supported */ -#define ENTROPY_MAX_GATHER 128 /**< Maximum amount requested from entropy sources */ -#endif /* !POLARSSL_CONFIG_OPTIONS */ - -#define ENTROPY_BLOCK_SIZE 64 /**< Block size of entropy accumulator (SHA-512) */ - -#define ENTROPY_MAX_SEED_SIZE 1024 /**< Maximum size of seed we read from seed file */ -#define ENTROPY_SOURCE_MANUAL ENTROPY_MAX_SOURCES - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \brief Entropy poll callback pointer - * - * \param data Callback-specific data pointer - * \param output Data to fill - * \param len Maximum size to provide - * \param olen The actual amount of bytes put into the buffer (Can be 0) - * - * \return 0 if no critical failures occurred, - * POLARSSL_ERR_ENTROPY_SOURCE_FAILED otherwise - */ -typedef int (*f_source_ptr)(void *data, unsigned char *output, size_t len, size_t *olen); - -/** - * \brief Entropy source state - */ -typedef struct -{ - f_source_ptr f_source; /**< The entropy source callback */ - void * p_source; /**< The callback data pointer */ - size_t size; /**< Amount received */ - size_t threshold; /**< Minimum level required before release */ -} -source_state; - -/** - * \brief Entropy context structure - */ -typedef struct -{ - sha4_context accumulator; - int source_count; - source_state source[ENTROPY_MAX_SOURCES]; -#if defined(POLARSSL_HAVEGE_C) - havege_state havege_data; -#endif -} -entropy_context; - -/** - * \brief Initialize the context - * - * \param ctx Entropy context to initialize - */ -void entropy_init( entropy_context *ctx ); - -/** - * \brief Adds an entropy source to poll - * - * \param ctx Entropy context - * \param f_source Entropy function - * \param p_source Function data - * \param threshold Minimum required from source before entropy is released - * ( with entropy_func() ) - * - * \return 0 if successful or POLARSSL_ERR_ENTROPY_MAX_SOURCES - */ -int entropy_add_source( entropy_context *ctx, - f_source_ptr f_source, void *p_source, - size_t threshold ); - -/** - * \brief Trigger an extra gather poll for the accumulator - * - * \param ctx Entropy context - * - * \return 0 if successful, or POLARSSL_ERR_ENTROPY_SOURCE_FAILED - */ -int entropy_gather( entropy_context *ctx ); - -/** - * \brief Retrieve entropy from the accumulator (Max ENTROPY_BLOCK_SIZE) - * - * \param data Entropy context - * \param output Buffer to fill - * \param len Length of buffer - * - * \return 0 if successful, or POLARSSL_ERR_ENTROPY_SOURCE_FAILED - */ -int entropy_func( void *data, unsigned char *output, size_t len ); - -/** - * \brief Add data to the accumulator manually - * - * \param ctx Entropy context - * \param data Data to add - * \param len Length of data - * - * \return 0 if successful - */ -int entropy_update_manual( entropy_context *ctx, - const unsigned char *data, size_t len ); - -#if defined(POLARSSL_FS_IO) -/** - * \brief Write a seed file - * - * \param ctx Entropy context - * \param path Name of the file - * - * \return 0 if successful, - * POLARSSL_ERR_ENTROPY_FILE_IO_ERROR on file error, or - * POLARSSL_ERR_ENTROPY_SOURCE_FAILED - */ -int entropy_write_seed_file( entropy_context *ctx, const char *path ); - -/** - * \brief Read and update a seed file. Seed is added to this - * instance. No more than ENTROPY_MAX_SEED_SIZE bytes are - * read from the seed file. The rest is ignored. - * - * \param ctx Entropy context - * \param path Name of the file - * - * \return 0 if successful, - * POLARSSL_ERR_ENTROPY_FILE_IO_ERROR on file error, - * POLARSSL_ERR_ENTROPY_SOURCE_FAILED - */ -int entropy_update_seed_file( entropy_context *ctx, const char *path ); -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* entropy.h */ diff --git a/lib/libpolarssl/include/polarssl/entropy_poll.h b/lib/libpolarssl/include/polarssl/entropy_poll.h deleted file mode 100644 index 82842ce..0000000 --- a/lib/libpolarssl/include/polarssl/entropy_poll.h +++ /dev/null @@ -1,72 +0,0 @@ -/** - * \file entropy_poll.h - * - * \brief Platform-specific and custom entropy polling functions - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved - * - * This file is part of mbed TLS (https://polarssl.org) - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ -#ifndef POLARSSL_ENTROPY_POLL_H -#define POLARSSL_ENTROPY_POLL_H - -#include - -#include "config.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Default thresholds for built-in sources - */ -#define ENTROPY_MIN_PLATFORM 128 /**< Minimum for platform source */ -#define ENTROPY_MIN_HAVEGE 128 /**< Minimum for HAVEGE */ -#define ENTROPY_MIN_HARDCLOCK 32 /**< Minimum for hardclock() */ - -#if !defined(POLARSSL_NO_PLATFORM_ENTROPY) -/** - * \brief Platform-specific entropy poll callback - */ -int platform_entropy_poll( void *data, - unsigned char *output, size_t len, size_t *olen ); -#endif - -#if defined(POLARSSL_HAVEGE_C) -/** - * \brief HAVEGE based entropy poll callback - * - * Requires an HAVEGE state as its data pointer. - */ -int havege_poll( void *data, - unsigned char *output, size_t len, size_t *olen ); -#endif - -#if defined(POLARSSL_TIMING_C) -/** - * \brief hardclock-based entropy poll callback - */ -int hardclock_poll( void *data, - unsigned char *output, size_t len, size_t *olen ); -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* entropy_poll.h */ diff --git a/lib/libpolarssl/include/polarssl/md.h b/lib/libpolarssl/include/polarssl/md.h deleted file mode 100644 index ae38aad..0000000 --- a/lib/libpolarssl/include/polarssl/md.h +++ /dev/null @@ -1,357 +0,0 @@ -/** - * \file md.h - * - * \brief Generic message digest wrapper - * - * \author Adriaan de Jong - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved - * - * This file is part of mbed TLS (https://polarssl.org) - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ -#ifndef POLARSSL_MD_H -#define POLARSSL_MD_H - -#include - -#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \ - !defined(inline) && !defined(__cplusplus) -#define inline __inline -#endif - -#define POLARSSL_ERR_MD_FEATURE_UNAVAILABLE -0x5080 /**< The selected feature is not available. */ -#define POLARSSL_ERR_MD_BAD_INPUT_DATA -0x5100 /**< Bad input parameters to function. */ -#define POLARSSL_ERR_MD_ALLOC_FAILED -0x5180 /**< Failed to allocate memory. */ -#define POLARSSL_ERR_MD_FILE_IO_ERROR -0x5200 /**< Opening or reading of file failed. */ - -typedef enum { - POLARSSL_MD_NONE=0, - POLARSSL_MD_MD2, - POLARSSL_MD_MD4, - POLARSSL_MD_MD5, - POLARSSL_MD_SHA1, - POLARSSL_MD_SHA224, - POLARSSL_MD_SHA256, - POLARSSL_MD_SHA384, - POLARSSL_MD_SHA512, -} md_type_t; - -#define POLARSSL_MD_MAX_SIZE 64 /* longest known is SHA512 */ - -/** - * Message digest information. Allows message digest functions to be called - * in a generic way. - */ -typedef struct { - /** Digest identifier */ - md_type_t type; - - /** Name of the message digest */ - const char * name; - - /** Output length of the digest function */ - int size; - - /** Digest initialisation function */ - void (*starts_func)( void *ctx ); - - /** Digest update function */ - void (*update_func)( void *ctx, const unsigned char *input, size_t ilen ); - - /** Digest finalisation function */ - void (*finish_func)( void *ctx, unsigned char *output ); - - /** Generic digest function */ - void (*digest_func)( const unsigned char *input, size_t ilen, - unsigned char *output ); - - /** Generic file digest function */ - int (*file_func)( const char *path, unsigned char *output ); - - /** HMAC Initialisation function */ - void (*hmac_starts_func)( void *ctx, const unsigned char *key, size_t keylen ); - - /** HMAC update function */ - void (*hmac_update_func)( void *ctx, const unsigned char *input, size_t ilen ); - - /** HMAC finalisation function */ - void (*hmac_finish_func)( void *ctx, unsigned char *output); - - /** HMAC context reset function */ - void (*hmac_reset_func)( void *ctx ); - - /** Generic HMAC function */ - void (*hmac_func)( const unsigned char *key, size_t keylen, - const unsigned char *input, size_t ilen, - unsigned char *output ); - - /** Allocate a new context */ - void * (*ctx_alloc_func)( void ); - - /** Free the given context */ - void (*ctx_free_func)( void *ctx ); - -} md_info_t; - -/** - * Generic message digest context. - */ -typedef struct { - /** Information about the associated message digest */ - const md_info_t *md_info; - - /** Digest-specific context */ - void *md_ctx; -} md_context_t; - -#define MD_CONTEXT_T_INIT { \ - NULL, /* md_info */ \ - NULL, /* md_ctx */ \ -} - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \brief Returns the list of digests supported by the generic digest module. - * - * \return a statically allocated array of digests, the last entry - * is 0. - */ -const int *md_list( void ); - -/** - * \brief Returns the message digest information associated with the - * given digest name. - * - * \param md_name Name of the digest to search for. - * - * \return The message digest information associated with md_name or - * NULL if not found. - */ -const md_info_t *md_info_from_string( const char *md_name ); - -/** - * \brief Returns the message digest information associated with the - * given digest type. - * - * \param md_type type of digest to search for. - * - * \return The message digest information associated with md_type or - * NULL if not found. - */ -const md_info_t *md_info_from_type( md_type_t md_type ); - -/** - * \brief Initialises and fills the message digest context structure with - * the appropriate values. - * - * \param ctx context to initialise. May not be NULL. The - * digest-specific context (ctx->md_ctx) must be NULL. It will - * be allocated, and must be freed using md_free_ctx() later. - * \param md_info message digest to use. - * - * \returns \c 0 on success, \c POLARSSL_ERR_MD_BAD_INPUT_DATA on - * parameter failure, \c POLARSSL_ERR_MD_ALLOC_FAILED if - * allocation of the digest-specific context failed. - */ -int md_init_ctx( md_context_t *ctx, const md_info_t *md_info ); - -/** - * \brief Free the message-specific context of ctx. Freeing ctx itself - * remains the responsibility of the caller. - * - * \param ctx Free the message-specific context - * - * \returns 0 on success, POLARSSL_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. - */ -int md_free_ctx( md_context_t *ctx ); - -/** - * \brief Returns the size of the message digest output. - * - * \param md_info message digest info - * - * \return size of the message digest output. - */ -static inline unsigned char md_get_size( const md_info_t *md_info ) -{ - if( md_info == NULL ) - return( 0 ); - - return md_info->size; -} - -/** - * \brief Returns the type of the message digest output. - * - * \param md_info message digest info - * - * \return type of the message digest output. - */ -static inline md_type_t md_get_type( const md_info_t *md_info ) -{ - if( md_info == NULL ) - return( POLARSSL_MD_NONE ); - - return md_info->type; -} - -/** - * \brief Returns the name of the message digest output. - * - * \param md_info message digest info - * - * \return name of the message digest output. - */ -static inline const char *md_get_name( const md_info_t *md_info ) -{ - if( md_info == NULL ) - return( NULL ); - - return md_info->name; -} - -/** - * \brief Set-up the given context for a new message digest - * - * \param ctx generic message digest context. - * - * \returns 0 on success, POLARSSL_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. - */ -int md_starts( md_context_t *ctx ); - -/** - * \brief Generic message digest process buffer - * - * \param ctx Generic message digest context - * \param input buffer holding the datal - * \param ilen length of the input data - * - * \returns 0 on success, POLARSSL_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. - */ -int md_update( md_context_t *ctx, const unsigned char *input, size_t ilen ); - -/** - * \brief Generic message digest final digest - * - * \param ctx Generic message digest context - * \param output Generic message digest checksum result - * - * \returns 0 on success, POLARSSL_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. - */ -int md_finish( md_context_t *ctx, unsigned char *output ); - -/** - * \brief Output = message_digest( input buffer ) - * - * \param md_info message digest info - * \param input buffer holding the data - * \param ilen length of the input data - * \param output Generic message digest checksum result - * - * \returns 0 on success, POLARSSL_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. - */ -int md( const md_info_t *md_info, const unsigned char *input, size_t ilen, - unsigned char *output ); - -/** - * \brief Output = message_digest( file contents ) - * - * \param md_info message digest info - * \param path input file name - * \param output generic message digest checksum result - * - * \return 0 if successful, POLARSSL_ERR_MD_FILE_OPEN_FAILED if fopen - * failed, POLARSSL_ERR_MD_FILE_READ_FAILED if fread failed, - * POLARSSL_ERR_MD_BAD_INPUT_DATA if md_info was NULL. - */ -int md_file( const md_info_t *md_info, const char *path, unsigned char *output ); - -/** - * \brief Generic HMAC context setup - * - * \param ctx HMAC context to be initialized - * \param key HMAC secret key - * \param keylen length of the HMAC key - * - * \returns 0 on success, POLARSSL_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. - */ -int md_hmac_starts( md_context_t *ctx, const unsigned char *key, size_t keylen ); - -/** - * \brief Generic HMAC process buffer - * - * \param ctx HMAC context - * \param input buffer holding the data - * \param ilen length of the input data - * - * \returns 0 on success, POLARSSL_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. - */ -int md_hmac_update( md_context_t *ctx, const unsigned char *input, size_t ilen ); - -/** - * \brief Generic HMAC final digest - * - * \param ctx HMAC context - * \param output Generic HMAC checksum result - * - * \returns 0 on success, POLARSSL_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. - */ -int md_hmac_finish( md_context_t *ctx, unsigned char *output); - -/** - * \brief Generic HMAC context reset - * - * \param ctx HMAC context to be reset - * - * \returns 0 on success, POLARSSL_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. - */ -int md_hmac_reset( md_context_t *ctx ); - -/** - * \brief Output = Generic_HMAC( hmac key, input buffer ) - * - * \param md_info message digest info - * \param key HMAC secret key - * \param keylen length of the HMAC key - * \param input buffer holding the data - * \param ilen length of the input data - * \param output Generic HMAC-result - * - * \returns 0 on success, POLARSSL_ERR_MD_BAD_INPUT_DATA if parameter - * verification fails. - */ -int md_hmac( const md_info_t *md_info, const unsigned char *key, size_t keylen, - const unsigned char *input, size_t ilen, - unsigned char *output ); - -#ifdef __cplusplus -} -#endif - -#endif /* POLARSSL_MD_H */ diff --git a/lib/libpolarssl/include/polarssl/md_wrap.h b/lib/libpolarssl/include/polarssl/md_wrap.h deleted file mode 100644 index 0c2ced5..0000000 --- a/lib/libpolarssl/include/polarssl/md_wrap.h +++ /dev/null @@ -1,61 +0,0 @@ -/** - * \file md_wrap.h - * - * \brief Message digest wrappers. - * - * \author Adriaan de Jong - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved - * - * This file is part of mbed TLS (https://polarssl.org) - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ -#ifndef POLARSSL_MD_WRAP_H -#define POLARSSL_MD_WRAP_H - -#include "config.h" -#include "md.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined(POLARSSL_MD2_C) -extern const md_info_t md2_info; -#endif -#if defined(POLARSSL_MD4_C) -extern const md_info_t md4_info; -#endif -#if defined(POLARSSL_MD5_C) -extern const md_info_t md5_info; -#endif -#if defined(POLARSSL_SHA1_C) -extern const md_info_t sha1_info; -#endif -#if defined(POLARSSL_SHA2_C) -extern const md_info_t sha224_info; -extern const md_info_t sha256_info; -#endif -#if defined(POLARSSL_SHA4_C) -extern const md_info_t sha384_info; -extern const md_info_t sha512_info; -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* POLARSSL_MD_WRAP_H */ diff --git a/lib/libpolarssl/include/polarssl/rsa.h b/lib/libpolarssl/include/polarssl/rsa.h deleted file mode 100644 index 8edc21d..0000000 --- a/lib/libpolarssl/include/polarssl/rsa.h +++ /dev/null @@ -1,597 +0,0 @@ -/** - * \file rsa.h - * - * \brief The RSA public-key cryptosystem - * - * Copyright (C) 2006-2010, Brainspark B.V. - * - * This file is part of PolarSSL (http://www.polarssl.org) - * Lead Maintainer: Paul Bakker - * - * All rights reserved. - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ -#ifndef POLARSSL_RSA_H -#define POLARSSL_RSA_H - -#include "bignum.h" - -/* - * RSA Error codes - */ -#define POLARSSL_ERR_RSA_BAD_INPUT_DATA -0x4080 /**< Bad input parameters to function. */ -#define POLARSSL_ERR_RSA_INVALID_PADDING -0x4100 /**< Input data contains invalid padding and is rejected. */ -#define POLARSSL_ERR_RSA_KEY_GEN_FAILED -0x4180 /**< Something failed during generation of a key. */ -#define POLARSSL_ERR_RSA_KEY_CHECK_FAILED -0x4200 /**< Key failed to pass the libraries validity check. */ -#define POLARSSL_ERR_RSA_PUBLIC_FAILED -0x4280 /**< The public key operation failed. */ -#define POLARSSL_ERR_RSA_PRIVATE_FAILED -0x4300 /**< The private key operation failed. */ -#define POLARSSL_ERR_RSA_VERIFY_FAILED -0x4380 /**< The PKCS#1 verification failed. */ -#define POLARSSL_ERR_RSA_OUTPUT_TOO_LARGE -0x4400 /**< The output buffer for decryption is not large enough. */ -#define POLARSSL_ERR_RSA_RNG_FAILED -0x4480 /**< The random generator failed to generate non-zeros. */ - -/* - * PKCS#1 constants - */ -#define SIG_RSA_RAW 0 -#define SIG_RSA_MD2 2 -#define SIG_RSA_MD4 3 -#define SIG_RSA_MD5 4 -#define SIG_RSA_SHA1 5 -#define SIG_RSA_SHA224 14 -#define SIG_RSA_SHA256 11 -#define SIG_RSA_SHA384 12 -#define SIG_RSA_SHA512 13 - -#define RSA_PUBLIC 0 -#define RSA_PRIVATE 1 - -#define RSA_PKCS_V15 0 -#define RSA_PKCS_V21 1 - -#define RSA_SIGN 1 -#define RSA_CRYPT 2 - -#define ASN1_STR_CONSTRUCTED_SEQUENCE "\x30" -#define ASN1_STR_NULL "\x05" -#define ASN1_STR_OID "\x06" -#define ASN1_STR_OCTET_STRING "\x04" - -#define OID_DIGEST_ALG_MDX "\x2A\x86\x48\x86\xF7\x0D\x02\x00" -#define OID_HASH_ALG_SHA1 "\x2b\x0e\x03\x02\x1a" -#define OID_HASH_ALG_SHA2X "\x60\x86\x48\x01\x65\x03\x04\x02\x00" - -#define OID_ISO_MEMBER_BODIES "\x2a" -#define OID_ISO_IDENTIFIED_ORG "\x2b" - -/* - * ISO Member bodies OID parts - */ -#define OID_COUNTRY_US "\x86\x48" -#define OID_RSA_DATA_SECURITY "\x86\xf7\x0d" - -/* - * ISO Identified organization OID parts - */ -#define OID_OIW_SECSIG_SHA1 "\x0e\x03\x02\x1a" - -/* - * DigestInfo ::= SEQUENCE { - * digestAlgorithm DigestAlgorithmIdentifier, - * digest Digest } - * - * DigestAlgorithmIdentifier ::= AlgorithmIdentifier - * - * Digest ::= OCTET STRING - */ -#define ASN1_HASH_MDX \ -( \ - ASN1_STR_CONSTRUCTED_SEQUENCE "\x20" \ - ASN1_STR_CONSTRUCTED_SEQUENCE "\x0C" \ - ASN1_STR_OID "\x08" \ - OID_DIGEST_ALG_MDX \ - ASN1_STR_NULL "\x00" \ - ASN1_STR_OCTET_STRING "\x10" \ -) - -#define ASN1_HASH_SHA1 \ - ASN1_STR_CONSTRUCTED_SEQUENCE "\x21" \ - ASN1_STR_CONSTRUCTED_SEQUENCE "\x09" \ - ASN1_STR_OID "\x05" \ - OID_HASH_ALG_SHA1 \ - ASN1_STR_NULL "\x00" \ - ASN1_STR_OCTET_STRING "\x14" - -#define ASN1_HASH_SHA1_ALT \ - ASN1_STR_CONSTRUCTED_SEQUENCE "\x1F" \ - ASN1_STR_CONSTRUCTED_SEQUENCE "\x07" \ - ASN1_STR_OID "\x05" \ - OID_HASH_ALG_SHA1 \ - ASN1_STR_OCTET_STRING "\x14" - -#define ASN1_HASH_SHA2X \ - ASN1_STR_CONSTRUCTED_SEQUENCE "\x11" \ - ASN1_STR_CONSTRUCTED_SEQUENCE "\x0d" \ - ASN1_STR_OID "\x09" \ - OID_HASH_ALG_SHA2X \ - ASN1_STR_NULL "\x00" \ - ASN1_STR_OCTET_STRING "\x00" - -/** - * \brief RSA context structure - */ -typedef struct -{ - int ver; /*!< always 0 */ - size_t len; /*!< size(N) in chars */ - - mpi N; /*!< public modulus */ - mpi E; /*!< public exponent */ - - mpi D; /*!< private exponent */ - mpi P; /*!< 1st prime factor */ - mpi Q; /*!< 2nd prime factor */ - mpi DP; /*!< D % (P - 1) */ - mpi DQ; /*!< D % (Q - 1) */ - mpi QP; /*!< 1 / (Q % P) */ - - mpi RN; /*!< cached R^2 mod N */ - mpi RP; /*!< cached R^2 mod P */ - mpi RQ; /*!< cached R^2 mod Q */ - - int padding; /*!< RSA_PKCS_V15 for 1.5 padding and - RSA_PKCS_v21 for OAEP/PSS */ - int hash_id; /*!< Hash identifier of md_type_t as - specified in the md.h header file - for the EME-OAEP and EMSA-PSS - encoding */ -} -rsa_context; - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \brief Initialize an RSA context - * - * Note: Set padding to RSA_PKCS_V21 for the RSAES-OAEP - * encryption scheme and the RSASSA-PSS signature scheme. - * - * \param ctx RSA context to be initialized - * \param padding RSA_PKCS_V15 or RSA_PKCS_V21 - * \param hash_id RSA_PKCS_V21 hash identifier - * - * \note The hash_id parameter is actually ignored - * when using RSA_PKCS_V15 padding. - */ -void rsa_init( rsa_context *ctx, - int padding, - int hash_id); - -/** - * \brief Generate an RSA keypair - * - * \param ctx RSA context that will hold the key - * \param f_rng RNG function - * \param p_rng RNG parameter - * \param nbits size of the public key in bits - * \param exponent public exponent (e.g., 65537) - * - * \note rsa_init() must be called beforehand to setup - * the RSA context. - * - * \return 0 if successful, or an POLARSSL_ERR_RSA_XXX error code - */ -int rsa_gen_key( rsa_context *ctx, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng, - unsigned int nbits, int exponent ); - -/** - * \brief Check a public RSA key - * - * \param ctx RSA context to be checked - * - * \return 0 if successful, or an POLARSSL_ERR_RSA_XXX error code - */ -int rsa_check_pubkey( const rsa_context *ctx ); - -/** - * \brief Check a private RSA key - * - * \param ctx RSA context to be checked - * - * \return 0 if successful, or an POLARSSL_ERR_RSA_XXX error code - */ -int rsa_check_privkey( const rsa_context *ctx ); - -/** - * \brief Do an RSA public key operation - * - * \param ctx RSA context - * \param input input buffer - * \param output output buffer - * - * \return 0 if successful, or an POLARSSL_ERR_RSA_XXX error code - * - * \note This function does NOT take care of message - * padding. Also, be sure to set input[0] = 0 or assure that - * input is smaller than N. - * - * \note The input and output buffers must be large - * enough (eg. 128 bytes if RSA-1024 is used). - */ -int rsa_public( rsa_context *ctx, - const unsigned char *input, - unsigned char *output ); - -/** - * \brief Do an RSA private key operation - * - * \param ctx RSA context - * \param input input buffer - * \param output output buffer - * - * \return 0 if successful, or an POLARSSL_ERR_RSA_XXX error code - * - * \note The input and output buffers must be large - * enough (eg. 128 bytes if RSA-1024 is used). - */ -int rsa_private( rsa_context *ctx, - const unsigned char *input, - unsigned char *output ); - -/** - * \brief Generic wrapper to perform a PKCS#1 encryption using the - * mode from the context. Add the message padding, then do an - * RSA operation. - * - * \param ctx RSA context - * \param f_rng RNG function (Needed for padding and PKCS#1 v2.1 encoding) - * \param p_rng RNG parameter - * \param mode RSA_PUBLIC or RSA_PRIVATE - * \param ilen contains the plaintext length - * \param input buffer holding the data to be encrypted - * \param output buffer that will hold the ciphertext - * - * \return 0 if successful, or an POLARSSL_ERR_RSA_XXX error code - * - * \note The output buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used). - */ -int rsa_pkcs1_encrypt( rsa_context *ctx, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng, - int mode, size_t ilen, - const unsigned char *input, - unsigned char *output ); - -/** - * \brief Perform a PKCS#1 v1.5 encryption (RSAES-PKCS1-v1_5-ENCRYPT) - * - * \param ctx RSA context - * \param f_rng RNG function (Needed for padding) - * \param p_rng RNG parameter - * \param mode RSA_PUBLIC or RSA_PRIVATE - * \param ilen contains the plaintext length - * \param input buffer holding the data to be encrypted - * \param output buffer that will hold the ciphertext - * - * \return 0 if successful, or an POLARSSL_ERR_RSA_XXX error code - * - * \note The output buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used). - */ -int rsa_rsaes_pkcs1_v15_encrypt( rsa_context *ctx, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng, - int mode, size_t ilen, - const unsigned char *input, - unsigned char *output ); - -/** - * \brief Perform a PKCS#1 v2.1 OAEP encryption (RSAES-OAEP-ENCRYPT) - * - * \param ctx RSA context - * \param f_rng RNG function (Needed for padding and PKCS#1 v2.1 encoding) - * \param p_rng RNG parameter - * \param mode RSA_PUBLIC or RSA_PRIVATE - * \param label buffer holding the custom label to use - * \param label_len contains the label length - * \param ilen contains the plaintext length - * \param input buffer holding the data to be encrypted - * \param output buffer that will hold the ciphertext - * - * \return 0 if successful, or an POLARSSL_ERR_RSA_XXX error code - * - * \note The output buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used). - */ -int rsa_rsaes_oaep_encrypt( rsa_context *ctx, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng, - int mode, - const unsigned char *label, size_t label_len, - size_t ilen, - const unsigned char *input, - unsigned char *output ); - -/** - * \brief Generic wrapper to perform a PKCS#1 decryption using the - * mode from the context. Do an RSA operation, then remove - * the message padding - * - * \param ctx RSA context - * \param mode RSA_PUBLIC or RSA_PRIVATE - * \param olen will contain the plaintext length - * \param input buffer holding the encrypted data - * \param output buffer that will hold the plaintext - * \param output_max_len maximum length of the output buffer - * - * \return 0 if successful, or an POLARSSL_ERR_RSA_XXX error code - * - * \note The output buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used) otherwise - * an error is thrown. - */ -int rsa_pkcs1_decrypt( rsa_context *ctx, - int mode, size_t *olen, - const unsigned char *input, - unsigned char *output, - size_t output_max_len ); - -/** - * \brief Perform a PKCS#1 v1.5 decryption (RSAES-PKCS1-v1_5-DECRYPT) - * - * \param ctx RSA context - * \param mode RSA_PUBLIC or RSA_PRIVATE - * \param olen will contain the plaintext length - * \param input buffer holding the encrypted data - * \param output buffer that will hold the plaintext - * \param output_max_len maximum length of the output buffer - * - * \return 0 if successful, or an POLARSSL_ERR_RSA_XXX error code - * - * \note The output buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used) otherwise - * an error is thrown. - */ -int rsa_rsaes_pkcs1_v15_decrypt( rsa_context *ctx, - int mode, size_t *olen, - const unsigned char *input, - unsigned char *output, - size_t output_max_len ); - -/** - * \brief Perform a PKCS#1 v2.1 OAEP decryption (RSAES-OAEP-DECRYPT) - * - * \param ctx RSA context - * \param mode RSA_PUBLIC or RSA_PRIVATE - * \param label buffer holding the custom label to use - * \param label_len contains the label length - * \param olen will contain the plaintext length - * \param input buffer holding the encrypted data - * \param output buffer that will hold the plaintext - * \param output_max_len maximum length of the output buffer - * - * \return 0 if successful, or an POLARSSL_ERR_RSA_XXX error code - * - * \note The output buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used) otherwise - * an error is thrown. - */ -int rsa_rsaes_oaep_decrypt( rsa_context *ctx, - int mode, - const unsigned char *label, size_t label_len, - size_t *olen, - const unsigned char *input, - unsigned char *output, - size_t output_max_len ); - -/** - * \brief Generic wrapper to perform a PKCS#1 signature using the - * mode from the context. Do a private RSA operation to sign - * a message digest - * - * \param ctx RSA context - * \param f_rng RNG function (Needed for PKCS#1 v2.1 encoding) - * \param p_rng RNG parameter - * \param mode RSA_PUBLIC or RSA_PRIVATE - * \param hash_id SIG_RSA_RAW, SIG_RSA_MD{2,4,5} or SIG_RSA_SHA{1,224,256,384,512} - * \param hashlen message digest length (for SIG_RSA_RAW only) - * \param hash buffer holding the message digest - * \param sig buffer that will hold the ciphertext - * - * \return 0 if the signing operation was successful, - * or an POLARSSL_ERR_RSA_XXX error code - * - * \note The "sig" buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used). - * - * \note In case of PKCS#1 v2.1 encoding keep in mind that - * the hash_id in the RSA context is the one used for the - * encoding. hash_id in the function call is the type of hash - * that is encoded. According to RFC 3447 it is advised to - * keep both hashes the same. - */ -int rsa_pkcs1_sign( rsa_context *ctx, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng, - int mode, - int hash_id, - unsigned int hashlen, - const unsigned char *hash, - unsigned char *sig ); - -/** - * \brief Perform a PKCS#1 v1.5 signature (RSASSA-PKCS1-v1_5-SIGN) - * - * \param ctx RSA context - * \param mode RSA_PUBLIC or RSA_PRIVATE - * \param hash_id SIG_RSA_RAW, SIG_RSA_MD{2,4,5} or SIG_RSA_SHA{1,224,256,384,512} - * \param hashlen message digest length (for SIG_RSA_RAW only) - * \param hash buffer holding the message digest - * \param sig buffer that will hold the ciphertext - * - * \return 0 if the signing operation was successful, - * or an POLARSSL_ERR_RSA_XXX error code - * - * \note The "sig" buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used). - */ -int rsa_rsassa_pkcs1_v15_sign( rsa_context *ctx, - int mode, - int hash_id, - unsigned int hashlen, - const unsigned char *hash, - unsigned char *sig ); - -/** - * \brief Perform a PKCS#1 v2.1 PSS signature (RSASSA-PSS-SIGN) - * - * \param ctx RSA context - * \param f_rng RNG function (Needed for PKCS#1 v2.1 encoding) - * \param p_rng RNG parameter - * \param mode RSA_PUBLIC or RSA_PRIVATE - * \param hash_id SIG_RSA_RAW, SIG_RSA_MD{2,4,5} or SIG_RSA_SHA{1,224,256,384,512} - * \param hashlen message digest length (for SIG_RSA_RAW only) - * \param hash buffer holding the message digest - * \param sig buffer that will hold the ciphertext - * - * \return 0 if the signing operation was successful, - * or an POLARSSL_ERR_RSA_XXX error code - * - * \note The "sig" buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used). - * - * \note In case of PKCS#1 v2.1 encoding keep in mind that - * the hash_id in the RSA context is the one used for the - * encoding. hash_id in the function call is the type of hash - * that is encoded. According to RFC 3447 it is advised to - * keep both hashes the same. - */ -int rsa_rsassa_pss_sign( rsa_context *ctx, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng, - int mode, - int hash_id, - unsigned int hashlen, - const unsigned char *hash, - unsigned char *sig ); - -/** - * \brief Generic wrapper to perform a PKCS#1 verification using the - * mode from the context. Do a public RSA operation and check - * the message digest - * - * \param ctx points to an RSA public key - * \param mode RSA_PUBLIC or RSA_PRIVATE - * \param hash_id SIG_RSA_RAW, SIG_RSA_MD{2,4,5} or SIG_RSA_SHA{1,224,256,384,512} - * \param hashlen message digest length (for SIG_RSA_RAW only) - * \param hash buffer holding the message digest - * \param sig buffer holding the ciphertext - * - * \return 0 if the verify operation was successful, - * or an POLARSSL_ERR_RSA_XXX error code - * - * \note The "sig" buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used). - * - * \note In case of PKCS#1 v2.1 encoding keep in mind that - * the hash_id in the RSA context is the one used for the - * verification. hash_id in the function call is the type of hash - * that is verified. According to RFC 3447 it is advised to - * keep both hashes the same. - */ -int rsa_pkcs1_verify( rsa_context *ctx, - int mode, - int hash_id, - unsigned int hashlen, - const unsigned char *hash, - const unsigned char *sig ); - -/** - * \brief Perform a PKCS#1 v1.5 verification (RSASSA-PKCS1-v1_5-VERIFY) - * - * \param ctx points to an RSA public key - * \param mode RSA_PUBLIC or RSA_PRIVATE - * \param hash_id SIG_RSA_RAW, SIG_RSA_MD{2,4,5} or SIG_RSA_SHA{1,224,256,384,512} - * \param hashlen message digest length (for SIG_RSA_RAW only) - * \param hash buffer holding the message digest - * \param sig buffer holding the ciphertext - * - * \return 0 if the verify operation was successful, - * or an POLARSSL_ERR_RSA_XXX error code - * - * \note The "sig" buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used). - */ -int rsa_rsassa_pkcs1_v15_verify( rsa_context *ctx, - int mode, - int hash_id, - unsigned int hashlen, - const unsigned char *hash, - const unsigned char *sig ); - -/** - * \brief Perform a PKCS#1 v2.1 PSS verification (RSASSA-PSS-VERIFY) - * \brief Do a public RSA and check the message digest - * - * \param ctx points to an RSA public key - * \param mode RSA_PUBLIC or RSA_PRIVATE - * \param hash_id SIG_RSA_RAW, SIG_RSA_MD{2,4,5} or SIG_RSA_SHA{1,224,256,384,512} - * \param hashlen message digest length (for SIG_RSA_RAW only) - * \param hash buffer holding the message digest - * \param sig buffer holding the ciphertext - * - * \return 0 if the verify operation was successful, - * or an POLARSSL_ERR_RSA_XXX error code - * - * \note The "sig" buffer must be as large as the size - * of ctx->N (eg. 128 bytes if RSA-1024 is used). - * - * \note In case of PKCS#1 v2.1 encoding keep in mind that - * the hash_id in the RSA context is the one used for the - * verification. hash_id in the function call is the type of hash - * that is verified. According to RFC 3447 it is advised to - * keep both hashes the same. - */ -int rsa_rsassa_pss_verify( rsa_context *ctx, - int mode, - int hash_id, - unsigned int hashlen, - const unsigned char *hash, - const unsigned char *sig ); - -/** - * \brief Free the components of an RSA key - * - * \param ctx RSA Context to free - */ -void rsa_free( rsa_context *ctx ); - -/** - * \brief Checkup routine - * - * \return 0 if successful, or 1 if the test failed - */ -int rsa_self_test( int verbose ); - -#ifdef __cplusplus -} -#endif - -#endif /* rsa.h */ diff --git a/lib/libpolarssl/include/polarssl/sha1.h b/lib/libpolarssl/include/polarssl/sha1.h deleted file mode 100644 index 0bb3ba1..0000000 --- a/lib/libpolarssl/include/polarssl/sha1.h +++ /dev/null @@ -1,180 +0,0 @@ -/** - * \file sha1.h - * - * \brief SHA-1 cryptographic hash function - * - * Copyright (C) 2006-2013, Brainspark B.V. - * - * This file is part of PolarSSL (http://www.polarssl.org) - * Lead Maintainer: Paul Bakker - * - * All rights reserved. - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ -#ifndef POLARSSL_SHA1_H -#define POLARSSL_SHA1_H - -#include "config.h" - -#include - -#ifdef _MSC_VER -#include -typedef UINT32 uint32_t; -#else -#include -#endif - -#define POLARSSL_ERR_SHA1_FILE_IO_ERROR -0x0076 /**< Read/write error in file. */ - -#if !defined(POLARSSL_SHA1_ALT) -// Regular implementation -// - -/** - * \brief SHA-1 context structure - */ -typedef struct -{ - uint32_t total[2]; /*!< number of bytes processed */ - uint32_t state[5]; /*!< intermediate digest state */ - unsigned char buffer[64]; /*!< data block being processed */ - - unsigned char ipad[64]; /*!< HMAC: inner padding */ - unsigned char opad[64]; /*!< HMAC: outer padding */ -} -sha1_context; - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \brief SHA-1 context setup - * - * \param ctx context to be initialized - */ -void sha1_starts( sha1_context *ctx ); - -/** - * \brief SHA-1 process buffer - * - * \param ctx SHA-1 context - * \param input buffer holding the data - * \param ilen length of the input data - */ -void sha1_update( sha1_context *ctx, const unsigned char *input, size_t ilen ); - -/** - * \brief SHA-1 final digest - * - * \param ctx SHA-1 context - * \param output SHA-1 checksum result - */ -void sha1_finish( sha1_context *ctx, unsigned char output[20] ); - -/* Internal use */ -void sha1_process( sha1_context *ctx, const unsigned char data[64] ); - -#ifdef __cplusplus -} -#endif - -#else /* POLARSSL_SHA1_ALT */ -#include "polarssl/sha1_alt.h" -#endif /* POLARSSL_SHA1_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \brief Output = SHA-1( input buffer ) - * - * \param input buffer holding the data - * \param ilen length of the input data - * \param output SHA-1 checksum result - */ -void sha1( const unsigned char *input, size_t ilen, unsigned char output[20] ); - -/** - * \brief Output = SHA-1( file contents ) - * - * \param path input file name - * \param output SHA-1 checksum result - * - * \return 0 if successful, or POLARSSL_ERR_SHA1_FILE_IO_ERROR - */ -int sha1_file( const char *path, unsigned char output[20] ); - -/** - * \brief SHA-1 HMAC context setup - * - * \param ctx HMAC context to be initialized - * \param key HMAC secret key - * \param keylen length of the HMAC key - */ -void sha1_hmac_starts( sha1_context *ctx, const unsigned char *key, size_t keylen ); - -/** - * \brief SHA-1 HMAC process buffer - * - * \param ctx HMAC context - * \param input buffer holding the data - * \param ilen length of the input data - */ -void sha1_hmac_update( sha1_context *ctx, const unsigned char *input, size_t ilen ); - -/** - * \brief SHA-1 HMAC final digest - * - * \param ctx HMAC context - * \param output SHA-1 HMAC checksum result - */ -void sha1_hmac_finish( sha1_context *ctx, unsigned char output[20] ); - -/** - * \brief SHA-1 HMAC context reset - * - * \param ctx HMAC context to be reset - */ -void sha1_hmac_reset( sha1_context *ctx ); - -/** - * \brief Output = HMAC-SHA-1( hmac key, input buffer ) - * - * \param key HMAC secret key - * \param keylen length of the HMAC key - * \param input buffer holding the data - * \param ilen length of the input data - * \param output HMAC-SHA-1 result - */ -void sha1_hmac( const unsigned char *key, size_t keylen, - const unsigned char *input, size_t ilen, - unsigned char output[20] ); - -/** - * \brief Checkup routine - * - * \return 0 if successful, or 1 if the test failed - */ -int sha1_self_test( int verbose ); - -#ifdef __cplusplus -} -#endif - -#endif /* sha1.h */ diff --git a/lib/libpolarssl/include/polarssl/sha2.h b/lib/libpolarssl/include/polarssl/sha2.h deleted file mode 100644 index f271974..0000000 --- a/lib/libpolarssl/include/polarssl/sha2.h +++ /dev/null @@ -1,183 +0,0 @@ -/** - * \file sha2.h - * - * \brief SHA-224 and SHA-256 cryptographic hash function - * - * Copyright (C) 2006-2013, Brainspark B.V. - * - * This file is part of PolarSSL (http://www.polarssl.org) - * Lead Maintainer: Paul Bakker - * - * All rights reserved. - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ -#ifndef POLARSSL_SHA2_H -#define POLARSSL_SHA2_H - -#include "config.h" - -#include - -#ifdef _MSC_VER -#include -typedef UINT32 uint32_t; -#else -#include -#endif - -#define POLARSSL_ERR_SHA2_FILE_IO_ERROR -0x0078 /**< Read/write error in file. */ - -// Regular implementation -// - -/** - * \brief SHA-256 context structure - */ -typedef struct -{ - uint32_t total[2]; /*!< number of bytes processed */ - uint32_t state[8]; /*!< intermediate digest state */ - unsigned char buffer[64]; /*!< data block being processed */ - - unsigned char ipad[64]; /*!< HMAC: inner padding */ - unsigned char opad[64]; /*!< HMAC: outer padding */ - int is224; /*!< 0 => SHA-256, else SHA-224 */ -} -sha2_context; - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \brief SHA-256 context setup - * - * \param ctx context to be initialized - * \param is224 0 = use SHA256, 1 = use SHA224 - */ -void sha2_starts( sha2_context *ctx, int is224 ); - -/** - * \brief SHA-256 process buffer - * - * \param ctx SHA-256 context - * \param input buffer holding the data - * \param ilen length of the input data - */ -void sha2_update( sha2_context *ctx, const unsigned char *input, size_t ilen ); - -/** - * \brief SHA-256 final digest - * - * \param ctx SHA-256 context - * \param output SHA-224/256 checksum result - */ -void sha2_finish( sha2_context *ctx, unsigned char output[32] ); - -/* Internal use */ -void sha2_process( sha2_context *ctx, const unsigned char data[64] ); - -#ifdef __cplusplus -} -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \brief Output = SHA-256( input buffer ) - * - * \param input buffer holding the data - * \param ilen length of the input data - * \param output SHA-224/256 checksum result - * \param is224 0 = use SHA256, 1 = use SHA224 - */ -void sha2( const unsigned char *input, size_t ilen, - unsigned char output[32], int is224 ); - -/** - * \brief Output = SHA-256( file contents ) - * - * \param path input file name - * \param output SHA-224/256 checksum result - * \param is224 0 = use SHA256, 1 = use SHA224 - * - * \return 0 if successful, or POLARSSL_ERR_SHA2_FILE_IO_ERROR - */ -int sha2_file( const char *path, unsigned char output[32], int is224 ); - -/** - * \brief SHA-256 HMAC context setup - * - * \param ctx HMAC context to be initialized - * \param key HMAC secret key - * \param keylen length of the HMAC key - * \param is224 0 = use SHA256, 1 = use SHA224 - */ -void sha2_hmac_starts( sha2_context *ctx, const unsigned char *key, size_t keylen, - int is224 ); - -/** - * \brief SHA-256 HMAC process buffer - * - * \param ctx HMAC context - * \param input buffer holding the data - * \param ilen length of the input data - */ -void sha2_hmac_update( sha2_context *ctx, const unsigned char *input, size_t ilen ); - -/** - * \brief SHA-256 HMAC final digest - * - * \param ctx HMAC context - * \param output SHA-224/256 HMAC checksum result - */ -void sha2_hmac_finish( sha2_context *ctx, unsigned char output[32] ); - -/** - * \brief SHA-256 HMAC context reset - * - * \param ctx HMAC context to be reset - */ -void sha2_hmac_reset( sha2_context *ctx ); - -/** - * \brief Output = HMAC-SHA-256( hmac key, input buffer ) - * - * \param key HMAC secret key - * \param keylen length of the HMAC key - * \param input buffer holding the data - * \param ilen length of the input data - * \param output HMAC-SHA-224/256 result - * \param is224 0 = use SHA256, 1 = use SHA224 - */ -void sha2_hmac( const unsigned char *key, size_t keylen, - const unsigned char *input, size_t ilen, - unsigned char output[32], int is224 ); - -/** - * \brief Checkup routine - * - * \return 0 if successful, or 1 if the test failed - */ -int sha2_self_test( int verbose ); - -#ifdef __cplusplus -} -#endif - -#endif /* sha2.h */ diff --git a/lib/libpolarssl/include/polarssl/sha4.h b/lib/libpolarssl/include/polarssl/sha4.h deleted file mode 100644 index fa57d4d..0000000 --- a/lib/libpolarssl/include/polarssl/sha4.h +++ /dev/null @@ -1,183 +0,0 @@ -/** - * \file sha4.h - * - * \brief SHA-384 and SHA-512 cryptographic hash function - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved - * - * This file is part of mbed TLS (https://polarssl.org) - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ -#ifndef POLARSSL_SHA4_H -#define POLARSSL_SHA4_H - -#include "config.h" - -#include - -#if defined(_MSC_VER) || defined(__WATCOMC__) - #define UL64(x) x##ui64 - typedef unsigned __int64 uint64_t; -#else - #include - #define UL64(x) x##ULL -#endif - -#define POLARSSL_ERR_SHA4_FILE_IO_ERROR -0x007A /**< Read/write error in file. */ - -#if !defined(POLARSSL_SHA1_ALT) -// Regular implementation -// - -/** - * \brief SHA-512 context structure - */ -typedef struct -{ - uint64_t total[2]; /*!< number of bytes processed */ - uint64_t state[8]; /*!< intermediate digest state */ - unsigned char buffer[128]; /*!< data block being processed */ - - unsigned char ipad[128]; /*!< HMAC: inner padding */ - unsigned char opad[128]; /*!< HMAC: outer padding */ - int is384; /*!< 0 => SHA-512, else SHA-384 */ -} -sha4_context; - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \brief SHA-512 context setup - * - * \param ctx context to be initialized - * \param is384 0 = use SHA512, 1 = use SHA384 - */ -void sha4_starts( sha4_context *ctx, int is384 ); - -/** - * \brief SHA-512 process buffer - * - * \param ctx SHA-512 context - * \param input buffer holding the data - * \param ilen length of the input data - */ -void sha4_update( sha4_context *ctx, const unsigned char *input, size_t ilen ); - -/** - * \brief SHA-512 final digest - * - * \param ctx SHA-512 context - * \param output SHA-384/512 checksum result - */ -void sha4_finish( sha4_context *ctx, unsigned char output[64] ); - -#ifdef __cplusplus -} -#endif - -#else /* POLARSSL_SHA4_ALT */ -#include "sha4_alt.h" -#endif /* POLARSSL_SHA4_ALT */ - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \brief Output = SHA-512( input buffer ) - * - * \param input buffer holding the data - * \param ilen length of the input data - * \param output SHA-384/512 checksum result - * \param is384 0 = use SHA512, 1 = use SHA384 - */ -void sha4( const unsigned char *input, size_t ilen, - unsigned char output[64], int is384 ); - -/** - * \brief Output = SHA-512( file contents ) - * - * \param path input file name - * \param output SHA-384/512 checksum result - * \param is384 0 = use SHA512, 1 = use SHA384 - * - * \return 0 if successful, or POLARSSL_ERR_SHA4_FILE_IO_ERROR - */ -int sha4_file( const char *path, unsigned char output[64], int is384 ); - -/** - * \brief SHA-512 HMAC context setup - * - * \param ctx HMAC context to be initialized - * \param is384 0 = use SHA512, 1 = use SHA384 - * \param key HMAC secret key - * \param keylen length of the HMAC key - */ -void sha4_hmac_starts( sha4_context *ctx, const unsigned char *key, size_t keylen, - int is384 ); - -/** - * \brief SHA-512 HMAC process buffer - * - * \param ctx HMAC context - * \param input buffer holding the data - * \param ilen length of the input data - */ -void sha4_hmac_update( sha4_context *ctx, const unsigned char *input, size_t ilen ); - -/** - * \brief SHA-512 HMAC final digest - * - * \param ctx HMAC context - * \param output SHA-384/512 HMAC checksum result - */ -void sha4_hmac_finish( sha4_context *ctx, unsigned char output[64] ); - -/** - * \brief SHA-512 HMAC context reset - * - * \param ctx HMAC context to be reset - */ -void sha4_hmac_reset( sha4_context *ctx ); - -/** - * \brief Output = HMAC-SHA-512( hmac key, input buffer ) - * - * \param key HMAC secret key - * \param keylen length of the HMAC key - * \param input buffer holding the data - * \param ilen length of the input data - * \param output HMAC-SHA-384/512 result - * \param is384 0 = use SHA512, 1 = use SHA384 - */ -void sha4_hmac( const unsigned char *key, size_t keylen, - const unsigned char *input, size_t ilen, - unsigned char output[64], int is384 ); - -/** - * \brief Checkup routine - * - * \return 0 if successful, or 1 if the test failed - */ -int sha4_self_test( int verbose ); - -#ifdef __cplusplus -} -#endif - -#endif /* sha4.h */ diff --git a/lib/libpolarssl/libpolarssl.vcxproj b/lib/libpolarssl/libpolarssl.vcxproj deleted file mode 100644 index e392881..0000000 --- a/lib/libpolarssl/libpolarssl.vcxproj +++ /dev/null @@ -1,156 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 15.0 - {394EFC16-BD3A-4538-B33D-7BA1EDB8DAC1} - 10.0.16299.0 - - - - StaticLibrary - true - v141 - MultiByte - - - StaticLibrary - false - v141 - true - MultiByte - - - StaticLibrary - true - v141 - MultiByte - - - StaticLibrary - false - v141 - true - MultiByte - - - - - - - - - - - - - - - - - - - - - - - Level3 - Disabled - true - ..\libpolarssl\include; - _MBCS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - - - Level3 - Disabled - true - ..\libpolarssl\include; - _MBCS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - - - Level3 - MaxSpeed - true - true - true - ..\libpolarssl\include; - _MBCS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - true - true - - - - - Level3 - MaxSpeed - true - true - true - ..\libpolarssl\include; - _MBCS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - true - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/lib/libpolarssl/libpolarssl.vcxproj.filters b/lib/libpolarssl/libpolarssl.vcxproj.filters deleted file mode 100644 index 035cf2a..0000000 --- a/lib/libpolarssl/libpolarssl.vcxproj.filters +++ /dev/null @@ -1,102 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - \ No newline at end of file diff --git a/lib/libpolarssl/libpolarssl.vcxproj.user b/lib/libpolarssl/libpolarssl.vcxproj.user deleted file mode 100644 index be25078..0000000 --- a/lib/libpolarssl/libpolarssl.vcxproj.user +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/lib/libpolarssl/makefile b/lib/libpolarssl/makefile deleted file mode 100644 index 95b8e7c..0000000 --- a/lib/libpolarssl/makefile +++ /dev/null @@ -1,45 +0,0 @@ -# Sources -SRC_DIR = source -OBJS = $(foreach dir,$(SRC_DIR),$(subst .c,.o,$(wildcard $(dir)/*.c))) - -# External dependencies -DEPENDS = -LIB_DIR = .. -INCS = -I"include" $(foreach dep,$(DEPENDS), -I"$(LIB_DIR)/lib$(dep)/include") - -# Compiler Settings -CXXFLAGS = -std=c++11 $(INCS) -D__STDC_FORMAT_MACROS -Wall -Wno-unused-value -CFLAGS = -std=c11 $(INCS) -Wall -Wno-unused-value -ARFLAGS = cr -o -ifeq ($(OS),Windows_NT) - # Windows Only Flags/Libs - CC = x86_64-w64-mingw32-gcc - CXX = x86_64-w64-mingw32-g++ - CFLAGS += -Wno-unused-but-set-variable - CXXFLAGS += -Wno-unused-but-set-variable -else - UNAME = $(shell uname -s) - ifeq ($(UNAME), Darwin) - # MacOS Only Flags/Libs - CFLAGS += -arch x86_64 -Wno-unused-private-field - CXXFLAGS += -arch x86_64 -Wno-unused-private-field - ARFLAGS = rc - else - # *nix Only Flags/Libs - CFLAGS += -Wno-unused-but-set-variable - CXXFLAGS += -Wno-unused-but-set-variable - endif -endif - -# Output -OUTPUT = $(shell basename "$(CURDIR)").a - -main: build - -rebuild: clean build - -build: $(OBJS) - ar $(ARFLAGS) $(OUTPUT) $(OBJS) - -clean: - rm -rf $(OUTPUT) $(OBJS) \ No newline at end of file diff --git a/lib/libpolarssl/source/aes.c b/lib/libpolarssl/source/aes.c deleted file mode 100644 index f8293e6..0000000 --- a/lib/libpolarssl/source/aes.c +++ /dev/null @@ -1,1352 +0,0 @@ -/* - * FIPS-197 compliant AES implementation - * - * Copyright (C) 2006-2013, Brainspark B.V. - * - * This file is part of PolarSSL (http://www.polarssl.org) - * Lead Maintainer: Paul Bakker - * - * All rights reserved. - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ -/* - * The AES block cipher was designed by Vincent Rijmen and Joan Daemen. - * - * http://csrc.nist.gov/encryption/aes/rijndael/Rijndael.pdf - * http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf - */ - -#include - -#if defined(POLARSSL_AES_C) - -#include -#if defined(POLARSSL_PADLOCK_C) -#include -#endif - -#if !defined(POLARSSL_AES_ALT) - -/* - * 32-bit integer manipulation macros (little endian) - */ -#ifndef GET_UINT32_LE -#define GET_UINT32_LE(n,b,i) \ -{ \ - (n) = ( (uint32_t) (b)[(i) ] ) \ - | ( (uint32_t) (b)[(i) + 1] << 8 ) \ - | ( (uint32_t) (b)[(i) + 2] << 16 ) \ - | ( (uint32_t) (b)[(i) + 3] << 24 ); \ -} -#endif - -#ifndef PUT_UINT32_LE -#define PUT_UINT32_LE(n,b,i) \ -{ \ - (b)[(i) ] = (unsigned char) ( (n) ); \ - (b)[(i) + 1] = (unsigned char) ( (n) >> 8 ); \ - (b)[(i) + 2] = (unsigned char) ( (n) >> 16 ); \ - (b)[(i) + 3] = (unsigned char) ( (n) >> 24 ); \ -} -#endif - -#if defined(POLARSSL_PADLOCK_C) && \ - ( defined(POLARSSL_HAVE_X86) || defined(PADLOCK_ALIGN16) ) -static int aes_padlock_ace = -1; -#endif - -#if defined(POLARSSL_AES_ROM_TABLES) -/* - * Forward S-box - */ -static const unsigned char FSb[256] = -{ - 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, - 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, - 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, - 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, - 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, - 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, - 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, - 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, - 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, - 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, - 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, - 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, - 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, - 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, - 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, - 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, - 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, - 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, - 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, - 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, - 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, - 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, - 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, - 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, - 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, - 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, - 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, - 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, - 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, - 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, - 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, - 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 -}; - -/* - * Forward tables - */ -#define FT \ -\ - V(A5,63,63,C6), V(84,7C,7C,F8), V(99,77,77,EE), V(8D,7B,7B,F6), \ - V(0D,F2,F2,FF), V(BD,6B,6B,D6), V(B1,6F,6F,DE), V(54,C5,C5,91), \ - V(50,30,30,60), V(03,01,01,02), V(A9,67,67,CE), V(7D,2B,2B,56), \ - V(19,FE,FE,E7), V(62,D7,D7,B5), V(E6,AB,AB,4D), V(9A,76,76,EC), \ - V(45,CA,CA,8F), V(9D,82,82,1F), V(40,C9,C9,89), V(87,7D,7D,FA), \ - V(15,FA,FA,EF), V(EB,59,59,B2), V(C9,47,47,8E), V(0B,F0,F0,FB), \ - V(EC,AD,AD,41), V(67,D4,D4,B3), V(FD,A2,A2,5F), V(EA,AF,AF,45), \ - V(BF,9C,9C,23), V(F7,A4,A4,53), V(96,72,72,E4), V(5B,C0,C0,9B), \ - V(C2,B7,B7,75), V(1C,FD,FD,E1), V(AE,93,93,3D), V(6A,26,26,4C), \ - V(5A,36,36,6C), V(41,3F,3F,7E), V(02,F7,F7,F5), V(4F,CC,CC,83), \ - V(5C,34,34,68), V(F4,A5,A5,51), V(34,E5,E5,D1), V(08,F1,F1,F9), \ - V(93,71,71,E2), V(73,D8,D8,AB), V(53,31,31,62), V(3F,15,15,2A), \ - V(0C,04,04,08), V(52,C7,C7,95), V(65,23,23,46), V(5E,C3,C3,9D), \ - V(28,18,18,30), V(A1,96,96,37), V(0F,05,05,0A), V(B5,9A,9A,2F), \ - V(09,07,07,0E), V(36,12,12,24), V(9B,80,80,1B), V(3D,E2,E2,DF), \ - V(26,EB,EB,CD), V(69,27,27,4E), V(CD,B2,B2,7F), V(9F,75,75,EA), \ - V(1B,09,09,12), V(9E,83,83,1D), V(74,2C,2C,58), V(2E,1A,1A,34), \ - V(2D,1B,1B,36), V(B2,6E,6E,DC), V(EE,5A,5A,B4), V(FB,A0,A0,5B), \ - V(F6,52,52,A4), V(4D,3B,3B,76), V(61,D6,D6,B7), V(CE,B3,B3,7D), \ - V(7B,29,29,52), V(3E,E3,E3,DD), V(71,2F,2F,5E), V(97,84,84,13), \ - V(F5,53,53,A6), V(68,D1,D1,B9), V(00,00,00,00), V(2C,ED,ED,C1), \ - V(60,20,20,40), V(1F,FC,FC,E3), V(C8,B1,B1,79), V(ED,5B,5B,B6), \ - V(BE,6A,6A,D4), V(46,CB,CB,8D), V(D9,BE,BE,67), V(4B,39,39,72), \ - V(DE,4A,4A,94), V(D4,4C,4C,98), V(E8,58,58,B0), V(4A,CF,CF,85), \ - V(6B,D0,D0,BB), V(2A,EF,EF,C5), V(E5,AA,AA,4F), V(16,FB,FB,ED), \ - V(C5,43,43,86), V(D7,4D,4D,9A), V(55,33,33,66), V(94,85,85,11), \ - V(CF,45,45,8A), V(10,F9,F9,E9), V(06,02,02,04), V(81,7F,7F,FE), \ - V(F0,50,50,A0), V(44,3C,3C,78), V(BA,9F,9F,25), V(E3,A8,A8,4B), \ - V(F3,51,51,A2), V(FE,A3,A3,5D), V(C0,40,40,80), V(8A,8F,8F,05), \ - V(AD,92,92,3F), V(BC,9D,9D,21), V(48,38,38,70), V(04,F5,F5,F1), \ - V(DF,BC,BC,63), V(C1,B6,B6,77), V(75,DA,DA,AF), V(63,21,21,42), \ - V(30,10,10,20), V(1A,FF,FF,E5), V(0E,F3,F3,FD), V(6D,D2,D2,BF), \ - V(4C,CD,CD,81), V(14,0C,0C,18), V(35,13,13,26), V(2F,EC,EC,C3), \ - V(E1,5F,5F,BE), V(A2,97,97,35), V(CC,44,44,88), V(39,17,17,2E), \ - V(57,C4,C4,93), V(F2,A7,A7,55), V(82,7E,7E,FC), V(47,3D,3D,7A), \ - V(AC,64,64,C8), V(E7,5D,5D,BA), V(2B,19,19,32), V(95,73,73,E6), \ - V(A0,60,60,C0), V(98,81,81,19), V(D1,4F,4F,9E), V(7F,DC,DC,A3), \ - V(66,22,22,44), V(7E,2A,2A,54), V(AB,90,90,3B), V(83,88,88,0B), \ - V(CA,46,46,8C), V(29,EE,EE,C7), V(D3,B8,B8,6B), V(3C,14,14,28), \ - V(79,DE,DE,A7), V(E2,5E,5E,BC), V(1D,0B,0B,16), V(76,DB,DB,AD), \ - V(3B,E0,E0,DB), V(56,32,32,64), V(4E,3A,3A,74), V(1E,0A,0A,14), \ - V(DB,49,49,92), V(0A,06,06,0C), V(6C,24,24,48), V(E4,5C,5C,B8), \ - V(5D,C2,C2,9F), V(6E,D3,D3,BD), V(EF,AC,AC,43), V(A6,62,62,C4), \ - V(A8,91,91,39), V(A4,95,95,31), V(37,E4,E4,D3), V(8B,79,79,F2), \ - V(32,E7,E7,D5), V(43,C8,C8,8B), V(59,37,37,6E), V(B7,6D,6D,DA), \ - V(8C,8D,8D,01), V(64,D5,D5,B1), V(D2,4E,4E,9C), V(E0,A9,A9,49), \ - V(B4,6C,6C,D8), V(FA,56,56,AC), V(07,F4,F4,F3), V(25,EA,EA,CF), \ - V(AF,65,65,CA), V(8E,7A,7A,F4), V(E9,AE,AE,47), V(18,08,08,10), \ - V(D5,BA,BA,6F), V(88,78,78,F0), V(6F,25,25,4A), V(72,2E,2E,5C), \ - V(24,1C,1C,38), V(F1,A6,A6,57), V(C7,B4,B4,73), V(51,C6,C6,97), \ - V(23,E8,E8,CB), V(7C,DD,DD,A1), V(9C,74,74,E8), V(21,1F,1F,3E), \ - V(DD,4B,4B,96), V(DC,BD,BD,61), V(86,8B,8B,0D), V(85,8A,8A,0F), \ - V(90,70,70,E0), V(42,3E,3E,7C), V(C4,B5,B5,71), V(AA,66,66,CC), \ - V(D8,48,48,90), V(05,03,03,06), V(01,F6,F6,F7), V(12,0E,0E,1C), \ - V(A3,61,61,C2), V(5F,35,35,6A), V(F9,57,57,AE), V(D0,B9,B9,69), \ - V(91,86,86,17), V(58,C1,C1,99), V(27,1D,1D,3A), V(B9,9E,9E,27), \ - V(38,E1,E1,D9), V(13,F8,F8,EB), V(B3,98,98,2B), V(33,11,11,22), \ - V(BB,69,69,D2), V(70,D9,D9,A9), V(89,8E,8E,07), V(A7,94,94,33), \ - V(B6,9B,9B,2D), V(22,1E,1E,3C), V(92,87,87,15), V(20,E9,E9,C9), \ - V(49,CE,CE,87), V(FF,55,55,AA), V(78,28,28,50), V(7A,DF,DF,A5), \ - V(8F,8C,8C,03), V(F8,A1,A1,59), V(80,89,89,09), V(17,0D,0D,1A), \ - V(DA,BF,BF,65), V(31,E6,E6,D7), V(C6,42,42,84), V(B8,68,68,D0), \ - V(C3,41,41,82), V(B0,99,99,29), V(77,2D,2D,5A), V(11,0F,0F,1E), \ - V(CB,B0,B0,7B), V(FC,54,54,A8), V(D6,BB,BB,6D), V(3A,16,16,2C) - -#define V(a,b,c,d) 0x##a##b##c##d -static const uint32_t FT0[256] = { FT }; -#undef V - -#define V(a,b,c,d) 0x##b##c##d##a -static const uint32_t FT1[256] = { FT }; -#undef V - -#define V(a,b,c,d) 0x##c##d##a##b -static const uint32_t FT2[256] = { FT }; -#undef V - -#define V(a,b,c,d) 0x##d##a##b##c -static const uint32_t FT3[256] = { FT }; -#undef V - -#undef FT - -/* - * Reverse S-box - */ -static const unsigned char RSb[256] = -{ - 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, - 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB, - 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, - 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, - 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, - 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, - 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, - 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, - 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, - 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, - 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, - 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, - 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, - 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, - 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, - 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, - 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, - 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, - 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, - 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E, - 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, - 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, - 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, - 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, - 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, - 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, - 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, - 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, - 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, - 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, - 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, - 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D -}; - -/* - * Reverse tables - */ -#define RT \ -\ - V(50,A7,F4,51), V(53,65,41,7E), V(C3,A4,17,1A), V(96,5E,27,3A), \ - V(CB,6B,AB,3B), V(F1,45,9D,1F), V(AB,58,FA,AC), V(93,03,E3,4B), \ - V(55,FA,30,20), V(F6,6D,76,AD), V(91,76,CC,88), V(25,4C,02,F5), \ - V(FC,D7,E5,4F), V(D7,CB,2A,C5), V(80,44,35,26), V(8F,A3,62,B5), \ - V(49,5A,B1,DE), V(67,1B,BA,25), V(98,0E,EA,45), V(E1,C0,FE,5D), \ - V(02,75,2F,C3), V(12,F0,4C,81), V(A3,97,46,8D), V(C6,F9,D3,6B), \ - V(E7,5F,8F,03), V(95,9C,92,15), V(EB,7A,6D,BF), V(DA,59,52,95), \ - V(2D,83,BE,D4), V(D3,21,74,58), V(29,69,E0,49), V(44,C8,C9,8E), \ - V(6A,89,C2,75), V(78,79,8E,F4), V(6B,3E,58,99), V(DD,71,B9,27), \ - V(B6,4F,E1,BE), V(17,AD,88,F0), V(66,AC,20,C9), V(B4,3A,CE,7D), \ - V(18,4A,DF,63), V(82,31,1A,E5), V(60,33,51,97), V(45,7F,53,62), \ - V(E0,77,64,B1), V(84,AE,6B,BB), V(1C,A0,81,FE), V(94,2B,08,F9), \ - V(58,68,48,70), V(19,FD,45,8F), V(87,6C,DE,94), V(B7,F8,7B,52), \ - V(23,D3,73,AB), V(E2,02,4B,72), V(57,8F,1F,E3), V(2A,AB,55,66), \ - V(07,28,EB,B2), V(03,C2,B5,2F), V(9A,7B,C5,86), V(A5,08,37,D3), \ - V(F2,87,28,30), V(B2,A5,BF,23), V(BA,6A,03,02), V(5C,82,16,ED), \ - V(2B,1C,CF,8A), V(92,B4,79,A7), V(F0,F2,07,F3), V(A1,E2,69,4E), \ - V(CD,F4,DA,65), V(D5,BE,05,06), V(1F,62,34,D1), V(8A,FE,A6,C4), \ - V(9D,53,2E,34), V(A0,55,F3,A2), V(32,E1,8A,05), V(75,EB,F6,A4), \ - V(39,EC,83,0B), V(AA,EF,60,40), V(06,9F,71,5E), V(51,10,6E,BD), \ - V(F9,8A,21,3E), V(3D,06,DD,96), V(AE,05,3E,DD), V(46,BD,E6,4D), \ - V(B5,8D,54,91), V(05,5D,C4,71), V(6F,D4,06,04), V(FF,15,50,60), \ - V(24,FB,98,19), V(97,E9,BD,D6), V(CC,43,40,89), V(77,9E,D9,67), \ - V(BD,42,E8,B0), V(88,8B,89,07), V(38,5B,19,E7), V(DB,EE,C8,79), \ - V(47,0A,7C,A1), V(E9,0F,42,7C), V(C9,1E,84,F8), V(00,00,00,00), \ - V(83,86,80,09), V(48,ED,2B,32), V(AC,70,11,1E), V(4E,72,5A,6C), \ - V(FB,FF,0E,FD), V(56,38,85,0F), V(1E,D5,AE,3D), V(27,39,2D,36), \ - V(64,D9,0F,0A), V(21,A6,5C,68), V(D1,54,5B,9B), V(3A,2E,36,24), \ - V(B1,67,0A,0C), V(0F,E7,57,93), V(D2,96,EE,B4), V(9E,91,9B,1B), \ - V(4F,C5,C0,80), V(A2,20,DC,61), V(69,4B,77,5A), V(16,1A,12,1C), \ - V(0A,BA,93,E2), V(E5,2A,A0,C0), V(43,E0,22,3C), V(1D,17,1B,12), \ - V(0B,0D,09,0E), V(AD,C7,8B,F2), V(B9,A8,B6,2D), V(C8,A9,1E,14), \ - V(85,19,F1,57), V(4C,07,75,AF), V(BB,DD,99,EE), V(FD,60,7F,A3), \ - V(9F,26,01,F7), V(BC,F5,72,5C), V(C5,3B,66,44), V(34,7E,FB,5B), \ - V(76,29,43,8B), V(DC,C6,23,CB), V(68,FC,ED,B6), V(63,F1,E4,B8), \ - V(CA,DC,31,D7), V(10,85,63,42), V(40,22,97,13), V(20,11,C6,84), \ - V(7D,24,4A,85), V(F8,3D,BB,D2), V(11,32,F9,AE), V(6D,A1,29,C7), \ - V(4B,2F,9E,1D), V(F3,30,B2,DC), V(EC,52,86,0D), V(D0,E3,C1,77), \ - V(6C,16,B3,2B), V(99,B9,70,A9), V(FA,48,94,11), V(22,64,E9,47), \ - V(C4,8C,FC,A8), V(1A,3F,F0,A0), V(D8,2C,7D,56), V(EF,90,33,22), \ - V(C7,4E,49,87), V(C1,D1,38,D9), V(FE,A2,CA,8C), V(36,0B,D4,98), \ - V(CF,81,F5,A6), V(28,DE,7A,A5), V(26,8E,B7,DA), V(A4,BF,AD,3F), \ - V(E4,9D,3A,2C), V(0D,92,78,50), V(9B,CC,5F,6A), V(62,46,7E,54), \ - V(C2,13,8D,F6), V(E8,B8,D8,90), V(5E,F7,39,2E), V(F5,AF,C3,82), \ - V(BE,80,5D,9F), V(7C,93,D0,69), V(A9,2D,D5,6F), V(B3,12,25,CF), \ - V(3B,99,AC,C8), V(A7,7D,18,10), V(6E,63,9C,E8), V(7B,BB,3B,DB), \ - V(09,78,26,CD), V(F4,18,59,6E), V(01,B7,9A,EC), V(A8,9A,4F,83), \ - V(65,6E,95,E6), V(7E,E6,FF,AA), V(08,CF,BC,21), V(E6,E8,15,EF), \ - V(D9,9B,E7,BA), V(CE,36,6F,4A), V(D4,09,9F,EA), V(D6,7C,B0,29), \ - V(AF,B2,A4,31), V(31,23,3F,2A), V(30,94,A5,C6), V(C0,66,A2,35), \ - V(37,BC,4E,74), V(A6,CA,82,FC), V(B0,D0,90,E0), V(15,D8,A7,33), \ - V(4A,98,04,F1), V(F7,DA,EC,41), V(0E,50,CD,7F), V(2F,F6,91,17), \ - V(8D,D6,4D,76), V(4D,B0,EF,43), V(54,4D,AA,CC), V(DF,04,96,E4), \ - V(E3,B5,D1,9E), V(1B,88,6A,4C), V(B8,1F,2C,C1), V(7F,51,65,46), \ - V(04,EA,5E,9D), V(5D,35,8C,01), V(73,74,87,FA), V(2E,41,0B,FB), \ - V(5A,1D,67,B3), V(52,D2,DB,92), V(33,56,10,E9), V(13,47,D6,6D), \ - V(8C,61,D7,9A), V(7A,0C,A1,37), V(8E,14,F8,59), V(89,3C,13,EB), \ - V(EE,27,A9,CE), V(35,C9,61,B7), V(ED,E5,1C,E1), V(3C,B1,47,7A), \ - V(59,DF,D2,9C), V(3F,73,F2,55), V(79,CE,14,18), V(BF,37,C7,73), \ - V(EA,CD,F7,53), V(5B,AA,FD,5F), V(14,6F,3D,DF), V(86,DB,44,78), \ - V(81,F3,AF,CA), V(3E,C4,68,B9), V(2C,34,24,38), V(5F,40,A3,C2), \ - V(72,C3,1D,16), V(0C,25,E2,BC), V(8B,49,3C,28), V(41,95,0D,FF), \ - V(71,01,A8,39), V(DE,B3,0C,08), V(9C,E4,B4,D8), V(90,C1,56,64), \ - V(61,84,CB,7B), V(70,B6,32,D5), V(74,5C,6C,48), V(42,57,B8,D0) - -#define V(a,b,c,d) 0x##a##b##c##d -static const uint32_t RT0[256] = { RT }; -#undef V - -#define V(a,b,c,d) 0x##b##c##d##a -static const uint32_t RT1[256] = { RT }; -#undef V - -#define V(a,b,c,d) 0x##c##d##a##b -static const uint32_t RT2[256] = { RT }; -#undef V - -#define V(a,b,c,d) 0x##d##a##b##c -static const uint32_t RT3[256] = { RT }; -#undef V - -#undef RT - -/* - * Round constants - */ -static const uint32_t RCON[10] = -{ - 0x00000001, 0x00000002, 0x00000004, 0x00000008, - 0x00000010, 0x00000020, 0x00000040, 0x00000080, - 0x0000001B, 0x00000036 -}; - -#else - -/* - * Forward S-box & tables - */ -static unsigned char FSb[256]; -static uint32_t FT0[256]; -static uint32_t FT1[256]; -static uint32_t FT2[256]; -static uint32_t FT3[256]; - -/* - * Reverse S-box & tables - */ -static unsigned char RSb[256]; -static uint32_t RT0[256]; -static uint32_t RT1[256]; -static uint32_t RT2[256]; -static uint32_t RT3[256]; - -/* - * Round constants - */ -static uint32_t RCON[10]; - -/* - * Tables generation code - */ -#define ROTL8(x) ( ( x << 8 ) & 0xFFFFFFFF ) | ( x >> 24 ) -#define XTIME(x) ( ( x << 1 ) ^ ( ( x & 0x80 ) ? 0x1B : 0x00 ) ) -#define MUL(x,y) ( ( x && y ) ? pow[(log[x]+log[y]) % 255] : 0 ) - -static int aes_init_done = 0; - -static void aes_gen_tables( void ) -{ - int i, x, y, z; - int pow[256]; - int log[256]; - - /* - * compute pow and log tables over GF(2^8) - */ - for( i = 0, x = 1; i < 256; i++ ) - { - pow[i] = x; - log[x] = i; - x = ( x ^ XTIME( x ) ) & 0xFF; - } - - /* - * calculate the round constants - */ - for( i = 0, x = 1; i < 10; i++ ) - { - RCON[i] = (uint32_t) x; - x = XTIME( x ) & 0xFF; - } - - /* - * generate the forward and reverse S-boxes - */ - FSb[0x00] = 0x63; - RSb[0x63] = 0x00; - - for( i = 1; i < 256; i++ ) - { - x = pow[255 - log[i]]; - - y = x; y = ( (y << 1) | (y >> 7) ) & 0xFF; - x ^= y; y = ( (y << 1) | (y >> 7) ) & 0xFF; - x ^= y; y = ( (y << 1) | (y >> 7) ) & 0xFF; - x ^= y; y = ( (y << 1) | (y >> 7) ) & 0xFF; - x ^= y ^ 0x63; - - FSb[i] = (unsigned char) x; - RSb[x] = (unsigned char) i; - } - - /* - * generate the forward and reverse tables - */ - for( i = 0; i < 256; i++ ) - { - x = FSb[i]; - y = XTIME( x ) & 0xFF; - z = ( y ^ x ) & 0xFF; - - FT0[i] = ( (uint32_t) y ) ^ - ( (uint32_t) x << 8 ) ^ - ( (uint32_t) x << 16 ) ^ - ( (uint32_t) z << 24 ); - - FT1[i] = ROTL8( FT0[i] ); - FT2[i] = ROTL8( FT1[i] ); - FT3[i] = ROTL8( FT2[i] ); - - x = RSb[i]; - - RT0[i] = ( (uint32_t) MUL( 0x0E, x ) ) ^ - ( (uint32_t) MUL( 0x09, x ) << 8 ) ^ - ( (uint32_t) MUL( 0x0D, x ) << 16 ) ^ - ( (uint32_t) MUL( 0x0B, x ) << 24 ); - - RT1[i] = ROTL8( RT0[i] ); - RT2[i] = ROTL8( RT1[i] ); - RT3[i] = ROTL8( RT2[i] ); - } -} - -#endif - -/* - * AES key schedule (encryption) - */ -int aes_setkey_enc( aes_context *ctx, const unsigned char *key, unsigned int keysize ) -{ - unsigned int i; - uint32_t *RK; - -#if !defined(POLARSSL_AES_ROM_TABLES) - if( aes_init_done == 0 ) - { - aes_gen_tables(); - aes_init_done = 1; - - } -#endif - - switch( keysize ) - { - case 128: ctx->nr = 10; break; - case 192: ctx->nr = 12; break; - case 256: ctx->nr = 14; break; - default : return( POLARSSL_ERR_AES_INVALID_KEY_LENGTH ); - } - -#if defined(POLARSSL_PADLOCK_C) && defined(PADLOCK_ALIGN16) - if( aes_padlock_ace == -1 ) - aes_padlock_ace = padlock_supports( PADLOCK_ACE ); - - if( aes_padlock_ace ) - ctx->rk = RK = PADLOCK_ALIGN16( ctx->buf ); - else -#endif - ctx->rk = RK = ctx->buf; - - for( i = 0; i < (keysize >> 5); i++ ) - { - GET_UINT32_LE( RK[i], key, i << 2 ); - } - - switch( ctx->nr ) - { - case 10: - - for( i = 0; i < 10; i++, RK += 4 ) - { - RK[4] = RK[0] ^ RCON[i] ^ - ( (uint32_t) FSb[ ( RK[3] >> 8 ) & 0xFF ] ) ^ - ( (uint32_t) FSb[ ( RK[3] >> 16 ) & 0xFF ] << 8 ) ^ - ( (uint32_t) FSb[ ( RK[3] >> 24 ) & 0xFF ] << 16 ) ^ - ( (uint32_t) FSb[ ( RK[3] ) & 0xFF ] << 24 ); - - RK[5] = RK[1] ^ RK[4]; - RK[6] = RK[2] ^ RK[5]; - RK[7] = RK[3] ^ RK[6]; - } - break; - - case 12: - - for( i = 0; i < 8; i++, RK += 6 ) - { - RK[6] = RK[0] ^ RCON[i] ^ - ( (uint32_t) FSb[ ( RK[5] >> 8 ) & 0xFF ] ) ^ - ( (uint32_t) FSb[ ( RK[5] >> 16 ) & 0xFF ] << 8 ) ^ - ( (uint32_t) FSb[ ( RK[5] >> 24 ) & 0xFF ] << 16 ) ^ - ( (uint32_t) FSb[ ( RK[5] ) & 0xFF ] << 24 ); - - RK[7] = RK[1] ^ RK[6]; - RK[8] = RK[2] ^ RK[7]; - RK[9] = RK[3] ^ RK[8]; - RK[10] = RK[4] ^ RK[9]; - RK[11] = RK[5] ^ RK[10]; - } - break; - - case 14: - - for( i = 0; i < 7; i++, RK += 8 ) - { - RK[8] = RK[0] ^ RCON[i] ^ - ( (uint32_t) FSb[ ( RK[7] >> 8 ) & 0xFF ] ) ^ - ( (uint32_t) FSb[ ( RK[7] >> 16 ) & 0xFF ] << 8 ) ^ - ( (uint32_t) FSb[ ( RK[7] >> 24 ) & 0xFF ] << 16 ) ^ - ( (uint32_t) FSb[ ( RK[7] ) & 0xFF ] << 24 ); - - RK[9] = RK[1] ^ RK[8]; - RK[10] = RK[2] ^ RK[9]; - RK[11] = RK[3] ^ RK[10]; - - RK[12] = RK[4] ^ - ( (uint32_t) FSb[ ( RK[11] ) & 0xFF ] ) ^ - ( (uint32_t) FSb[ ( RK[11] >> 8 ) & 0xFF ] << 8 ) ^ - ( (uint32_t) FSb[ ( RK[11] >> 16 ) & 0xFF ] << 16 ) ^ - ( (uint32_t) FSb[ ( RK[11] >> 24 ) & 0xFF ] << 24 ); - - RK[13] = RK[5] ^ RK[12]; - RK[14] = RK[6] ^ RK[13]; - RK[15] = RK[7] ^ RK[14]; - } - break; - - default: - - break; - } - - return( 0 ); -} - -/* - * AES key schedule (decryption) - */ -int aes_setkey_dec( aes_context *ctx, const unsigned char *key, unsigned int keysize ) -{ - int i, j; - aes_context cty; - uint32_t *RK; - uint32_t *SK; - int ret; - - switch( keysize ) - { - case 128: ctx->nr = 10; break; - case 192: ctx->nr = 12; break; - case 256: ctx->nr = 14; break; - default : return( POLARSSL_ERR_AES_INVALID_KEY_LENGTH ); - } - -#if defined(POLARSSL_PADLOCK_C) && defined(PADLOCK_ALIGN16) - if( aes_padlock_ace == -1 ) - aes_padlock_ace = padlock_supports( PADLOCK_ACE ); - - if( aes_padlock_ace ) - ctx->rk = RK = PADLOCK_ALIGN16( ctx->buf ); - else -#endif - ctx->rk = RK = ctx->buf; - - ret = aes_setkey_enc( &cty, key, keysize ); - if( ret != 0 ) - return( ret ); - - SK = cty.rk + cty.nr * 4; - - *RK++ = *SK++; - *RK++ = *SK++; - *RK++ = *SK++; - *RK++ = *SK++; - - for( i = ctx->nr - 1, SK -= 8; i > 0; i--, SK -= 8 ) - { - for( j = 0; j < 4; j++, SK++ ) - { - *RK++ = RT0[ FSb[ ( *SK ) & 0xFF ] ] ^ - RT1[ FSb[ ( *SK >> 8 ) & 0xFF ] ] ^ - RT2[ FSb[ ( *SK >> 16 ) & 0xFF ] ] ^ - RT3[ FSb[ ( *SK >> 24 ) & 0xFF ] ]; - } - } - - *RK++ = *SK++; - *RK++ = *SK++; - *RK++ = *SK++; - *RK++ = *SK++; - - memset( &cty, 0, sizeof( aes_context ) ); - - return( 0 ); -} - -#define AES_FROUND(X0,X1,X2,X3,Y0,Y1,Y2,Y3) \ -{ \ - X0 = *RK++ ^ FT0[ ( Y0 ) & 0xFF ] ^ \ - FT1[ ( Y1 >> 8 ) & 0xFF ] ^ \ - FT2[ ( Y2 >> 16 ) & 0xFF ] ^ \ - FT3[ ( Y3 >> 24 ) & 0xFF ]; \ - \ - X1 = *RK++ ^ FT0[ ( Y1 ) & 0xFF ] ^ \ - FT1[ ( Y2 >> 8 ) & 0xFF ] ^ \ - FT2[ ( Y3 >> 16 ) & 0xFF ] ^ \ - FT3[ ( Y0 >> 24 ) & 0xFF ]; \ - \ - X2 = *RK++ ^ FT0[ ( Y2 ) & 0xFF ] ^ \ - FT1[ ( Y3 >> 8 ) & 0xFF ] ^ \ - FT2[ ( Y0 >> 16 ) & 0xFF ] ^ \ - FT3[ ( Y1 >> 24 ) & 0xFF ]; \ - \ - X3 = *RK++ ^ FT0[ ( Y3 ) & 0xFF ] ^ \ - FT1[ ( Y0 >> 8 ) & 0xFF ] ^ \ - FT2[ ( Y1 >> 16 ) & 0xFF ] ^ \ - FT3[ ( Y2 >> 24 ) & 0xFF ]; \ -} - -#define AES_RROUND(X0,X1,X2,X3,Y0,Y1,Y2,Y3) \ -{ \ - X0 = *RK++ ^ RT0[ ( Y0 ) & 0xFF ] ^ \ - RT1[ ( Y3 >> 8 ) & 0xFF ] ^ \ - RT2[ ( Y2 >> 16 ) & 0xFF ] ^ \ - RT3[ ( Y1 >> 24 ) & 0xFF ]; \ - \ - X1 = *RK++ ^ RT0[ ( Y1 ) & 0xFF ] ^ \ - RT1[ ( Y0 >> 8 ) & 0xFF ] ^ \ - RT2[ ( Y3 >> 16 ) & 0xFF ] ^ \ - RT3[ ( Y2 >> 24 ) & 0xFF ]; \ - \ - X2 = *RK++ ^ RT0[ ( Y2 ) & 0xFF ] ^ \ - RT1[ ( Y1 >> 8 ) & 0xFF ] ^ \ - RT2[ ( Y0 >> 16 ) & 0xFF ] ^ \ - RT3[ ( Y3 >> 24 ) & 0xFF ]; \ - \ - X3 = *RK++ ^ RT0[ ( Y3 ) & 0xFF ] ^ \ - RT1[ ( Y2 >> 8 ) & 0xFF ] ^ \ - RT2[ ( Y1 >> 16 ) & 0xFF ] ^ \ - RT3[ ( Y0 >> 24 ) & 0xFF ]; \ -} - -/* - * AES-ECB block encryption/decryption - */ -int aes_crypt_ecb( aes_context *ctx, - int mode, - const unsigned char input[16], - unsigned char output[16] ) -{ - int i; - uint32_t *RK, X0, X1, X2, X3, Y0, Y1, Y2, Y3; - -#if defined(POLARSSL_PADLOCK_C) && defined(POLARSSL_HAVE_X86) - if( aes_padlock_ace ) - { - if( padlock_xcryptecb( ctx, mode, input, output ) == 0 ) - return( 0 ); - - // If padlock data misaligned, we just fall back to - // unaccelerated mode - // - } -#endif - - RK = ctx->rk; - - GET_UINT32_LE( X0, input, 0 ); X0 ^= *RK++; - GET_UINT32_LE( X1, input, 4 ); X1 ^= *RK++; - GET_UINT32_LE( X2, input, 8 ); X2 ^= *RK++; - GET_UINT32_LE( X3, input, 12 ); X3 ^= *RK++; - - if( mode == AES_DECRYPT ) - { - for( i = (ctx->nr >> 1) - 1; i > 0; i-- ) - { - AES_RROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 ); - AES_RROUND( X0, X1, X2, X3, Y0, Y1, Y2, Y3 ); - } - - AES_RROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 ); - - X0 = *RK++ ^ \ - ( (uint32_t) RSb[ ( Y0 ) & 0xFF ] ) ^ - ( (uint32_t) RSb[ ( Y3 >> 8 ) & 0xFF ] << 8 ) ^ - ( (uint32_t) RSb[ ( Y2 >> 16 ) & 0xFF ] << 16 ) ^ - ( (uint32_t) RSb[ ( Y1 >> 24 ) & 0xFF ] << 24 ); - - X1 = *RK++ ^ \ - ( (uint32_t) RSb[ ( Y1 ) & 0xFF ] ) ^ - ( (uint32_t) RSb[ ( Y0 >> 8 ) & 0xFF ] << 8 ) ^ - ( (uint32_t) RSb[ ( Y3 >> 16 ) & 0xFF ] << 16 ) ^ - ( (uint32_t) RSb[ ( Y2 >> 24 ) & 0xFF ] << 24 ); - - X2 = *RK++ ^ \ - ( (uint32_t) RSb[ ( Y2 ) & 0xFF ] ) ^ - ( (uint32_t) RSb[ ( Y1 >> 8 ) & 0xFF ] << 8 ) ^ - ( (uint32_t) RSb[ ( Y0 >> 16 ) & 0xFF ] << 16 ) ^ - ( (uint32_t) RSb[ ( Y3 >> 24 ) & 0xFF ] << 24 ); - - X3 = *RK++ ^ \ - ( (uint32_t) RSb[ ( Y3 ) & 0xFF ] ) ^ - ( (uint32_t) RSb[ ( Y2 >> 8 ) & 0xFF ] << 8 ) ^ - ( (uint32_t) RSb[ ( Y1 >> 16 ) & 0xFF ] << 16 ) ^ - ( (uint32_t) RSb[ ( Y0 >> 24 ) & 0xFF ] << 24 ); - } - else /* AES_ENCRYPT */ - { - for( i = (ctx->nr >> 1) - 1; i > 0; i-- ) - { - AES_FROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 ); - AES_FROUND( X0, X1, X2, X3, Y0, Y1, Y2, Y3 ); - } - - AES_FROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 ); - - X0 = *RK++ ^ \ - ( (uint32_t) FSb[ ( Y0 ) & 0xFF ] ) ^ - ( (uint32_t) FSb[ ( Y1 >> 8 ) & 0xFF ] << 8 ) ^ - ( (uint32_t) FSb[ ( Y2 >> 16 ) & 0xFF ] << 16 ) ^ - ( (uint32_t) FSb[ ( Y3 >> 24 ) & 0xFF ] << 24 ); - - X1 = *RK++ ^ \ - ( (uint32_t) FSb[ ( Y1 ) & 0xFF ] ) ^ - ( (uint32_t) FSb[ ( Y2 >> 8 ) & 0xFF ] << 8 ) ^ - ( (uint32_t) FSb[ ( Y3 >> 16 ) & 0xFF ] << 16 ) ^ - ( (uint32_t) FSb[ ( Y0 >> 24 ) & 0xFF ] << 24 ); - - X2 = *RK++ ^ \ - ( (uint32_t) FSb[ ( Y2 ) & 0xFF ] ) ^ - ( (uint32_t) FSb[ ( Y3 >> 8 ) & 0xFF ] << 8 ) ^ - ( (uint32_t) FSb[ ( Y0 >> 16 ) & 0xFF ] << 16 ) ^ - ( (uint32_t) FSb[ ( Y1 >> 24 ) & 0xFF ] << 24 ); - - X3 = *RK++ ^ \ - ( (uint32_t) FSb[ ( Y3 ) & 0xFF ] ) ^ - ( (uint32_t) FSb[ ( Y0 >> 8 ) & 0xFF ] << 8 ) ^ - ( (uint32_t) FSb[ ( Y1 >> 16 ) & 0xFF ] << 16 ) ^ - ( (uint32_t) FSb[ ( Y2 >> 24 ) & 0xFF ] << 24 ); - } - - PUT_UINT32_LE( X0, output, 0 ); - PUT_UINT32_LE( X1, output, 4 ); - PUT_UINT32_LE( X2, output, 8 ); - PUT_UINT32_LE( X3, output, 12 ); - - return( 0 ); -} - -/* - * AES-CBC buffer encryption/decryption - */ -int aes_crypt_cbc( aes_context *ctx, - int mode, - uint64_t length, - unsigned char iv[16], - const unsigned char *input, - unsigned char *output ) -{ - int i; - unsigned char temp[16]; - - if( length % 16 ) - return( POLARSSL_ERR_AES_INVALID_INPUT_LENGTH ); - -#if defined(POLARSSL_PADLOCK_C) && defined(POLARSSL_HAVE_X86) - if( aes_padlock_ace ) - { - if( padlock_xcryptcbc( ctx, mode, length, iv, input, output ) == 0 ) - return( 0 ); - - // If padlock data misaligned, we just fall back to - // unaccelerated mode - // - } -#endif - - if( mode == AES_DECRYPT ) - { - while( length > 0 ) - { - memcpy( temp, input, 16 ); - aes_crypt_ecb( ctx, mode, input, output ); - - for( i = 0; i < 16; i++ ) - output[i] = (unsigned char)( output[i] ^ iv[i] ); - - memcpy( iv, temp, 16 ); - - input += 16; - output += 16; - length -= 16; - } - } - else - { - while( length > 0 ) - { - for( i = 0; i < 16; i++ ) - output[i] = (unsigned char)( input[i] ^ iv[i] ); - - aes_crypt_ecb( ctx, mode, output, output ); - memcpy( iv, output, 16 ); - - input += 16; - output += 16; - length -= 16; - } - } - - return( 0 ); -} - -#if defined(POLARSSL_CIPHER_MODE_CFB) -/* - * AES-CFB128 buffer encryption/decryption - */ -int aes_crypt_cfb128( aes_context *ctx, - int mode, - uint64_t length, - size_t *iv_off, - unsigned char iv[16], - const unsigned char *input, - unsigned char *output ) -{ - int c; - size_t n = *iv_off; - - if( mode == AES_DECRYPT ) - { - while( length-- ) - { - if( n == 0 ) - aes_crypt_ecb( ctx, AES_ENCRYPT, iv, iv ); - - c = *input++; - *output++ = (unsigned char)( c ^ iv[n] ); - iv[n] = (unsigned char) c; - - n = (n + 1) & 0x0F; - } - } - else - { - while( length-- ) - { - if( n == 0 ) - aes_crypt_ecb( ctx, AES_ENCRYPT, iv, iv ); - - iv[n] = *output++ = (unsigned char)( iv[n] ^ *input++ ); - - n = (n + 1) & 0x0F; - } - } - - *iv_off = n; - - return( 0 ); -} -#endif /*POLARSSL_CIPHER_MODE_CFB */ - -#if defined(POLARSSL_CIPHER_MODE_CTR) -/* - * AES-CTR buffer encryption/decryption - */ -int aes_crypt_ctr( aes_context *ctx, - uint64_t length, - size_t *nc_off, - unsigned char nonce_counter[16], - unsigned char stream_block[16], - const unsigned char *input, - unsigned char *output ) -{ - int c, i; - size_t n = *nc_off; - - while( length-- ) - { - if( n == 0 ) { - aes_crypt_ecb( ctx, AES_ENCRYPT, nonce_counter, stream_block ); - - for( i = 16; i > 0; i-- ) - if( ++nonce_counter[i - 1] != 0 ) - break; - } - c = *input++; - *output++ = (unsigned char)( c ^ stream_block[n] ); - - n = (n + 1) & 0x0F; - } - - *nc_off = n; - - return( 0 ); -} -#endif /* POLARSSL_CIPHER_MODE_CTR */ -#endif /* !POLARSSL_AES_ALT */ - -#if defined(POLARSSL_SELF_TEST) - -#include - -/* - * AES test vectors from: - * - * http://csrc.nist.gov/archive/aes/rijndael/rijndael-vals.zip - */ -static const unsigned char aes_test_ecb_dec[3][16] = -{ - { 0x44, 0x41, 0x6A, 0xC2, 0xD1, 0xF5, 0x3C, 0x58, - 0x33, 0x03, 0x91, 0x7E, 0x6B, 0xE9, 0xEB, 0xE0 }, - { 0x48, 0xE3, 0x1E, 0x9E, 0x25, 0x67, 0x18, 0xF2, - 0x92, 0x29, 0x31, 0x9C, 0x19, 0xF1, 0x5B, 0xA4 }, - { 0x05, 0x8C, 0xCF, 0xFD, 0xBB, 0xCB, 0x38, 0x2D, - 0x1F, 0x6F, 0x56, 0x58, 0x5D, 0x8A, 0x4A, 0xDE } -}; - -static const unsigned char aes_test_ecb_enc[3][16] = -{ - { 0xC3, 0x4C, 0x05, 0x2C, 0xC0, 0xDA, 0x8D, 0x73, - 0x45, 0x1A, 0xFE, 0x5F, 0x03, 0xBE, 0x29, 0x7F }, - { 0xF3, 0xF6, 0x75, 0x2A, 0xE8, 0xD7, 0x83, 0x11, - 0x38, 0xF0, 0x41, 0x56, 0x06, 0x31, 0xB1, 0x14 }, - { 0x8B, 0x79, 0xEE, 0xCC, 0x93, 0xA0, 0xEE, 0x5D, - 0xFF, 0x30, 0xB4, 0xEA, 0x21, 0x63, 0x6D, 0xA4 } -}; - -static const unsigned char aes_test_cbc_dec[3][16] = -{ - { 0xFA, 0xCA, 0x37, 0xE0, 0xB0, 0xC8, 0x53, 0x73, - 0xDF, 0x70, 0x6E, 0x73, 0xF7, 0xC9, 0xAF, 0x86 }, - { 0x5D, 0xF6, 0x78, 0xDD, 0x17, 0xBA, 0x4E, 0x75, - 0xB6, 0x17, 0x68, 0xC6, 0xAD, 0xEF, 0x7C, 0x7B }, - { 0x48, 0x04, 0xE1, 0x81, 0x8F, 0xE6, 0x29, 0x75, - 0x19, 0xA3, 0xE8, 0x8C, 0x57, 0x31, 0x04, 0x13 } -}; - -static const unsigned char aes_test_cbc_enc[3][16] = -{ - { 0x8A, 0x05, 0xFC, 0x5E, 0x09, 0x5A, 0xF4, 0x84, - 0x8A, 0x08, 0xD3, 0x28, 0xD3, 0x68, 0x8E, 0x3D }, - { 0x7B, 0xD9, 0x66, 0xD5, 0x3A, 0xD8, 0xC1, 0xBB, - 0x85, 0xD2, 0xAD, 0xFA, 0xE8, 0x7B, 0xB1, 0x04 }, - { 0xFE, 0x3C, 0x53, 0x65, 0x3E, 0x2F, 0x45, 0xB5, - 0x6F, 0xCD, 0x88, 0xB2, 0xCC, 0x89, 0x8F, 0xF0 } -}; - -#if defined(POLARSSL_CIPHER_MODE_CFB) -/* - * AES-CFB128 test vectors from: - * - * http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf - */ -static const unsigned char aes_test_cfb128_key[3][32] = -{ - { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, - 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C }, - { 0x8E, 0x73, 0xB0, 0xF7, 0xDA, 0x0E, 0x64, 0x52, - 0xC8, 0x10, 0xF3, 0x2B, 0x80, 0x90, 0x79, 0xE5, - 0x62, 0xF8, 0xEA, 0xD2, 0x52, 0x2C, 0x6B, 0x7B }, - { 0x60, 0x3D, 0xEB, 0x10, 0x15, 0xCA, 0x71, 0xBE, - 0x2B, 0x73, 0xAE, 0xF0, 0x85, 0x7D, 0x77, 0x81, - 0x1F, 0x35, 0x2C, 0x07, 0x3B, 0x61, 0x08, 0xD7, - 0x2D, 0x98, 0x10, 0xA3, 0x09, 0x14, 0xDF, 0xF4 } -}; - -static const unsigned char aes_test_cfb128_iv[16] = -{ - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F -}; - -static const unsigned char aes_test_cfb128_pt[64] = -{ - 0x6B, 0xC1, 0xBE, 0xE2, 0x2E, 0x40, 0x9F, 0x96, - 0xE9, 0x3D, 0x7E, 0x11, 0x73, 0x93, 0x17, 0x2A, - 0xAE, 0x2D, 0x8A, 0x57, 0x1E, 0x03, 0xAC, 0x9C, - 0x9E, 0xB7, 0x6F, 0xAC, 0x45, 0xAF, 0x8E, 0x51, - 0x30, 0xC8, 0x1C, 0x46, 0xA3, 0x5C, 0xE4, 0x11, - 0xE5, 0xFB, 0xC1, 0x19, 0x1A, 0x0A, 0x52, 0xEF, - 0xF6, 0x9F, 0x24, 0x45, 0xDF, 0x4F, 0x9B, 0x17, - 0xAD, 0x2B, 0x41, 0x7B, 0xE6, 0x6C, 0x37, 0x10 -}; - -static const unsigned char aes_test_cfb128_ct[3][64] = -{ - { 0x3B, 0x3F, 0xD9, 0x2E, 0xB7, 0x2D, 0xAD, 0x20, - 0x33, 0x34, 0x49, 0xF8, 0xE8, 0x3C, 0xFB, 0x4A, - 0xC8, 0xA6, 0x45, 0x37, 0xA0, 0xB3, 0xA9, 0x3F, - 0xCD, 0xE3, 0xCD, 0xAD, 0x9F, 0x1C, 0xE5, 0x8B, - 0x26, 0x75, 0x1F, 0x67, 0xA3, 0xCB, 0xB1, 0x40, - 0xB1, 0x80, 0x8C, 0xF1, 0x87, 0xA4, 0xF4, 0xDF, - 0xC0, 0x4B, 0x05, 0x35, 0x7C, 0x5D, 0x1C, 0x0E, - 0xEA, 0xC4, 0xC6, 0x6F, 0x9F, 0xF7, 0xF2, 0xE6 }, - { 0xCD, 0xC8, 0x0D, 0x6F, 0xDD, 0xF1, 0x8C, 0xAB, - 0x34, 0xC2, 0x59, 0x09, 0xC9, 0x9A, 0x41, 0x74, - 0x67, 0xCE, 0x7F, 0x7F, 0x81, 0x17, 0x36, 0x21, - 0x96, 0x1A, 0x2B, 0x70, 0x17, 0x1D, 0x3D, 0x7A, - 0x2E, 0x1E, 0x8A, 0x1D, 0xD5, 0x9B, 0x88, 0xB1, - 0xC8, 0xE6, 0x0F, 0xED, 0x1E, 0xFA, 0xC4, 0xC9, - 0xC0, 0x5F, 0x9F, 0x9C, 0xA9, 0x83, 0x4F, 0xA0, - 0x42, 0xAE, 0x8F, 0xBA, 0x58, 0x4B, 0x09, 0xFF }, - { 0xDC, 0x7E, 0x84, 0xBF, 0xDA, 0x79, 0x16, 0x4B, - 0x7E, 0xCD, 0x84, 0x86, 0x98, 0x5D, 0x38, 0x60, - 0x39, 0xFF, 0xED, 0x14, 0x3B, 0x28, 0xB1, 0xC8, - 0x32, 0x11, 0x3C, 0x63, 0x31, 0xE5, 0x40, 0x7B, - 0xDF, 0x10, 0x13, 0x24, 0x15, 0xE5, 0x4B, 0x92, - 0xA1, 0x3E, 0xD0, 0xA8, 0x26, 0x7A, 0xE2, 0xF9, - 0x75, 0xA3, 0x85, 0x74, 0x1A, 0xB9, 0xCE, 0xF8, - 0x20, 0x31, 0x62, 0x3D, 0x55, 0xB1, 0xE4, 0x71 } -}; -#endif /* POLARSSL_CIPHER_MODE_CFB */ - -#if defined(POLARSSL_CIPHER_MODE_CTR) -/* - * AES-CTR test vectors from: - * - * http://www.faqs.org/rfcs/rfc3686.html - */ - -static const unsigned char aes_test_ctr_key[3][16] = -{ - { 0xAE, 0x68, 0x52, 0xF8, 0x12, 0x10, 0x67, 0xCC, - 0x4B, 0xF7, 0xA5, 0x76, 0x55, 0x77, 0xF3, 0x9E }, - { 0x7E, 0x24, 0x06, 0x78, 0x17, 0xFA, 0xE0, 0xD7, - 0x43, 0xD6, 0xCE, 0x1F, 0x32, 0x53, 0x91, 0x63 }, - { 0x76, 0x91, 0xBE, 0x03, 0x5E, 0x50, 0x20, 0xA8, - 0xAC, 0x6E, 0x61, 0x85, 0x29, 0xF9, 0xA0, 0xDC } -}; - -static const unsigned char aes_test_ctr_nonce_counter[3][16] = -{ - { 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }, - { 0x00, 0x6C, 0xB6, 0xDB, 0xC0, 0x54, 0x3B, 0x59, - 0xDA, 0x48, 0xD9, 0x0B, 0x00, 0x00, 0x00, 0x01 }, - { 0x00, 0xE0, 0x01, 0x7B, 0x27, 0x77, 0x7F, 0x3F, - 0x4A, 0x17, 0x86, 0xF0, 0x00, 0x00, 0x00, 0x01 } -}; - -static const unsigned char aes_test_ctr_pt[3][48] = -{ - { 0x53, 0x69, 0x6E, 0x67, 0x6C, 0x65, 0x20, 0x62, - 0x6C, 0x6F, 0x63, 0x6B, 0x20, 0x6D, 0x73, 0x67 }, - - { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, - 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, - 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }, - - { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, - 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, - 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, - 0x20, 0x21, 0x22, 0x23 } -}; - -static const unsigned char aes_test_ctr_ct[3][48] = -{ - { 0xE4, 0x09, 0x5D, 0x4F, 0xB7, 0xA7, 0xB3, 0x79, - 0x2D, 0x61, 0x75, 0xA3, 0x26, 0x13, 0x11, 0xB8 }, - { 0x51, 0x04, 0xA1, 0x06, 0x16, 0x8A, 0x72, 0xD9, - 0x79, 0x0D, 0x41, 0xEE, 0x8E, 0xDA, 0xD3, 0x88, - 0xEB, 0x2E, 0x1E, 0xFC, 0x46, 0xDA, 0x57, 0xC8, - 0xFC, 0xE6, 0x30, 0xDF, 0x91, 0x41, 0xBE, 0x28 }, - { 0xC1, 0xCF, 0x48, 0xA8, 0x9F, 0x2F, 0xFD, 0xD9, - 0xCF, 0x46, 0x52, 0xE9, 0xEF, 0xDB, 0x72, 0xD7, - 0x45, 0x40, 0xA4, 0x2B, 0xDE, 0x6D, 0x78, 0x36, - 0xD5, 0x9A, 0x5C, 0xEA, 0xAE, 0xF3, 0x10, 0x53, - 0x25, 0xB2, 0x07, 0x2F } -}; - -static const int aes_test_ctr_len[3] = - { 16, 32, 36 }; -#endif /* POLARSSL_CIPHER_MODE_CTR */ - -/* - * Checkup routine - */ -int aes_self_test( int verbose ) -{ - int i, j, u, v; - unsigned char key[32]; - unsigned char buf[64]; - unsigned char prv[16]; - unsigned char iv[16]; -#if defined(POLARSSL_CIPHER_MODE_CTR) || defined(POLARSSL_CIPHER_MODE_CFB) - size_t offset; -#endif -#if defined(POLARSSL_CIPHER_MODE_CTR) - int len; - unsigned char nonce_counter[16]; - unsigned char stream_block[16]; -#endif - aes_context ctx; - - memset( key, 0, 32 ); - - /* - * ECB mode - */ - for( i = 0; i < 6; i++ ) - { - u = i >> 1; - v = i & 1; - - if( verbose != 0 ) - printf( " AES-ECB-%3d (%s): ", 128 + u * 64, - ( v == AES_DECRYPT ) ? "dec" : "enc" ); - - memset( buf, 0, 16 ); - - if( v == AES_DECRYPT ) - { - aes_setkey_dec( &ctx, key, 128 + u * 64 ); - - for( j = 0; j < 10000; j++ ) - aes_crypt_ecb( &ctx, v, buf, buf ); - - if( memcmp( buf, aes_test_ecb_dec[u], 16 ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - } - else - { - aes_setkey_enc( &ctx, key, 128 + u * 64 ); - - for( j = 0; j < 10000; j++ ) - aes_crypt_ecb( &ctx, v, buf, buf ); - - if( memcmp( buf, aes_test_ecb_enc[u], 16 ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - } - - if( verbose != 0 ) - printf( "passed\n" ); - } - - if( verbose != 0 ) - printf( "\n" ); - - /* - * CBC mode - */ - for( i = 0; i < 6; i++ ) - { - u = i >> 1; - v = i & 1; - - if( verbose != 0 ) - printf( " AES-CBC-%3d (%s): ", 128 + u * 64, - ( v == AES_DECRYPT ) ? "dec" : "enc" ); - - memset( iv , 0, 16 ); - memset( prv, 0, 16 ); - memset( buf, 0, 16 ); - - if( v == AES_DECRYPT ) - { - aes_setkey_dec( &ctx, key, 128 + u * 64 ); - - for( j = 0; j < 10000; j++ ) - aes_crypt_cbc( &ctx, v, 16, iv, buf, buf ); - - if( memcmp( buf, aes_test_cbc_dec[u], 16 ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - } - else - { - aes_setkey_enc( &ctx, key, 128 + u * 64 ); - - for( j = 0; j < 10000; j++ ) - { - unsigned char tmp[16]; - - aes_crypt_cbc( &ctx, v, 16, iv, buf, buf ); - - memcpy( tmp, prv, 16 ); - memcpy( prv, buf, 16 ); - memcpy( buf, tmp, 16 ); - } - - if( memcmp( prv, aes_test_cbc_enc[u], 16 ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - } - - if( verbose != 0 ) - printf( "passed\n" ); - } - - if( verbose != 0 ) - printf( "\n" ); - -#if defined(POLARSSL_CIPHER_MODE_CFB) - /* - * CFB128 mode - */ - for( i = 0; i < 6; i++ ) - { - u = i >> 1; - v = i & 1; - - if( verbose != 0 ) - printf( " AES-CFB128-%3d (%s): ", 128 + u * 64, - ( v == AES_DECRYPT ) ? "dec" : "enc" ); - - memcpy( iv, aes_test_cfb128_iv, 16 ); - memcpy( key, aes_test_cfb128_key[u], 16 + u * 8 ); - - offset = 0; - aes_setkey_enc( &ctx, key, 128 + u * 64 ); - - if( v == AES_DECRYPT ) - { - memcpy( buf, aes_test_cfb128_ct[u], 64 ); - aes_crypt_cfb128( &ctx, v, 64, &offset, iv, buf, buf ); - - if( memcmp( buf, aes_test_cfb128_pt, 64 ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - } - else - { - memcpy( buf, aes_test_cfb128_pt, 64 ); - aes_crypt_cfb128( &ctx, v, 64, &offset, iv, buf, buf ); - - if( memcmp( buf, aes_test_cfb128_ct[u], 64 ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - } - - if( verbose != 0 ) - printf( "passed\n" ); - } - - if( verbose != 0 ) - printf( "\n" ); -#endif /* POLARSSL_CIPHER_MODE_CFB */ - -#if defined(POLARSSL_CIPHER_MODE_CTR) - /* - * CTR mode - */ - for( i = 0; i < 6; i++ ) - { - u = i >> 1; - v = i & 1; - - if( verbose != 0 ) - printf( " AES-CTR-128 (%s): ", - ( v == AES_DECRYPT ) ? "dec" : "enc" ); - - memcpy( nonce_counter, aes_test_ctr_nonce_counter[u], 16 ); - memcpy( key, aes_test_ctr_key[u], 16 ); - - offset = 0; - aes_setkey_enc( &ctx, key, 128 ); - - if( v == AES_DECRYPT ) - { - len = aes_test_ctr_len[u]; - memcpy( buf, aes_test_ctr_ct[u], len ); - - aes_crypt_ctr( &ctx, len, &offset, nonce_counter, stream_block, buf, buf ); - - if( memcmp( buf, aes_test_ctr_pt[u], len ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - } - else - { - len = aes_test_ctr_len[u]; - memcpy( buf, aes_test_ctr_pt[u], len ); - - aes_crypt_ctr( &ctx, len, &offset, nonce_counter, stream_block, buf, buf ); - - if( memcmp( buf, aes_test_ctr_ct[u], len ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - } - - if( verbose != 0 ) - printf( "passed\n" ); - } - - if( verbose != 0 ) - printf( "\n" ); -#endif /* POLARSSL_CIPHER_MODE_CTR */ - - return( 0 ); -} - -#endif - -#endif diff --git a/lib/libpolarssl/source/base64.c b/lib/libpolarssl/source/base64.c deleted file mode 100644 index b596527..0000000 --- a/lib/libpolarssl/source/base64.c +++ /dev/null @@ -1,269 +0,0 @@ -/* - * RFC 1521 base64 encoding/decoding - * - * Copyright (C) 2006-2010, Brainspark B.V. - * - * This file is part of PolarSSL (http://www.polarssl.org) - * Lead Maintainer: Paul Bakker - * - * All rights reserved. - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ - -#include - -#if defined(POLARSSL_BASE64_C) - -#include - -#ifdef _MSC_VER -#include -typedef UINT32 uint32_t; -#else -#include -#endif - -static const unsigned char base64_enc_map[64] = -{ - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', - 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', - 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', - 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', - 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', - 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', '+', '/' -}; - -static const unsigned char base64_dec_map[128] = -{ - 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, - 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, - 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, - 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, - 127, 127, 127, 62, 127, 127, 127, 63, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, 127, 127, - 127, 64, 127, 127, 127, 0, 1, 2, 3, 4, - 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 127, 127, 127, 127, 127, 127, 26, 27, 28, - 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, - 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, - 49, 50, 51, 127, 127, 127, 127, 127 -}; - -/* - * Encode a buffer into base64 format - */ -int base64_encode( unsigned char *dst, size_t *dlen, - const unsigned char *src, size_t slen ) -{ - size_t i, n; - int C1, C2, C3; - unsigned char *p; - - if( slen == 0 ) - return( 0 ); - - n = (slen << 3) / 6; - - switch( (slen << 3) - (n * 6) ) - { - case 2: n += 3; break; - case 4: n += 2; break; - default: break; - } - - if( *dlen < n + 1 ) - { - *dlen = n + 1; - return( POLARSSL_ERR_BASE64_BUFFER_TOO_SMALL ); - } - - n = (slen / 3) * 3; - - for( i = 0, p = dst; i < n; i += 3 ) - { - C1 = *src++; - C2 = *src++; - C3 = *src++; - - *p++ = base64_enc_map[(C1 >> 2) & 0x3F]; - *p++ = base64_enc_map[(((C1 & 3) << 4) + (C2 >> 4)) & 0x3F]; - *p++ = base64_enc_map[(((C2 & 15) << 2) + (C3 >> 6)) & 0x3F]; - *p++ = base64_enc_map[C3 & 0x3F]; - } - - if( i < slen ) - { - C1 = *src++; - C2 = ((i + 1) < slen) ? *src++ : 0; - - *p++ = base64_enc_map[(C1 >> 2) & 0x3F]; - *p++ = base64_enc_map[(((C1 & 3) << 4) + (C2 >> 4)) & 0x3F]; - - if( (i + 1) < slen ) - *p++ = base64_enc_map[((C2 & 15) << 2) & 0x3F]; - else *p++ = '='; - - *p++ = '='; - } - - *dlen = p - dst; - *p = 0; - - return( 0 ); -} - -/* - * Decode a base64-formatted buffer - */ -int base64_decode( unsigned char *dst, size_t *dlen, - const unsigned char *src, size_t slen ) -{ - size_t i, n; - uint32_t j, x; - unsigned char *p; - - for( i = j = n = 0; i < slen; i++ ) - { - if( ( slen - i ) >= 2 && - src[i] == '\r' && src[i + 1] == '\n' ) - continue; - - if( src[i] == '\n' ) - continue; - - if( src[i] == '=' && ++j > 2 ){ - printf("err 0 char[%lu] = '%c' (0x%x)\n",i,src[i],src[i]); - return( POLARSSL_ERR_BASE64_INVALID_CHARACTER ); - } - - if( src[i] > 127 || base64_dec_map[src[i]] == 127 ){ - printf("err 1 char[%lu] = '%c' (0x%x)\n",i,src[i],src[i]); - return( POLARSSL_ERR_BASE64_INVALID_CHARACTER ); - } - - if( base64_dec_map[src[i]] < 64 && j != 0 ){ - printf("err 2 char[%lu] = '%c' (0x%x)\n",i,src[i],src[i]); - return( POLARSSL_ERR_BASE64_INVALID_CHARACTER ); - } - - n++; - } - - if( n == 0 ) - return( 0 ); - - - n = ((n * 6) + 7) >> 3; - - if( (*dlen+4) < n ) - { - *dlen = n; - return( POLARSSL_ERR_BASE64_BUFFER_TOO_SMALL ); - } - - for( j = 3, n = x = 0, p = dst; i > 0; i--, src++ ) - { - if( *src == '\r' || *src == '\n' ) - continue; - - j -= ( base64_dec_map[*src] == 64 ); - x = (x << 6) | ( base64_dec_map[*src] & 0x3F ); - - if( ++n == 4 ) - { - n = 0; - if( j > 0 ) *p++ = (unsigned char)( x >> 16 ); - if( j > 1 ) *p++ = (unsigned char)( x >> 8 ); - if( j > 2 ) *p++ = (unsigned char)( x ); - } - } - - *dlen = p - dst; - - return( 0 ); -} - -#if defined(POLARSSL_SELF_TEST) - -#include -#include - -static const unsigned char base64_test_dec[64] = -{ - 0x24, 0x48, 0x6E, 0x56, 0x87, 0x62, 0x5A, 0xBD, - 0xBF, 0x17, 0xD9, 0xA2, 0xC4, 0x17, 0x1A, 0x01, - 0x94, 0xED, 0x8F, 0x1E, 0x11, 0xB3, 0xD7, 0x09, - 0x0C, 0xB6, 0xE9, 0x10, 0x6F, 0x22, 0xEE, 0x13, - 0xCA, 0xB3, 0x07, 0x05, 0x76, 0xC9, 0xFA, 0x31, - 0x6C, 0x08, 0x34, 0xFF, 0x8D, 0xC2, 0x6C, 0x38, - 0x00, 0x43, 0xE9, 0x54, 0x97, 0xAF, 0x50, 0x4B, - 0xD1, 0x41, 0xBA, 0x95, 0x31, 0x5A, 0x0B, 0x97 -}; - -static const unsigned char base64_test_enc[] = - "JEhuVodiWr2/F9mixBcaAZTtjx4Rs9cJDLbpEG8i7hPK" - "swcFdsn6MWwINP+Nwmw4AEPpVJevUEvRQbqVMVoLlw=="; - -/* - * Checkup routine - */ -int base64_self_test( int verbose ) -{ - size_t len; - const unsigned char *src; - unsigned char buffer[128]; - - if( verbose != 0 ) - printf( " Base64 encoding test: " ); - - len = sizeof( buffer ); - src = base64_test_dec; - - if( base64_encode( buffer, &len, src, 64 ) != 0 || - memcmp( base64_test_enc, buffer, 88 ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( verbose != 0 ) - printf( "passed\n Base64 decoding test: " ); - - len = sizeof( buffer ); - src = base64_test_enc; - - if( base64_decode( buffer, &len, src, 88 ) != 0 || - memcmp( base64_test_dec, buffer, 64 ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( verbose != 0 ) - printf( "passed\n\n" ); - - return( 0 ); -} - -#endif - -#endif diff --git a/lib/libpolarssl/source/bignum.c b/lib/libpolarssl/source/bignum.c deleted file mode 100644 index 839ec30..0000000 --- a/lib/libpolarssl/source/bignum.c +++ /dev/null @@ -1,2135 +0,0 @@ -/* - * Multi-precision integer library - * - * Copyright (C) 2006-2010, Brainspark B.V. - * - * This file is part of PolarSSL (http://www.polarssl.org) - * Lead Maintainer: Paul Bakker - * - * All rights reserved. - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ -/* - * This MPI implementation is based on: - * - * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf - * http://www.stillhq.com/extracted/gnupg-api/mpi/ - * http://math.libtomcrypt.com/files/tommath.pdf - */ - -#include - -#if defined(POLARSSL_BIGNUM_C) - -#include -#include - -#include - -#define ciL (sizeof(t_uint)) /* chars in limb */ -#define biL (ciL << 3) /* bits in limb */ -#define biH (ciL << 2) /* half limb size */ - -/* - * Convert between bits/chars and number of limbs - */ -#define BITS_TO_LIMBS(i) (((i) + biL - 1) / biL) -#define CHARS_TO_LIMBS(i) (((i) + ciL - 1) / ciL) - -/* - * Initialize one MPI - */ -void mpi_init( mpi *X ) -{ - if( X == NULL ) - return; - - X->s = 1; - X->n = 0; - X->p = NULL; -} - -/* - * Unallocate one MPI - */ -void mpi_free( mpi *X ) -{ - if( X == NULL ) - return; - - if( X->p != NULL ) - { - memset( X->p, 0, X->n * ciL ); - free( X->p ); - } - - X->s = 1; - X->n = 0; - X->p = NULL; -} - -/* - * Enlarge to the specified number of limbs - */ -int mpi_grow( mpi *X, size_t nblimbs ) -{ - t_uint *p; - - if( nblimbs > POLARSSL_MPI_MAX_LIMBS ) - return( POLARSSL_ERR_MPI_MALLOC_FAILED ); - - if( X->n < nblimbs ) - { - if( ( p = (t_uint *) malloc( nblimbs * ciL ) ) == NULL ) - return( POLARSSL_ERR_MPI_MALLOC_FAILED ); - - memset( p, 0, nblimbs * ciL ); - - if( X->p != NULL ) - { - memcpy( p, X->p, X->n * ciL ); - memset( X->p, 0, X->n * ciL ); - free( X->p ); - } - - X->n = nblimbs; - X->p = p; - } - - return( 0 ); -} - -/* - * Copy the contents of Y into X - */ -int mpi_copy( mpi *X, const mpi *Y ) -{ - int ret; - size_t i; - - if( X == Y ) - return( 0 ); - - for( i = Y->n - 1; i > 0; i-- ) - if( Y->p[i] != 0 ) - break; - i++; - - X->s = Y->s; - - MPI_CHK( mpi_grow( X, i ) ); - - memset( X->p, 0, X->n * ciL ); - memcpy( X->p, Y->p, i * ciL ); - -cleanup: - - return( ret ); -} - -/* - * Swap the contents of X and Y - */ -void mpi_swap( mpi *X, mpi *Y ) -{ - mpi T; - - memcpy( &T, X, sizeof( mpi ) ); - memcpy( X, Y, sizeof( mpi ) ); - memcpy( Y, &T, sizeof( mpi ) ); -} - -/* - * Set value from integer - */ -int mpi_lset( mpi *X, t_sint z ) -{ - int ret; - - MPI_CHK( mpi_grow( X, 1 ) ); - memset( X->p, 0, X->n * ciL ); - - X->p[0] = ( z < 0 ) ? -z : z; - X->s = ( z < 0 ) ? -1 : 1; - -cleanup: - - return( ret ); -} - -/* - * Get a specific bit - */ -int mpi_get_bit( const mpi *X, size_t pos ) -{ - if( X->n * biL <= pos ) - return( 0 ); - - return ( X->p[pos / biL] >> ( pos % biL ) ) & 0x01; -} - -/* - * Set a bit to a specific value of 0 or 1 - */ -int mpi_set_bit( mpi *X, size_t pos, unsigned char val ) -{ - int ret = 0; - size_t off = pos / biL; - size_t idx = pos % biL; - - if( val != 0 && val != 1 ) - return POLARSSL_ERR_MPI_BAD_INPUT_DATA; - - if( X->n * biL <= pos ) - { - if( val == 0 ) - return ( 0 ); - - MPI_CHK( mpi_grow( X, off + 1 ) ); - } - - X->p[off] = ( X->p[off] & ~( 0x01 << idx ) ) | ( val << idx ); - -cleanup: - - return( ret ); -} - -/* - * Return the number of least significant bits - */ -size_t mpi_lsb( const mpi *X ) -{ - size_t i, j, count = 0; - - for( i = 0; i < X->n; i++ ) - for( j = 0; j < biL; j++, count++ ) - if( ( ( X->p[i] >> j ) & 1 ) != 0 ) - return( count ); - - return( 0 ); -} - -/* - * Return the number of most significant bits - */ -size_t mpi_msb( const mpi *X ) -{ - size_t i, j; - - for( i = X->n - 1; i > 0; i-- ) - if( X->p[i] != 0 ) - break; - - for( j = biL; j > 0; j-- ) - if( ( ( X->p[i] >> ( j - 1 ) ) & 1 ) != 0 ) - break; - - return( ( i * biL ) + j ); -} - -/* - * Return the total size in bytes - */ -size_t mpi_size( const mpi *X ) -{ - return( ( mpi_msb( X ) + 7 ) >> 3 ); -} - -/* - * Convert an ASCII character to digit value - */ -static int mpi_get_digit( t_uint *d, int radix, char c ) -{ - *d = 255; - - if( c >= 0x30 && c <= 0x39 ) *d = c - 0x30; - if( c >= 0x41 && c <= 0x46 ) *d = c - 0x37; - if( c >= 0x61 && c <= 0x66 ) *d = c - 0x57; - - if( *d >= (t_uint) radix ) - return( POLARSSL_ERR_MPI_INVALID_CHARACTER ); - - return( 0 ); -} - -/* - * Import from an ASCII string - */ -int mpi_read_string( mpi *X, int radix, const char *s ) -{ - int ret; - size_t i, j, slen, n; - t_uint d; - mpi T; - - if( radix < 2 || radix > 16 ) - return( POLARSSL_ERR_MPI_BAD_INPUT_DATA ); - - mpi_init( &T ); - - slen = strlen( s ); - - if( radix == 16 ) - { - n = BITS_TO_LIMBS( slen << 2 ); - - MPI_CHK( mpi_grow( X, n ) ); - MPI_CHK( mpi_lset( X, 0 ) ); - - for( i = slen, j = 0; i > 0; i--, j++ ) - { - if( i == 1 && s[i - 1] == '-' ) - { - X->s = -1; - break; - } - - MPI_CHK( mpi_get_digit( &d, radix, s[i - 1] ) ); - X->p[j / (2 * ciL)] |= d << ( (j % (2 * ciL)) << 2 ); - } - } - else - { - MPI_CHK( mpi_lset( X, 0 ) ); - - for( i = 0; i < slen; i++ ) - { - if( i == 0 && s[i] == '-' ) - { - X->s = -1; - continue; - } - - MPI_CHK( mpi_get_digit( &d, radix, s[i] ) ); - MPI_CHK( mpi_mul_int( &T, X, radix ) ); - - if( X->s == 1 ) - { - MPI_CHK( mpi_add_int( X, &T, d ) ); - } - else - { - MPI_CHK( mpi_sub_int( X, &T, d ) ); - } - } - } - -cleanup: - - mpi_free( &T ); - - return( ret ); -} - -/* - * Helper to write the digits high-order first - */ -static int mpi_write_hlp( mpi *X, int radix, char **p ) -{ - int ret; - t_uint r; - - if( radix < 2 || radix > 16 ) - return( POLARSSL_ERR_MPI_BAD_INPUT_DATA ); - - MPI_CHK( mpi_mod_int( &r, X, radix ) ); - MPI_CHK( mpi_div_int( X, NULL, X, radix ) ); - - if( mpi_cmp_int( X, 0 ) != 0 ) - MPI_CHK( mpi_write_hlp( X, radix, p ) ); - - if( r < 10 ) - *(*p)++ = (char)( r + 0x30 ); - else - *(*p)++ = (char)( r + 0x37 ); - -cleanup: - - return( ret ); -} - -/* - * Export into an ASCII string - */ -int mpi_write_string( const mpi *X, int radix, char *s, size_t *slen ) -{ - int ret = 0; - size_t n; - char *p; - mpi T; - - if( radix < 2 || radix > 16 ) - return( POLARSSL_ERR_MPI_BAD_INPUT_DATA ); - - n = mpi_msb( X ); - if( radix >= 4 ) n >>= 1; - if( radix >= 16 ) n >>= 1; - n += 3; - - if( *slen < n ) - { - *slen = n; - return( POLARSSL_ERR_MPI_BUFFER_TOO_SMALL ); - } - - p = s; - mpi_init( &T ); - - if( X->s == -1 ) - *p++ = '-'; - - if( radix == 16 ) - { - int c; - size_t i, j, k; - - for( i = X->n, k = 0; i > 0; i-- ) - { - for( j = ciL; j > 0; j-- ) - { - c = ( X->p[i - 1] >> ( ( j - 1 ) << 3) ) & 0xFF; - - if( c == 0 && k == 0 && ( i + j + 3 ) != 0 ) - continue; - - *(p++) = "0123456789ABCDEF" [c / 16]; - *(p++) = "0123456789ABCDEF" [c % 16]; - k = 1; - } - } - } - else - { - MPI_CHK( mpi_copy( &T, X ) ); - - if( T.s == -1 ) - T.s = 1; - - MPI_CHK( mpi_write_hlp( &T, radix, &p ) ); - } - - *p++ = '\0'; - *slen = p - s; - -cleanup: - - mpi_free( &T ); - - return( ret ); -} - -#if defined(POLARSSL_FS_IO) -/* - * Read X from an opened file - */ -int mpi_read_file( mpi *X, int radix, FILE *fin ) -{ - t_uint d; - size_t slen; - char *p; - /* - * Buffer should have space for (short) label and decimal formatted MPI, - * newline characters and '\0' - */ - char s[ POLARSSL_MPI_RW_BUFFER_SIZE ]; - - memset( s, 0, sizeof( s ) ); - if( fgets( s, sizeof( s ) - 1, fin ) == NULL ) - return( POLARSSL_ERR_MPI_FILE_IO_ERROR ); - - slen = strlen( s ); - if( slen == sizeof( s ) - 2 ) - return( POLARSSL_ERR_MPI_BUFFER_TOO_SMALL ); - - if( s[slen - 1] == '\n' ) { slen--; s[slen] = '\0'; } - if( s[slen - 1] == '\r' ) { slen--; s[slen] = '\0'; } - - p = s + slen; - while( --p >= s ) - if( mpi_get_digit( &d, radix, *p ) != 0 ) - break; - - return( mpi_read_string( X, radix, p + 1 ) ); -} - -/* - * Write X into an opened file (or stdout if fout == NULL) - */ -int mpi_write_file( const char *p, const mpi *X, int radix, FILE *fout ) -{ - int ret; - size_t n, slen, plen; - /* - * Buffer should have space for (short) label and decimal formatted MPI, - * newline characters and '\0' - */ - char s[ POLARSSL_MPI_RW_BUFFER_SIZE ]; - - n = sizeof( s ); - memset( s, 0, n ); - n -= 2; - - MPI_CHK( mpi_write_string( X, radix, s, (size_t *) &n ) ); - - if( p == NULL ) p = ""; - - plen = strlen( p ); - slen = strlen( s ); - s[slen++] = '\r'; - s[slen++] = '\n'; - - if( fout != NULL ) - { - if( fwrite( p, 1, plen, fout ) != plen || - fwrite( s, 1, slen, fout ) != slen ) - return( POLARSSL_ERR_MPI_FILE_IO_ERROR ); - } - else - printf( "%s%s", p, s ); - -cleanup: - - return( ret ); -} -#endif /* POLARSSL_FS_IO */ - -/* - * Import X from unsigned binary data, big endian - */ -int mpi_read_binary( mpi *X, const unsigned char *buf, size_t buflen ) -{ - int ret; - size_t i, j, n; - - for( n = 0; n < buflen; n++ ) - if( buf[n] != 0 ) - break; - - MPI_CHK( mpi_grow( X, CHARS_TO_LIMBS( buflen - n ) ) ); - MPI_CHK( mpi_lset( X, 0 ) ); - - for( i = buflen, j = 0; i > n; i--, j++ ) - X->p[j / ciL] |= ((t_uint) buf[i - 1]) << ((j % ciL) << 3); - -cleanup: - - return( ret ); -} - -/* - * Export X into unsigned binary data, big endian - */ -int mpi_write_binary( const mpi *X, unsigned char *buf, size_t buflen ) -{ - size_t i, j, n; - - n = mpi_size( X ); - - if( buflen < n ) - return( POLARSSL_ERR_MPI_BUFFER_TOO_SMALL ); - - memset( buf, 0, buflen ); - - for( i = buflen - 1, j = 0; n > 0; i--, j++, n-- ) - buf[i] = (unsigned char)( X->p[j / ciL] >> ((j % ciL) << 3) ); - - return( 0 ); -} - -/* - * Left-shift: X <<= count - */ -int mpi_shift_l( mpi *X, size_t count ) -{ - int ret; - size_t i, v0, t1; - t_uint r0 = 0, r1; - - v0 = count / (biL ); - t1 = count & (biL - 1); - - i = mpi_msb( X ) + count; - - if( X->n * biL < i ) - MPI_CHK( mpi_grow( X, BITS_TO_LIMBS( i ) ) ); - - ret = 0; - - /* - * shift by count / limb_size - */ - if( v0 > 0 ) - { - for( i = X->n; i > v0; i-- ) - X->p[i - 1] = X->p[i - v0 - 1]; - - for( ; i > 0; i-- ) - X->p[i - 1] = 0; - } - - /* - * shift by count % limb_size - */ - if( t1 > 0 ) - { - for( i = v0; i < X->n; i++ ) - { - r1 = X->p[i] >> (biL - t1); - X->p[i] <<= t1; - X->p[i] |= r0; - r0 = r1; - } - } - -cleanup: - - return( ret ); -} - -/* - * Right-shift: X >>= count - */ -int mpi_shift_r( mpi *X, size_t count ) -{ - size_t i, v0, v1; - t_uint r0 = 0, r1; - - v0 = count / biL; - v1 = count & (biL - 1); - - if( v0 > X->n || ( v0 == X->n && v1 > 0 ) ) - return mpi_lset( X, 0 ); - - /* - * shift by count / limb_size - */ - if( v0 > 0 ) - { - for( i = 0; i < X->n - v0; i++ ) - X->p[i] = X->p[i + v0]; - - for( ; i < X->n; i++ ) - X->p[i] = 0; - } - - /* - * shift by count % limb_size - */ - if( v1 > 0 ) - { - for( i = X->n; i > 0; i-- ) - { - r1 = X->p[i - 1] << (biL - v1); - X->p[i - 1] >>= v1; - X->p[i - 1] |= r0; - r0 = r1; - } - } - - return( 0 ); -} - -/* - * Compare unsigned values - */ -int mpi_cmp_abs( const mpi *X, const mpi *Y ) -{ - size_t i, j; - - for( i = X->n; i > 0; i-- ) - if( X->p[i - 1] != 0 ) - break; - - for( j = Y->n; j > 0; j-- ) - if( Y->p[j - 1] != 0 ) - break; - - if( i == 0 && j == 0 ) - return( 0 ); - - if( i > j ) return( 1 ); - if( j > i ) return( -1 ); - - for( ; i > 0; i-- ) - { - if( X->p[i - 1] > Y->p[i - 1] ) return( 1 ); - if( X->p[i - 1] < Y->p[i - 1] ) return( -1 ); - } - - return( 0 ); -} - -/* - * Compare signed values - */ -int mpi_cmp_mpi( const mpi *X, const mpi *Y ) -{ - size_t i, j; - - for( i = X->n; i > 0; i-- ) - if( X->p[i - 1] != 0 ) - break; - - for( j = Y->n; j > 0; j-- ) - if( Y->p[j - 1] != 0 ) - break; - - if( i == 0 && j == 0 ) - return( 0 ); - - if( i > j ) return( X->s ); - if( j > i ) return( -Y->s ); - - if( X->s > 0 && Y->s < 0 ) return( 1 ); - if( Y->s > 0 && X->s < 0 ) return( -1 ); - - for( ; i > 0; i-- ) - { - if( X->p[i - 1] > Y->p[i - 1] ) return( X->s ); - if( X->p[i - 1] < Y->p[i - 1] ) return( -X->s ); - } - - return( 0 ); -} - -/* - * Compare signed values - */ -int mpi_cmp_int( const mpi *X, t_sint z ) -{ - mpi Y; - t_uint p[1]; - - *p = ( z < 0 ) ? -z : z; - Y.s = ( z < 0 ) ? -1 : 1; - Y.n = 1; - Y.p = p; - - return( mpi_cmp_mpi( X, &Y ) ); -} - -/* - * Unsigned addition: X = |A| + |B| (HAC 14.7) - */ -int mpi_add_abs( mpi *X, const mpi *A, const mpi *B ) -{ - int ret; - size_t i, j; - t_uint *o, *p, c; - - if( X == B ) - { - const mpi *T = A; A = X; B = T; - } - - if( X != A ) - MPI_CHK( mpi_copy( X, A ) ); - - /* - * X should always be positive as a result of unsigned additions. - */ - X->s = 1; - - for( j = B->n; j > 0; j-- ) - if( B->p[j - 1] != 0 ) - break; - - MPI_CHK( mpi_grow( X, j ) ); - - o = B->p; p = X->p; c = 0; - - for( i = 0; i < j; i++, o++, p++ ) - { - *p += c; c = ( *p < c ); - *p += *o; c += ( *p < *o ); - } - - while( c != 0 ) - { - if( i >= X->n ) - { - MPI_CHK( mpi_grow( X, i + 1 ) ); - p = X->p + i; - } - - *p += c; c = ( *p < c ); i++; p++; - } - -cleanup: - - return( ret ); -} - -/* - * Helper for mpi substraction - */ -static void mpi_sub_hlp( size_t n, t_uint *s, t_uint *d ) -{ - size_t i; - t_uint c, z; - - for( i = c = 0; i < n; i++, s++, d++ ) - { - z = ( *d < c ); *d -= c; - c = ( *d < *s ) + z; *d -= *s; - } - - while( c != 0 ) - { - z = ( *d < c ); *d -= c; - c = z; i++; d++; - } -} - -/* - * Unsigned substraction: X = |A| - |B| (HAC 14.9) - */ -int mpi_sub_abs( mpi *X, const mpi *A, const mpi *B ) -{ - mpi TB; - int ret; - size_t n; - - if( mpi_cmp_abs( A, B ) < 0 ) - return( POLARSSL_ERR_MPI_NEGATIVE_VALUE ); - - mpi_init( &TB ); - - if( X == B ) - { - MPI_CHK( mpi_copy( &TB, B ) ); - B = &TB; - } - - if( X != A ) - MPI_CHK( mpi_copy( X, A ) ); - - /* - * X should always be positive as a result of unsigned substractions. - */ - X->s = 1; - - ret = 0; - - for( n = B->n; n > 0; n-- ) - if( B->p[n - 1] != 0 ) - break; - - mpi_sub_hlp( n, B->p, X->p ); - -cleanup: - - mpi_free( &TB ); - - return( ret ); -} - -/* - * Signed addition: X = A + B - */ -int mpi_add_mpi( mpi *X, const mpi *A, const mpi *B ) -{ - int ret, s = A->s; - - if( A->s * B->s < 0 ) - { - if( mpi_cmp_abs( A, B ) >= 0 ) - { - MPI_CHK( mpi_sub_abs( X, A, B ) ); - X->s = s; - } - else - { - MPI_CHK( mpi_sub_abs( X, B, A ) ); - X->s = -s; - } - } - else - { - MPI_CHK( mpi_add_abs( X, A, B ) ); - X->s = s; - } - -cleanup: - - return( ret ); -} - -/* - * Signed substraction: X = A - B - */ -int mpi_sub_mpi( mpi *X, const mpi *A, const mpi *B ) -{ - int ret, s = A->s; - - if( A->s * B->s > 0 ) - { - if( mpi_cmp_abs( A, B ) >= 0 ) - { - MPI_CHK( mpi_sub_abs( X, A, B ) ); - X->s = s; - } - else - { - MPI_CHK( mpi_sub_abs( X, B, A ) ); - X->s = -s; - } - } - else - { - MPI_CHK( mpi_add_abs( X, A, B ) ); - X->s = s; - } - -cleanup: - - return( ret ); -} - -/* - * Signed addition: X = A + b - */ -int mpi_add_int( mpi *X, const mpi *A, t_sint b ) -{ - mpi _B; - t_uint p[1]; - - p[0] = ( b < 0 ) ? -b : b; - _B.s = ( b < 0 ) ? -1 : 1; - _B.n = 1; - _B.p = p; - - return( mpi_add_mpi( X, A, &_B ) ); -} - -/* - * Signed substraction: X = A - b - */ -int mpi_sub_int( mpi *X, const mpi *A, t_sint b ) -{ - mpi _B; - t_uint p[1]; - - p[0] = ( b < 0 ) ? -b : b; - _B.s = ( b < 0 ) ? -1 : 1; - _B.n = 1; - _B.p = p; - - return( mpi_sub_mpi( X, A, &_B ) ); -} - -/* - * Helper for mpi multiplication - */ -static void mpi_mul_hlp( size_t i, t_uint *s, t_uint *d, t_uint b ) -{ - t_uint c = 0, t = 0; - -#if defined(MULADDC_HUIT) - for( ; i >= 8; i -= 8 ) - { - MULADDC_INIT - MULADDC_HUIT - MULADDC_STOP - } - - for( ; i > 0; i-- ) - { - MULADDC_INIT - MULADDC_CORE - MULADDC_STOP - } -#else - for( ; i >= 16; i -= 16 ) - { - MULADDC_INIT - MULADDC_CORE MULADDC_CORE - MULADDC_CORE MULADDC_CORE - MULADDC_CORE MULADDC_CORE - MULADDC_CORE MULADDC_CORE - - MULADDC_CORE MULADDC_CORE - MULADDC_CORE MULADDC_CORE - MULADDC_CORE MULADDC_CORE - MULADDC_CORE MULADDC_CORE - MULADDC_STOP - } - - for( ; i >= 8; i -= 8 ) - { - MULADDC_INIT - MULADDC_CORE MULADDC_CORE - MULADDC_CORE MULADDC_CORE - - MULADDC_CORE MULADDC_CORE - MULADDC_CORE MULADDC_CORE - MULADDC_STOP - } - - for( ; i > 0; i-- ) - { - MULADDC_INIT - MULADDC_CORE - MULADDC_STOP - } -#endif - - t++; - - do { - *d += c; c = ( *d < c ); d++; - } - while( c != 0 ); -} - -/* - * Baseline multiplication: X = A * B (HAC 14.12) - */ -int mpi_mul_mpi( mpi *X, const mpi *A, const mpi *B ) -{ - int ret; - size_t i, j; - mpi TA, TB; - - mpi_init( &TA ); mpi_init( &TB ); - - if( X == A ) { MPI_CHK( mpi_copy( &TA, A ) ); A = &TA; } - if( X == B ) { MPI_CHK( mpi_copy( &TB, B ) ); B = &TB; } - - for( i = A->n; i > 0; i-- ) - if( A->p[i - 1] != 0 ) - break; - - for( j = B->n; j > 0; j-- ) - if( B->p[j - 1] != 0 ) - break; - - MPI_CHK( mpi_grow( X, i + j ) ); - MPI_CHK( mpi_lset( X, 0 ) ); - - for( i++; j > 0; j-- ) - mpi_mul_hlp( i - 1, A->p, X->p + j - 1, B->p[j - 1] ); - - X->s = A->s * B->s; - -cleanup: - - mpi_free( &TB ); mpi_free( &TA ); - - return( ret ); -} - -/* - * Baseline multiplication: X = A * b - */ -int mpi_mul_int( mpi *X, const mpi *A, t_sint b ) -{ - mpi _B; - t_uint p[1]; - - _B.s = 1; - _B.n = 1; - _B.p = p; - p[0] = b; - - return( mpi_mul_mpi( X, A, &_B ) ); -} - -/* - * Division by mpi: A = Q * B + R (HAC 14.20) - */ -int mpi_div_mpi( mpi *Q, mpi *R, const mpi *A, const mpi *B ) -{ - int ret; - size_t i, n, t, k; - mpi X, Y, Z, T1, T2; - - if( mpi_cmp_int( B, 0 ) == 0 ) - return( POLARSSL_ERR_MPI_DIVISION_BY_ZERO ); - - mpi_init( &X ); mpi_init( &Y ); mpi_init( &Z ); - mpi_init( &T1 ); mpi_init( &T2 ); - - if( mpi_cmp_abs( A, B ) < 0 ) - { - if( Q != NULL ) MPI_CHK( mpi_lset( Q, 0 ) ); - if( R != NULL ) MPI_CHK( mpi_copy( R, A ) ); - return( 0 ); - } - - MPI_CHK( mpi_copy( &X, A ) ); - MPI_CHK( mpi_copy( &Y, B ) ); - X.s = Y.s = 1; - - MPI_CHK( mpi_grow( &Z, A->n + 2 ) ); - MPI_CHK( mpi_lset( &Z, 0 ) ); - MPI_CHK( mpi_grow( &T1, 2 ) ); - MPI_CHK( mpi_grow( &T2, 3 ) ); - - k = mpi_msb( &Y ) % biL; - if( k < biL - 1 ) - { - k = biL - 1 - k; - MPI_CHK( mpi_shift_l( &X, k ) ); - MPI_CHK( mpi_shift_l( &Y, k ) ); - } - else k = 0; - - n = X.n - 1; - t = Y.n - 1; - MPI_CHK( mpi_shift_l( &Y, biL * (n - t) ) ); - - while( mpi_cmp_mpi( &X, &Y ) >= 0 ) - { - Z.p[n - t]++; - mpi_sub_mpi( &X, &X, &Y ); - } - mpi_shift_r( &Y, biL * (n - t) ); - - for( i = n; i > t ; i-- ) - { - if( X.p[i] >= Y.p[t] ) - Z.p[i - t - 1] = ~0; - else - { -#if defined(POLARSSL_HAVE_UDBL) - t_udbl r; - - r = (t_udbl) X.p[i] << biL; - r |= (t_udbl) X.p[i - 1]; - r /= Y.p[t]; - if( r > ((t_udbl) 1 << biL) - 1) - r = ((t_udbl) 1 << biL) - 1; - - Z.p[i - t - 1] = (t_uint) r; -#else - /* - * __udiv_qrnnd_c, from gmp/longlong.h - */ - t_uint q0, q1, r0, r1; - t_uint d0, d1, d, m; - - d = Y.p[t]; - d0 = ( d << biH ) >> biH; - d1 = ( d >> biH ); - - q1 = X.p[i] / d1; - r1 = X.p[i] - d1 * q1; - r1 <<= biH; - r1 |= ( X.p[i - 1] >> biH ); - - m = q1 * d0; - if( r1 < m ) - { - q1--, r1 += d; - while( r1 >= d && r1 < m ) - q1--, r1 += d; - } - r1 -= m; - - q0 = r1 / d1; - r0 = r1 - d1 * q0; - r0 <<= biH; - r0 |= ( X.p[i - 1] << biH ) >> biH; - - m = q0 * d0; - if( r0 < m ) - { - q0--, r0 += d; - while( r0 >= d && r0 < m ) - q0--, r0 += d; - } - r0 -= m; - - Z.p[i - t - 1] = ( q1 << biH ) | q0; -#endif - } - - Z.p[i - t - 1]++; - do - { - Z.p[i - t - 1]--; - - MPI_CHK( mpi_lset( &T1, 0 ) ); - T1.p[0] = (t < 1) ? 0 : Y.p[t - 1]; - T1.p[1] = Y.p[t]; - MPI_CHK( mpi_mul_int( &T1, &T1, Z.p[i - t - 1] ) ); - - MPI_CHK( mpi_lset( &T2, 0 ) ); - T2.p[0] = (i < 2) ? 0 : X.p[i - 2]; - T2.p[1] = (i < 1) ? 0 : X.p[i - 1]; - T2.p[2] = X.p[i]; - } - while( mpi_cmp_mpi( &T1, &T2 ) > 0 ); - - MPI_CHK( mpi_mul_int( &T1, &Y, Z.p[i - t - 1] ) ); - MPI_CHK( mpi_shift_l( &T1, biL * (i - t - 1) ) ); - MPI_CHK( mpi_sub_mpi( &X, &X, &T1 ) ); - - if( mpi_cmp_int( &X, 0 ) < 0 ) - { - MPI_CHK( mpi_copy( &T1, &Y ) ); - MPI_CHK( mpi_shift_l( &T1, biL * (i - t - 1) ) ); - MPI_CHK( mpi_add_mpi( &X, &X, &T1 ) ); - Z.p[i - t - 1]--; - } - } - - if( Q != NULL ) - { - mpi_copy( Q, &Z ); - Q->s = A->s * B->s; - } - - if( R != NULL ) - { - mpi_shift_r( &X, k ); - X.s = A->s; - mpi_copy( R, &X ); - - if( mpi_cmp_int( R, 0 ) == 0 ) - R->s = 1; - } - -cleanup: - - mpi_free( &X ); mpi_free( &Y ); mpi_free( &Z ); - mpi_free( &T1 ); mpi_free( &T2 ); - - return( ret ); -} - -/* - * Division by int: A = Q * b + R - */ -int mpi_div_int( mpi *Q, mpi *R, const mpi *A, t_sint b ) -{ - mpi _B; - t_uint p[1]; - - p[0] = ( b < 0 ) ? -b : b; - _B.s = ( b < 0 ) ? -1 : 1; - _B.n = 1; - _B.p = p; - - return( mpi_div_mpi( Q, R, A, &_B ) ); -} - -/* - * Modulo: R = A mod B - */ -int mpi_mod_mpi( mpi *R, const mpi *A, const mpi *B ) -{ - int ret; - - if( mpi_cmp_int( B, 0 ) < 0 ) - return POLARSSL_ERR_MPI_NEGATIVE_VALUE; - - MPI_CHK( mpi_div_mpi( NULL, R, A, B ) ); - - while( mpi_cmp_int( R, 0 ) < 0 ) - MPI_CHK( mpi_add_mpi( R, R, B ) ); - - while( mpi_cmp_mpi( R, B ) >= 0 ) - MPI_CHK( mpi_sub_mpi( R, R, B ) ); - -cleanup: - - return( ret ); -} - -/* - * Modulo: r = A mod b - */ -int mpi_mod_int( t_uint *r, const mpi *A, t_sint b ) -{ - size_t i; - t_uint x, y, z; - - if( b == 0 ) - return( POLARSSL_ERR_MPI_DIVISION_BY_ZERO ); - - if( b < 0 ) - return POLARSSL_ERR_MPI_NEGATIVE_VALUE; - - /* - * handle trivial cases - */ - if( b == 1 ) - { - *r = 0; - return( 0 ); - } - - if( b == 2 ) - { - *r = A->p[0] & 1; - return( 0 ); - } - - /* - * general case - */ - for( i = A->n, y = 0; i > 0; i-- ) - { - x = A->p[i - 1]; - y = ( y << biH ) | ( x >> biH ); - z = y / b; - y -= z * b; - - x <<= biH; - y = ( y << biH ) | ( x >> biH ); - z = y / b; - y -= z * b; - } - - /* - * If A is negative, then the current y represents a negative value. - * Flipping it to the positive side. - */ - if( A->s < 0 && y != 0 ) - y = b - y; - - *r = y; - - return( 0 ); -} - -/* - * Fast Montgomery initialization (thanks to Tom St Denis) - */ -static void mpi_montg_init( t_uint *mm, const mpi *N ) -{ - t_uint x, m0 = N->p[0]; - - x = m0; - x += ( ( m0 + 2 ) & 4 ) << 1; - x *= ( 2 - ( m0 * x ) ); - - if( biL >= 16 ) x *= ( 2 - ( m0 * x ) ); - if( biL >= 32 ) x *= ( 2 - ( m0 * x ) ); - if( biL >= 64 ) x *= ( 2 - ( m0 * x ) ); - - *mm = ~x + 1; -} - -/* - * Montgomery multiplication: A = A * B * R^-1 mod N (HAC 14.36) - */ -static void mpi_montmul( mpi *A, const mpi *B, const mpi *N, t_uint mm, const mpi *T ) -{ - size_t i, n, m; - t_uint u0, u1, *d; - - memset( T->p, 0, T->n * ciL ); - - d = T->p; - n = N->n; - m = ( B->n < n ) ? B->n : n; - - for( i = 0; i < n; i++ ) - { - /* - * T = (T + u0*B + u1*N) / 2^biL - */ - u0 = A->p[i]; - u1 = ( d[0] + u0 * B->p[0] ) * mm; - - mpi_mul_hlp( m, B->p, d, u0 ); - mpi_mul_hlp( n, N->p, d, u1 ); - - *d++ = u0; d[n + 1] = 0; - } - - memcpy( A->p, d, (n + 1) * ciL ); - - if( mpi_cmp_abs( A, N ) >= 0 ) - mpi_sub_hlp( n, N->p, A->p ); - else - /* prevent timing attacks */ - mpi_sub_hlp( n, A->p, T->p ); -} - -/* - * Montgomery reduction: A = A * R^-1 mod N - */ -static void mpi_montred( mpi *A, const mpi *N, t_uint mm, const mpi *T ) -{ - t_uint z = 1; - mpi U; - - U.n = U.s = (int) z; - U.p = &z; - - mpi_montmul( A, &U, N, mm, T ); -} - -/* - * Sliding-window exponentiation: X = A^E mod N (HAC 14.85) - */ -int mpi_exp_mod( mpi *X, const mpi *A, const mpi *E, const mpi *N, mpi *_RR ) -{ - int ret; - size_t wbits, wsize, one = 1; - size_t i, j, nblimbs; - size_t bufsize, nbits; - t_uint ei, mm, state; - mpi RR, T, W[ 2 << POLARSSL_MPI_WINDOW_SIZE ], Apos; - int neg; - - if( mpi_cmp_int( N, 0 ) < 0 || ( N->p[0] & 1 ) == 0 ) - return( POLARSSL_ERR_MPI_BAD_INPUT_DATA ); - - if( mpi_cmp_int( E, 0 ) < 0 ) - return( POLARSSL_ERR_MPI_BAD_INPUT_DATA ); - - /* - * Init temps and window size - */ - mpi_montg_init( &mm, N ); - mpi_init( &RR ); mpi_init( &T ); - memset( W, 0, sizeof( W ) ); - - i = mpi_msb( E ); - - wsize = ( i > 671 ) ? 6 : ( i > 239 ) ? 5 : - ( i > 79 ) ? 4 : ( i > 23 ) ? 3 : 1; - - if( wsize > POLARSSL_MPI_WINDOW_SIZE ) - wsize = POLARSSL_MPI_WINDOW_SIZE; - - j = N->n + 1; - MPI_CHK( mpi_grow( X, j ) ); - MPI_CHK( mpi_grow( &W[1], j ) ); - MPI_CHK( mpi_grow( &T, j * 2 ) ); - - /* - * Compensate for negative A (and correct at the end) - */ - neg = ( A->s == -1 ); - - mpi_init( &Apos ); - if( neg ) - { - MPI_CHK( mpi_copy( &Apos, A ) ); - Apos.s = 1; - A = &Apos; - } - - /* - * If 1st call, pre-compute R^2 mod N - */ - if( _RR == NULL || _RR->p == NULL ) - { - MPI_CHK( mpi_lset( &RR, 1 ) ); - MPI_CHK( mpi_shift_l( &RR, N->n * 2 * biL ) ); - MPI_CHK( mpi_mod_mpi( &RR, &RR, N ) ); - - if( _RR != NULL ) - memcpy( _RR, &RR, sizeof( mpi ) ); - } - else - memcpy( &RR, _RR, sizeof( mpi ) ); - - /* - * W[1] = A * R^2 * R^-1 mod N = A * R mod N - */ - if( mpi_cmp_mpi( A, N ) >= 0 ) - mpi_mod_mpi( &W[1], A, N ); - else mpi_copy( &W[1], A ); - - mpi_montmul( &W[1], &RR, N, mm, &T ); - - /* - * X = R^2 * R^-1 mod N = R mod N - */ - MPI_CHK( mpi_copy( X, &RR ) ); - mpi_montred( X, N, mm, &T ); - - if( wsize > 1 ) - { - /* - * W[1 << (wsize - 1)] = W[1] ^ (wsize - 1) - */ - j = one << (wsize - 1); - - MPI_CHK( mpi_grow( &W[j], N->n + 1 ) ); - MPI_CHK( mpi_copy( &W[j], &W[1] ) ); - - for( i = 0; i < wsize - 1; i++ ) - mpi_montmul( &W[j], &W[j], N, mm, &T ); - - /* - * W[i] = W[i - 1] * W[1] - */ - for( i = j + 1; i < (one << wsize); i++ ) - { - MPI_CHK( mpi_grow( &W[i], N->n + 1 ) ); - MPI_CHK( mpi_copy( &W[i], &W[i - 1] ) ); - - mpi_montmul( &W[i], &W[1], N, mm, &T ); - } - } - - nblimbs = E->n; - bufsize = 0; - nbits = 0; - wbits = 0; - state = 0; - - while( 1 ) - { - if( bufsize == 0 ) - { - if( nblimbs-- == 0 ) - break; - - bufsize = sizeof( t_uint ) << 3; - } - - bufsize--; - - ei = (E->p[nblimbs] >> bufsize) & 1; - - /* - * skip leading 0s - */ - if( ei == 0 && state == 0 ) - continue; - - if( ei == 0 && state == 1 ) - { - /* - * out of window, square X - */ - mpi_montmul( X, X, N, mm, &T ); - continue; - } - - /* - * add ei to current window - */ - state = 2; - - nbits++; - wbits |= (ei << (wsize - nbits)); - - if( nbits == wsize ) - { - /* - * X = X^wsize R^-1 mod N - */ - for( i = 0; i < wsize; i++ ) - mpi_montmul( X, X, N, mm, &T ); - - /* - * X = X * W[wbits] R^-1 mod N - */ - mpi_montmul( X, &W[wbits], N, mm, &T ); - - state--; - nbits = 0; - wbits = 0; - } - } - - /* - * process the remaining bits - */ - for( i = 0; i < nbits; i++ ) - { - mpi_montmul( X, X, N, mm, &T ); - - wbits <<= 1; - - if( (wbits & (one << wsize)) != 0 ) - mpi_montmul( X, &W[1], N, mm, &T ); - } - - /* - * X = A^E * R * R^-1 mod N = A^E mod N - */ - mpi_montred( X, N, mm, &T ); - - if( neg ) - { - X->s = -1; - mpi_add_mpi( X, N, X ); - } - -cleanup: - - for( i = (one << (wsize - 1)); i < (one << wsize); i++ ) - mpi_free( &W[i] ); - - mpi_free( &W[1] ); mpi_free( &T ); mpi_free( &Apos ); - - if( _RR == NULL ) - mpi_free( &RR ); - - return( ret ); -} - -/* - * Greatest common divisor: G = gcd(A, B) (HAC 14.54) - */ -int mpi_gcd( mpi *G, const mpi *A, const mpi *B ) -{ - int ret; - size_t lz, lzt; - mpi TG, TA, TB; - - mpi_init( &TG ); mpi_init( &TA ); mpi_init( &TB ); - - MPI_CHK( mpi_copy( &TA, A ) ); - MPI_CHK( mpi_copy( &TB, B ) ); - - lz = mpi_lsb( &TA ); - lzt = mpi_lsb( &TB ); - - if ( lzt < lz ) - lz = lzt; - - MPI_CHK( mpi_shift_r( &TA, lz ) ); - MPI_CHK( mpi_shift_r( &TB, lz ) ); - - TA.s = TB.s = 1; - - while( mpi_cmp_int( &TA, 0 ) != 0 ) - { - MPI_CHK( mpi_shift_r( &TA, mpi_lsb( &TA ) ) ); - MPI_CHK( mpi_shift_r( &TB, mpi_lsb( &TB ) ) ); - - if( mpi_cmp_mpi( &TA, &TB ) >= 0 ) - { - MPI_CHK( mpi_sub_abs( &TA, &TA, &TB ) ); - MPI_CHK( mpi_shift_r( &TA, 1 ) ); - } - else - { - MPI_CHK( mpi_sub_abs( &TB, &TB, &TA ) ); - MPI_CHK( mpi_shift_r( &TB, 1 ) ); - } - } - - MPI_CHK( mpi_shift_l( &TB, lz ) ); - MPI_CHK( mpi_copy( G, &TB ) ); - -cleanup: - - mpi_free( &TG ); mpi_free( &TA ); mpi_free( &TB ); - - return( ret ); -} - -int mpi_fill_random( mpi *X, size_t size, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng ) -{ - int ret; - - MPI_CHK( mpi_grow( X, CHARS_TO_LIMBS( size ) ) ); - MPI_CHK( mpi_lset( X, 0 ) ); - - MPI_CHK( f_rng( p_rng, (unsigned char *) X->p, size ) ); - -cleanup: - return( ret ); -} - -/* - * Modular inverse: X = A^-1 mod N (HAC 14.61 / 14.64) - */ -int mpi_inv_mod( mpi *X, const mpi *A, const mpi *N ) -{ - int ret; - mpi G, TA, TU, U1, U2, TB, TV, V1, V2; - - if( mpi_cmp_int( N, 0 ) <= 0 ) - return( POLARSSL_ERR_MPI_BAD_INPUT_DATA ); - - mpi_init( &TA ); mpi_init( &TU ); mpi_init( &U1 ); mpi_init( &U2 ); - mpi_init( &G ); mpi_init( &TB ); mpi_init( &TV ); - mpi_init( &V1 ); mpi_init( &V2 ); - - MPI_CHK( mpi_gcd( &G, A, N ) ); - - if( mpi_cmp_int( &G, 1 ) != 0 ) - { - ret = POLARSSL_ERR_MPI_NOT_ACCEPTABLE; - goto cleanup; - } - - MPI_CHK( mpi_mod_mpi( &TA, A, N ) ); - MPI_CHK( mpi_copy( &TU, &TA ) ); - MPI_CHK( mpi_copy( &TB, N ) ); - MPI_CHK( mpi_copy( &TV, N ) ); - - MPI_CHK( mpi_lset( &U1, 1 ) ); - MPI_CHK( mpi_lset( &U2, 0 ) ); - MPI_CHK( mpi_lset( &V1, 0 ) ); - MPI_CHK( mpi_lset( &V2, 1 ) ); - - do - { - while( ( TU.p[0] & 1 ) == 0 ) - { - MPI_CHK( mpi_shift_r( &TU, 1 ) ); - - if( ( U1.p[0] & 1 ) != 0 || ( U2.p[0] & 1 ) != 0 ) - { - MPI_CHK( mpi_add_mpi( &U1, &U1, &TB ) ); - MPI_CHK( mpi_sub_mpi( &U2, &U2, &TA ) ); - } - - MPI_CHK( mpi_shift_r( &U1, 1 ) ); - MPI_CHK( mpi_shift_r( &U2, 1 ) ); - } - - while( ( TV.p[0] & 1 ) == 0 ) - { - MPI_CHK( mpi_shift_r( &TV, 1 ) ); - - if( ( V1.p[0] & 1 ) != 0 || ( V2.p[0] & 1 ) != 0 ) - { - MPI_CHK( mpi_add_mpi( &V1, &V1, &TB ) ); - MPI_CHK( mpi_sub_mpi( &V2, &V2, &TA ) ); - } - - MPI_CHK( mpi_shift_r( &V1, 1 ) ); - MPI_CHK( mpi_shift_r( &V2, 1 ) ); - } - - if( mpi_cmp_mpi( &TU, &TV ) >= 0 ) - { - MPI_CHK( mpi_sub_mpi( &TU, &TU, &TV ) ); - MPI_CHK( mpi_sub_mpi( &U1, &U1, &V1 ) ); - MPI_CHK( mpi_sub_mpi( &U2, &U2, &V2 ) ); - } - else - { - MPI_CHK( mpi_sub_mpi( &TV, &TV, &TU ) ); - MPI_CHK( mpi_sub_mpi( &V1, &V1, &U1 ) ); - MPI_CHK( mpi_sub_mpi( &V2, &V2, &U2 ) ); - } - } - while( mpi_cmp_int( &TU, 0 ) != 0 ); - - while( mpi_cmp_int( &V1, 0 ) < 0 ) - MPI_CHK( mpi_add_mpi( &V1, &V1, N ) ); - - while( mpi_cmp_mpi( &V1, N ) >= 0 ) - MPI_CHK( mpi_sub_mpi( &V1, &V1, N ) ); - - MPI_CHK( mpi_copy( X, &V1 ) ); - -cleanup: - - mpi_free( &TA ); mpi_free( &TU ); mpi_free( &U1 ); mpi_free( &U2 ); - mpi_free( &G ); mpi_free( &TB ); mpi_free( &TV ); - mpi_free( &V1 ); mpi_free( &V2 ); - - return( ret ); -} - -#if defined(POLARSSL_GENPRIME) - -static const int small_prime[] = -{ - 3, 5, 7, 11, 13, 17, 19, 23, - 29, 31, 37, 41, 43, 47, 53, 59, - 61, 67, 71, 73, 79, 83, 89, 97, - 101, 103, 107, 109, 113, 127, 131, 137, - 139, 149, 151, 157, 163, 167, 173, 179, - 181, 191, 193, 197, 199, 211, 223, 227, - 229, 233, 239, 241, 251, 257, 263, 269, - 271, 277, 281, 283, 293, 307, 311, 313, - 317, 331, 337, 347, 349, 353, 359, 367, - 373, 379, 383, 389, 397, 401, 409, 419, - 421, 431, 433, 439, 443, 449, 457, 461, - 463, 467, 479, 487, 491, 499, 503, 509, - 521, 523, 541, 547, 557, 563, 569, 571, - 577, 587, 593, 599, 601, 607, 613, 617, - 619, 631, 641, 643, 647, 653, 659, 661, - 673, 677, 683, 691, 701, 709, 719, 727, - 733, 739, 743, 751, 757, 761, 769, 773, - 787, 797, 809, 811, 821, 823, 827, 829, - 839, 853, 857, 859, 863, 877, 881, 883, - 887, 907, 911, 919, 929, 937, 941, 947, - 953, 967, 971, 977, 983, 991, 997, -103 -}; - -/* - * Miller-Rabin primality test (HAC 4.24) - */ -int mpi_is_prime( mpi *X, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng ) -{ - int ret, xs; - size_t i, j, n, s; - mpi W, R, T, A, RR; - - if( mpi_cmp_int( X, 0 ) == 0 || - mpi_cmp_int( X, 1 ) == 0 ) - return( POLARSSL_ERR_MPI_NOT_ACCEPTABLE ); - - if( mpi_cmp_int( X, 2 ) == 0 ) - return( 0 ); - - mpi_init( &W ); mpi_init( &R ); mpi_init( &T ); mpi_init( &A ); - mpi_init( &RR ); - - xs = X->s; X->s = 1; - - /* - * test trivial factors first - */ - if( ( X->p[0] & 1 ) == 0 ) - return( POLARSSL_ERR_MPI_NOT_ACCEPTABLE ); - - for( i = 0; small_prime[i] > 0; i++ ) - { - t_uint r; - - if( mpi_cmp_int( X, small_prime[i] ) <= 0 ) - return( 0 ); - - MPI_CHK( mpi_mod_int( &r, X, small_prime[i] ) ); - - if( r == 0 ) - return( POLARSSL_ERR_MPI_NOT_ACCEPTABLE ); - } - - /* - * W = |X| - 1 - * R = W >> lsb( W ) - */ - MPI_CHK( mpi_sub_int( &W, X, 1 ) ); - s = mpi_lsb( &W ); - MPI_CHK( mpi_copy( &R, &W ) ); - MPI_CHK( mpi_shift_r( &R, s ) ); - - i = mpi_msb( X ); - /* - * HAC, table 4.4 - */ - n = ( ( i >= 1300 ) ? 2 : ( i >= 850 ) ? 3 : - ( i >= 650 ) ? 4 : ( i >= 350 ) ? 8 : - ( i >= 250 ) ? 12 : ( i >= 150 ) ? 18 : 27 ); - - for( i = 0; i < n; i++ ) - { - /* - * pick a random A, 1 < A < |X| - 1 - */ - MPI_CHK( mpi_fill_random( &A, X->n * ciL, f_rng, p_rng ) ); - - if( mpi_cmp_mpi( &A, &W ) >= 0 ) - { - j = mpi_msb( &A ) - mpi_msb( &W ); - MPI_CHK( mpi_shift_r( &A, j + 1 ) ); - } - A.p[0] |= 3; - - /* - * A = A^R mod |X| - */ - MPI_CHK( mpi_exp_mod( &A, &A, &R, X, &RR ) ); - - if( mpi_cmp_mpi( &A, &W ) == 0 || - mpi_cmp_int( &A, 1 ) == 0 ) - continue; - - j = 1; - while( j < s && mpi_cmp_mpi( &A, &W ) != 0 ) - { - /* - * A = A * A mod |X| - */ - MPI_CHK( mpi_mul_mpi( &T, &A, &A ) ); - MPI_CHK( mpi_mod_mpi( &A, &T, X ) ); - - if( mpi_cmp_int( &A, 1 ) == 0 ) - break; - - j++; - } - - /* - * not prime if A != |X| - 1 or A == 1 - */ - if( mpi_cmp_mpi( &A, &W ) != 0 || - mpi_cmp_int( &A, 1 ) == 0 ) - { - ret = POLARSSL_ERR_MPI_NOT_ACCEPTABLE; - break; - } - } - -cleanup: - - X->s = xs; - - mpi_free( &W ); mpi_free( &R ); mpi_free( &T ); mpi_free( &A ); - mpi_free( &RR ); - - return( ret ); -} - -/* - * Prime number generation - */ -int mpi_gen_prime( mpi *X, size_t nbits, int dh_flag, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng ) -{ - int ret; - size_t k, n; - mpi Y; - - if( nbits < 3 || nbits > POLARSSL_MPI_MAX_BITS ) - return( POLARSSL_ERR_MPI_BAD_INPUT_DATA ); - - mpi_init( &Y ); - - n = BITS_TO_LIMBS( nbits ); - - MPI_CHK( mpi_fill_random( X, n * ciL, f_rng, p_rng ) ); - - k = mpi_msb( X ); - if( k < nbits ) MPI_CHK( mpi_shift_l( X, nbits - k ) ); - if( k > nbits ) MPI_CHK( mpi_shift_r( X, k - nbits ) ); - - X->p[0] |= 3; - - if( dh_flag == 0 ) - { - while( ( ret = mpi_is_prime( X, f_rng, p_rng ) ) != 0 ) - { - if( ret != POLARSSL_ERR_MPI_NOT_ACCEPTABLE ) - goto cleanup; - - MPI_CHK( mpi_add_int( X, X, 2 ) ); - } - } - else - { - MPI_CHK( mpi_sub_int( &Y, X, 1 ) ); - MPI_CHK( mpi_shift_r( &Y, 1 ) ); - - while( 1 ) - { - if( ( ret = mpi_is_prime( X, f_rng, p_rng ) ) == 0 ) - { - if( ( ret = mpi_is_prime( &Y, f_rng, p_rng ) ) == 0 ) - break; - - if( ret != POLARSSL_ERR_MPI_NOT_ACCEPTABLE ) - goto cleanup; - } - - if( ret != POLARSSL_ERR_MPI_NOT_ACCEPTABLE ) - goto cleanup; - - MPI_CHK( mpi_add_int( &Y, X, 1 ) ); - MPI_CHK( mpi_add_int( X, X, 2 ) ); - MPI_CHK( mpi_shift_r( &Y, 1 ) ); - } - } - -cleanup: - - mpi_free( &Y ); - - return( ret ); -} - -#endif - -#if defined(POLARSSL_SELF_TEST) - -#define GCD_PAIR_COUNT 3 - -static const int gcd_pairs[GCD_PAIR_COUNT][3] = -{ - { 693, 609, 21 }, - { 1764, 868, 28 }, - { 768454923, 542167814, 1 } -}; - -/* - * Checkup routine - */ -int mpi_self_test( int verbose ) -{ - int ret, i; - mpi A, E, N, X, Y, U, V; - - mpi_init( &A ); mpi_init( &E ); mpi_init( &N ); mpi_init( &X ); - mpi_init( &Y ); mpi_init( &U ); mpi_init( &V ); - - MPI_CHK( mpi_read_string( &A, 16, - "EFE021C2645FD1DC586E69184AF4A31E" \ - "D5F53E93B5F123FA41680867BA110131" \ - "944FE7952E2517337780CB0DB80E61AA" \ - "E7C8DDC6C5C6AADEB34EB38A2F40D5E6" ) ); - - MPI_CHK( mpi_read_string( &E, 16, - "B2E7EFD37075B9F03FF989C7C5051C20" \ - "34D2A323810251127E7BF8625A4F49A5" \ - "F3E27F4DA8BD59C47D6DAABA4C8127BD" \ - "5B5C25763222FEFCCFC38B832366C29E" ) ); - - MPI_CHK( mpi_read_string( &N, 16, - "0066A198186C18C10B2F5ED9B522752A" \ - "9830B69916E535C8F047518A889A43A5" \ - "94B6BED27A168D31D4A52F88925AA8F5" ) ); - - MPI_CHK( mpi_mul_mpi( &X, &A, &N ) ); - - MPI_CHK( mpi_read_string( &U, 16, - "602AB7ECA597A3D6B56FF9829A5E8B85" \ - "9E857EA95A03512E2BAE7391688D264A" \ - "A5663B0341DB9CCFD2C4C5F421FEC814" \ - "8001B72E848A38CAE1C65F78E56ABDEF" \ - "E12D3C039B8A02D6BE593F0BBBDA56F1" \ - "ECF677152EF804370C1A305CAF3B5BF1" \ - "30879B56C61DE584A0F53A2447A51E" ) ); - - if( verbose != 0 ) - printf( " MPI test #1 (mul_mpi): " ); - - if( mpi_cmp_mpi( &X, &U ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( verbose != 0 ) - printf( "passed\n" ); - - MPI_CHK( mpi_div_mpi( &X, &Y, &A, &N ) ); - - MPI_CHK( mpi_read_string( &U, 16, - "256567336059E52CAE22925474705F39A94" ) ); - - MPI_CHK( mpi_read_string( &V, 16, - "6613F26162223DF488E9CD48CC132C7A" \ - "0AC93C701B001B092E4E5B9F73BCD27B" \ - "9EE50D0657C77F374E903CDFA4C642" ) ); - - if( verbose != 0 ) - printf( " MPI test #2 (div_mpi): " ); - - if( mpi_cmp_mpi( &X, &U ) != 0 || - mpi_cmp_mpi( &Y, &V ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( verbose != 0 ) - printf( "passed\n" ); - - MPI_CHK( mpi_exp_mod( &X, &A, &E, &N, NULL ) ); - - MPI_CHK( mpi_read_string( &U, 16, - "36E139AEA55215609D2816998ED020BB" \ - "BD96C37890F65171D948E9BC7CBAA4D9" \ - "325D24D6A3C12710F10A09FA08AB87" ) ); - - if( verbose != 0 ) - printf( " MPI test #3 (exp_mod): " ); - - if( mpi_cmp_mpi( &X, &U ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( verbose != 0 ) - printf( "passed\n" ); - -#if defined(POLARSSL_GENPRIME) - MPI_CHK( mpi_inv_mod( &X, &A, &N ) ); - - MPI_CHK( mpi_read_string( &U, 16, - "003A0AAEDD7E784FC07D8F9EC6E3BFD5" \ - "C3DBA76456363A10869622EAC2DD84EC" \ - "C5B8A74DAC4D09E03B5E0BE779F2DF61" ) ); - - if( verbose != 0 ) - printf( " MPI test #4 (inv_mod): " ); - - if( mpi_cmp_mpi( &X, &U ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( verbose != 0 ) - printf( "passed\n" ); -#endif - - if( verbose != 0 ) - printf( " MPI test #5 (simple gcd): " ); - - for ( i = 0; i < GCD_PAIR_COUNT; i++) - { - MPI_CHK( mpi_lset( &X, gcd_pairs[i][0] ) ); - MPI_CHK( mpi_lset( &Y, gcd_pairs[i][1] ) ); - - MPI_CHK( mpi_gcd( &A, &X, &Y ) ); - - if( mpi_cmp_int( &A, gcd_pairs[i][2] ) != 0 ) - { - if( verbose != 0 ) - printf( "failed at %d\n", i ); - - return( 1 ); - } - } - - if( verbose != 0 ) - printf( "passed\n" ); - -cleanup: - - if( ret != 0 && verbose != 0 ) - printf( "Unexpected error, return code = %08X\n", ret ); - - mpi_free( &A ); mpi_free( &E ); mpi_free( &N ); mpi_free( &X ); - mpi_free( &Y ); mpi_free( &U ); mpi_free( &V ); - - if( verbose != 0 ) - printf( "\n" ); - - return( ret ); -} - -#endif - -#endif diff --git a/lib/libpolarssl/source/ctr_drbg.c b/lib/libpolarssl/source/ctr_drbg.c deleted file mode 100644 index 989eb45..0000000 --- a/lib/libpolarssl/source/ctr_drbg.c +++ /dev/null @@ -1,582 +0,0 @@ -/* - * CTR_DRBG implementation based on AES-256 (NIST SP 800-90) - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved - * - * This file is part of mbed TLS (https://polarssl.org) - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ -/* - * The NIST SP 800-90 DRBGs are described in the following publucation. - * - * http://csrc.nist.gov/publications/nistpubs/800-90/SP800-90revised_March2007.pdf - */ - -#include "polarssl/config.h" - -#if defined(POLARSSL_CTR_DRBG_C) - -#include "polarssl/ctr_drbg.h" - -#if defined(POLARSSL_FS_IO) -#include -#endif - -/* - * Non-public function wrapped by ctr_crbg_init(). Necessary to allow NIST - * tests to succeed (which require known length fixed entropy) - */ -int ctr_drbg_init_entropy_len( - ctr_drbg_context *ctx, - int (*f_entropy)(void *, unsigned char *, size_t), - void *p_entropy, - const unsigned char *custom, - size_t len, - size_t entropy_len ); - -int ctr_drbg_init_entropy_len( - ctr_drbg_context *ctx, - int (*f_entropy)(void *, unsigned char *, size_t), - void *p_entropy, - const unsigned char *custom, - size_t len, - size_t entropy_len ) -{ - int ret; - unsigned char key[CTR_DRBG_KEYSIZE]; - - memset( ctx, 0, sizeof(ctr_drbg_context) ); - memset( key, 0, CTR_DRBG_KEYSIZE ); - - ctx->f_entropy = f_entropy; - ctx->p_entropy = p_entropy; - - ctx->entropy_len = entropy_len; - ctx->reseed_interval = CTR_DRBG_RESEED_INTERVAL; - - /* - * Initialize with an empty key - */ - aes_setkey_enc( &ctx->aes_ctx, key, CTR_DRBG_KEYBITS ); - - if( ( ret = ctr_drbg_reseed( ctx, custom, len ) ) != 0 ) - return( ret ); - - return( 0 ); -} - -int ctr_drbg_init( ctr_drbg_context *ctx, - int (*f_entropy)(void *, unsigned char *, size_t), - void *p_entropy, - const unsigned char *custom, - size_t len ) -{ - return( ctr_drbg_init_entropy_len( ctx, f_entropy, p_entropy, custom, len, - CTR_DRBG_ENTROPY_LEN ) ); -} - -void ctr_drbg_set_prediction_resistance( ctr_drbg_context *ctx, int resistance ) -{ - ctx->prediction_resistance = resistance; -} - -void ctr_drbg_set_entropy_len( ctr_drbg_context *ctx, size_t len ) -{ - ctx->entropy_len = len; -} - -void ctr_drbg_set_reseed_interval( ctr_drbg_context *ctx, int interval ) -{ - ctx->reseed_interval = interval; -} - -static int block_cipher_df( unsigned char *output, - const unsigned char *data, size_t data_len ) -{ - unsigned char buf[CTR_DRBG_MAX_SEED_INPUT + CTR_DRBG_BLOCKSIZE + 16]; - unsigned char tmp[CTR_DRBG_SEEDLEN]; - unsigned char key[CTR_DRBG_KEYSIZE]; - unsigned char chain[CTR_DRBG_BLOCKSIZE]; - unsigned char *p, *iv; - aes_context aes_ctx; - - int i, j, buf_len, use_len; - - if( data_len > CTR_DRBG_MAX_SEED_INPUT ) - return( POLARSSL_ERR_CTR_DRBG_INPUT_TOO_BIG ); - - memset( buf, 0, CTR_DRBG_MAX_SEED_INPUT + CTR_DRBG_BLOCKSIZE + 16 ); - - /* - * Construct IV (16 bytes) and S in buffer - * IV = Counter (in 32-bits) padded to 16 with zeroes - * S = Length input string (in 32-bits) || Length of output (in 32-bits) || - * data || 0x80 - * (Total is padded to a multiple of 16-bytes with zeroes) - */ - p = buf + CTR_DRBG_BLOCKSIZE; - *p++ = ( data_len >> 24 ) & 0xff; - *p++ = ( data_len >> 16 ) & 0xff; - *p++ = ( data_len >> 8 ) & 0xff; - *p++ = ( data_len ) & 0xff; - p += 3; - *p++ = CTR_DRBG_SEEDLEN; - memcpy( p, data, data_len ); - p[data_len] = 0x80; - - buf_len = CTR_DRBG_BLOCKSIZE + 8 + data_len + 1; - - for( i = 0; i < CTR_DRBG_KEYSIZE; i++ ) - key[i] = i; - - aes_setkey_enc( &aes_ctx, key, CTR_DRBG_KEYBITS ); - - /* - * Reduce data to POLARSSL_CTR_DRBG_SEEDLEN bytes of data - */ - for( j = 0; j < CTR_DRBG_SEEDLEN; j += CTR_DRBG_BLOCKSIZE ) - { - p = buf; - memset( chain, 0, CTR_DRBG_BLOCKSIZE ); - use_len = buf_len; - - while( use_len > 0 ) - { - for( i = 0; i < CTR_DRBG_BLOCKSIZE; i++ ) - chain[i] ^= p[i]; - p += CTR_DRBG_BLOCKSIZE; - use_len -= CTR_DRBG_BLOCKSIZE; - - aes_crypt_ecb( &aes_ctx, AES_ENCRYPT, chain, chain ); - } - - memcpy( tmp + j, chain, CTR_DRBG_BLOCKSIZE ); - - /* - * Update IV - */ - buf[3]++; - } - - /* - * Do final encryption with reduced data - */ - aes_setkey_enc( &aes_ctx, tmp, CTR_DRBG_KEYBITS ); - iv = tmp + CTR_DRBG_KEYSIZE; - p = output; - - for( j = 0; j < CTR_DRBG_SEEDLEN; j += CTR_DRBG_BLOCKSIZE ) - { - aes_crypt_ecb( &aes_ctx, AES_ENCRYPT, iv, iv ); - memcpy( p, iv, CTR_DRBG_BLOCKSIZE ); - p += CTR_DRBG_BLOCKSIZE; - } - - return( 0 ); -} - -static int ctr_drbg_update_internal( ctr_drbg_context *ctx, - const unsigned char data[CTR_DRBG_SEEDLEN] ) -{ - unsigned char tmp[CTR_DRBG_SEEDLEN]; - unsigned char *p = tmp; - int i, j; - - memset( tmp, 0, CTR_DRBG_SEEDLEN ); - - for( j = 0; j < CTR_DRBG_SEEDLEN; j += CTR_DRBG_BLOCKSIZE ) - { - /* - * Increase counter - */ - for( i = CTR_DRBG_BLOCKSIZE; i > 0; i-- ) - if( ++ctx->counter[i - 1] != 0 ) - break; - - /* - * Crypt counter block - */ - aes_crypt_ecb( &ctx->aes_ctx, AES_ENCRYPT, ctx->counter, p ); - - p += CTR_DRBG_BLOCKSIZE; - } - - for( i = 0; i < CTR_DRBG_SEEDLEN; i++ ) - tmp[i] ^= data[i]; - - /* - * Update key and counter - */ - aes_setkey_enc( &ctx->aes_ctx, tmp, CTR_DRBG_KEYBITS ); - memcpy( ctx->counter, tmp + CTR_DRBG_KEYSIZE, CTR_DRBG_BLOCKSIZE ); - - return( 0 ); -} - -void ctr_drbg_update( ctr_drbg_context *ctx, - const unsigned char *additional, size_t add_len ) -{ - unsigned char add_input[CTR_DRBG_SEEDLEN]; - - if( add_len > 0 ) - { - /* MAX_INPUT would be more logical here, but we have to match - * block_cipher_df()'s limits since we can't propagate errors */ - if( add_len > CTR_DRBG_MAX_SEED_INPUT ) - add_len = CTR_DRBG_MAX_SEED_INPUT; - - block_cipher_df( add_input, additional, add_len ); - ctr_drbg_update_internal( ctx, add_input ); - } -} - -int ctr_drbg_reseed( ctr_drbg_context *ctx, - const unsigned char *additional, size_t len ) -{ - unsigned char seed[CTR_DRBG_MAX_SEED_INPUT]; - size_t seedlen = 0; - - if( ctx->entropy_len + len > CTR_DRBG_MAX_SEED_INPUT ) - return( POLARSSL_ERR_CTR_DRBG_INPUT_TOO_BIG ); - - memset( seed, 0, CTR_DRBG_MAX_SEED_INPUT ); - - /* - * Gather enropy_len bytes of entropy to seed state - */ - if( 0 != ctx->f_entropy( ctx->p_entropy, seed, - ctx->entropy_len ) ) - { - return( POLARSSL_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED ); - } - - seedlen += ctx->entropy_len; - - /* - * Add additional data - */ - if( additional && len ) - { - memcpy( seed + seedlen, additional, len ); - seedlen += len; - } - - /* - * Reduce to 384 bits - */ - block_cipher_df( seed, seed, seedlen ); - - /* - * Update state - */ - ctr_drbg_update_internal( ctx, seed ); - ctx->reseed_counter = 1; - - return( 0 ); -} - -int ctr_drbg_random_with_add( void *p_rng, - unsigned char *output, size_t output_len, - const unsigned char *additional, size_t add_len ) -{ - int ret = 0; - ctr_drbg_context *ctx = (ctr_drbg_context *) p_rng; - unsigned char add_input[CTR_DRBG_SEEDLEN]; - unsigned char *p = output; - unsigned char tmp[CTR_DRBG_BLOCKSIZE]; - int i; - size_t use_len; - - if( output_len > CTR_DRBG_MAX_REQUEST ) - return( POLARSSL_ERR_CTR_DRBG_REQUEST_TOO_BIG ); - - if( add_len > CTR_DRBG_MAX_INPUT ) - return( POLARSSL_ERR_CTR_DRBG_INPUT_TOO_BIG ); - - memset( add_input, 0, CTR_DRBG_SEEDLEN ); - - if( ctx->reseed_counter > ctx->reseed_interval || - ctx->prediction_resistance ) - { - if( ( ret = ctr_drbg_reseed( ctx, additional, add_len ) ) != 0 ) - return( ret ); - - add_len = 0; - } - - if( add_len > 0 ) - { - block_cipher_df( add_input, additional, add_len ); - ctr_drbg_update_internal( ctx, add_input ); - } - - while( output_len > 0 ) - { - /* - * Increase counter - */ - for( i = CTR_DRBG_BLOCKSIZE; i > 0; i-- ) - if( ++ctx->counter[i - 1] != 0 ) - break; - - /* - * Crypt counter block - */ - aes_crypt_ecb( &ctx->aes_ctx, AES_ENCRYPT, ctx->counter, tmp ); - - use_len = (output_len > CTR_DRBG_BLOCKSIZE ) ? CTR_DRBG_BLOCKSIZE : output_len; - /* - * Copy random block to destination - */ - memcpy( p, tmp, use_len ); - p += use_len; - output_len -= use_len; - } - - ctr_drbg_update_internal( ctx, add_input ); - - ctx->reseed_counter++; - - return( 0 ); -} - -int ctr_drbg_random( void *p_rng, unsigned char *output, size_t output_len ) -{ - return ctr_drbg_random_with_add( p_rng, output, output_len, NULL, 0 ); -} - -#if defined(POLARSSL_FS_IO) -int ctr_drbg_write_seed_file( ctr_drbg_context *ctx, const char *path ) -{ - int ret; - FILE *f; - unsigned char buf[ CTR_DRBG_MAX_INPUT ]; - - if( ( f = fopen( path, "wb" ) ) == NULL ) - return( POLARSSL_ERR_CTR_DRBG_FILE_IO_ERROR ); - - if( ( ret = ctr_drbg_random( ctx, buf, CTR_DRBG_MAX_INPUT ) ) != 0 ) - { - fclose( f ); - return( ret ); - } - - if( fwrite( buf, 1, CTR_DRBG_MAX_INPUT, f ) != CTR_DRBG_MAX_INPUT ) - { - fclose( f ); - return( POLARSSL_ERR_CTR_DRBG_FILE_IO_ERROR ); - } - - fclose( f ); - return( 0 ); -} - -int ctr_drbg_update_seed_file( ctr_drbg_context *ctx, const char *path ) -{ - FILE *f; - size_t n; - unsigned char buf[ CTR_DRBG_MAX_INPUT ]; - - if( ( f = fopen( path, "rb" ) ) == NULL ) - return( POLARSSL_ERR_CTR_DRBG_FILE_IO_ERROR ); - - fseek( f, 0, SEEK_END ); - n = (size_t) ftell( f ); - fseek( f, 0, SEEK_SET ); - - if( n > CTR_DRBG_MAX_INPUT ) - { - fclose( f ); - return( POLARSSL_ERR_CTR_DRBG_INPUT_TOO_BIG ); - } - - if( fread( buf, 1, n, f ) != n ) - { - fclose( f ); - return( POLARSSL_ERR_CTR_DRBG_FILE_IO_ERROR ); - } - - ctr_drbg_update( ctx, buf, n ); - - fclose( f ); - - return( ctr_drbg_write_seed_file( ctx, path ) ); -} -#endif /* POLARSSL_FS_IO */ - -#if defined(POLARSSL_SELF_TEST) - -#include - -unsigned char entropy_source_pr[96] = - { 0xc1, 0x80, 0x81, 0xa6, 0x5d, 0x44, 0x02, 0x16, - 0x19, 0xb3, 0xf1, 0x80, 0xb1, 0xc9, 0x20, 0x02, - 0x6a, 0x54, 0x6f, 0x0c, 0x70, 0x81, 0x49, 0x8b, - 0x6e, 0xa6, 0x62, 0x52, 0x6d, 0x51, 0xb1, 0xcb, - 0x58, 0x3b, 0xfa, 0xd5, 0x37, 0x5f, 0xfb, 0xc9, - 0xff, 0x46, 0xd2, 0x19, 0xc7, 0x22, 0x3e, 0x95, - 0x45, 0x9d, 0x82, 0xe1, 0xe7, 0x22, 0x9f, 0x63, - 0x31, 0x69, 0xd2, 0x6b, 0x57, 0x47, 0x4f, 0xa3, - 0x37, 0xc9, 0x98, 0x1c, 0x0b, 0xfb, 0x91, 0x31, - 0x4d, 0x55, 0xb9, 0xe9, 0x1c, 0x5a, 0x5e, 0xe4, - 0x93, 0x92, 0xcf, 0xc5, 0x23, 0x12, 0xd5, 0x56, - 0x2c, 0x4a, 0x6e, 0xff, 0xdc, 0x10, 0xd0, 0x68 }; - -unsigned char entropy_source_nopr[64] = - { 0x5a, 0x19, 0x4d, 0x5e, 0x2b, 0x31, 0x58, 0x14, - 0x54, 0xde, 0xf6, 0x75, 0xfb, 0x79, 0x58, 0xfe, - 0xc7, 0xdb, 0x87, 0x3e, 0x56, 0x89, 0xfc, 0x9d, - 0x03, 0x21, 0x7c, 0x68, 0xd8, 0x03, 0x38, 0x20, - 0xf9, 0xe6, 0x5e, 0x04, 0xd8, 0x56, 0xf3, 0xa9, - 0xc4, 0x4a, 0x4c, 0xbd, 0xc1, 0xd0, 0x08, 0x46, - 0xf5, 0x98, 0x3d, 0x77, 0x1c, 0x1b, 0x13, 0x7e, - 0x4e, 0x0f, 0x9d, 0x8e, 0xf4, 0x09, 0xf9, 0x2e }; - -unsigned char nonce_pers_pr[16] = - { 0xd2, 0x54, 0xfc, 0xff, 0x02, 0x1e, 0x69, 0xd2, - 0x29, 0xc9, 0xcf, 0xad, 0x85, 0xfa, 0x48, 0x6c }; - -unsigned char nonce_pers_nopr[16] = - { 0x1b, 0x54, 0xb8, 0xff, 0x06, 0x42, 0xbf, 0xf5, - 0x21, 0xf1, 0x5c, 0x1c, 0x0b, 0x66, 0x5f, 0x3f }; - -unsigned char result_pr[16] = - { 0x34, 0x01, 0x16, 0x56, 0xb4, 0x29, 0x00, 0x8f, - 0x35, 0x63, 0xec, 0xb5, 0xf2, 0x59, 0x07, 0x23 }; - -unsigned char result_nopr[16] = - { 0xa0, 0x54, 0x30, 0x3d, 0x8a, 0x7e, 0xa9, 0x88, - 0x9d, 0x90, 0x3e, 0x07, 0x7c, 0x6f, 0x21, 0x8f }; - -static size_t test_offset; -static int ctr_drbg_self_test_entropy( void *data, unsigned char *buf, - size_t len ) -{ - unsigned char *p = data; - memcpy( buf, p + test_offset, len ); - test_offset += 32; - return( 0 ); -} - -/* - * Checkup routine - */ -int ctr_drbg_self_test( int verbose ) -{ - ctr_drbg_context ctx; - unsigned char buf[16]; - - /* - * Based on a NIST CTR_DRBG test vector (PR = True) - */ - if( verbose != 0 ) - printf( " CTR_DRBG (PR = TRUE) : " ); - - test_offset = 0; - if( ctr_drbg_init_entropy_len( &ctx, ctr_drbg_self_test_entropy, entropy_source_pr, nonce_pers_pr, 16, 32 ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - ctr_drbg_set_prediction_resistance( &ctx, CTR_DRBG_PR_ON ); - - if( ctr_drbg_random( &ctx, buf, CTR_DRBG_BLOCKSIZE ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( ctr_drbg_random( &ctx, buf, CTR_DRBG_BLOCKSIZE ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( memcmp( buf, result_pr, CTR_DRBG_BLOCKSIZE ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( verbose != 0 ) - printf( "passed\n" ); - - /* - * Based on a NIST CTR_DRBG test vector (PR = FALSE) - */ - if( verbose != 0 ) - printf( " CTR_DRBG (PR = FALSE): " ); - - test_offset = 0; - if( ctr_drbg_init_entropy_len( &ctx, ctr_drbg_self_test_entropy, entropy_source_nopr, nonce_pers_nopr, 16, 32 ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( ctr_drbg_random( &ctx, buf, 16 ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( ctr_drbg_reseed( &ctx, NULL, 0 ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( ctr_drbg_random( &ctx, buf, 16 ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( memcmp( buf, result_nopr, 16 ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( verbose != 0 ) - printf( "passed\n" ); - - if( verbose != 0 ) - printf( "\n" ); - - return( 0 ); -} -#endif - -#endif diff --git a/lib/libpolarssl/source/entropy.c b/lib/libpolarssl/source/entropy.c deleted file mode 100644 index a9d2f1b..0000000 --- a/lib/libpolarssl/source/entropy.c +++ /dev/null @@ -1,261 +0,0 @@ -/* - * Entropy accumulator implementation - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved - * - * This file is part of mbed TLS (https://polarssl.org) - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ - -#include "polarssl/config.h" - -#if defined(POLARSSL_ENTROPY_C) - -#include "polarssl/entropy.h" -#include "polarssl/entropy_poll.h" - -#if defined(POLARSSL_FS_IO) -#include -#endif - -#if defined(POLARSSL_HAVEGE_C) -#include "polarssl/havege.h" -#endif - -#define ENTROPY_MAX_LOOP 256 /**< Maximum amount to loop before error */ - -void entropy_init( entropy_context *ctx ) -{ - memset( ctx, 0, sizeof(entropy_context) ); - - sha4_starts( &ctx->accumulator, 0 ); -#if defined(POLARSSL_HAVEGE_C) - havege_init( &ctx->havege_data ); -#endif - -#if !defined(POLARSSL_NO_DEFAULT_ENTROPY_SOURCES) -#if !defined(POLARSSL_NO_PLATFORM_ENTROPY) - entropy_add_source( ctx, platform_entropy_poll, NULL, - ENTROPY_MIN_PLATFORM ); -#endif -#if defined(POLARSSL_TIMING_C) - entropy_add_source( ctx, hardclock_poll, NULL, ENTROPY_MIN_HARDCLOCK ); -#endif -#if defined(POLARSSL_HAVEGE_C) - entropy_add_source( ctx, havege_poll, &ctx->havege_data, - ENTROPY_MIN_HAVEGE ); -#endif -#endif /* POLARSSL_NO_DEFAULT_ENTROPY_SOURCES */ -} - -int entropy_add_source( entropy_context *ctx, - f_source_ptr f_source, void *p_source, - size_t threshold ) -{ - int index = ctx->source_count; - - if( index >= ENTROPY_MAX_SOURCES ) - return( POLARSSL_ERR_ENTROPY_MAX_SOURCES ); - - ctx->source[index].f_source = f_source; - ctx->source[index].p_source = p_source; - ctx->source[index].threshold = threshold; - - ctx->source_count++; - - return( 0 ); -} - -/* - * Entropy accumulator update - */ -static int entropy_update( entropy_context *ctx, unsigned char source_id, - const unsigned char *data, size_t len ) -{ - unsigned char header[2]; - unsigned char tmp[ENTROPY_BLOCK_SIZE]; - size_t use_len = len; - const unsigned char *p = data; - - if( use_len > ENTROPY_BLOCK_SIZE ) - { - sha4( data, len, tmp, 0 ); - - p = tmp; - use_len = ENTROPY_BLOCK_SIZE; - } - - header[0] = source_id; - header[1] = use_len & 0xFF; - - sha4_update( &ctx->accumulator, header, 2 ); - sha4_update( &ctx->accumulator, p, use_len ); - - return( 0 ); -} - -int entropy_update_manual( entropy_context *ctx, - const unsigned char *data, size_t len ) -{ - return entropy_update( ctx, ENTROPY_SOURCE_MANUAL, data, len ); -} - -/* - * Run through the different sources to add entropy to our accumulator - */ -int entropy_gather( entropy_context *ctx ) -{ - int ret, i; - unsigned char buf[ENTROPY_MAX_GATHER]; - size_t olen; - - if( ctx->source_count == 0 ) - return( POLARSSL_ERR_ENTROPY_NO_SOURCES_DEFINED ); - - /* - * Run through our entropy sources - */ - for( i = 0; i < ctx->source_count; i++ ) - { - olen = 0; - if ( ( ret = ctx->source[i].f_source( ctx->source[i].p_source, - buf, ENTROPY_MAX_GATHER, &olen ) ) != 0 ) - { - return( ret ); - } - - /* - * Add if we actually gathered something - */ - if( olen > 0 ) - { - entropy_update( ctx, (unsigned char) i, buf, olen ); - ctx->source[i].size += olen; - } - } - - return( 0 ); -} - -int entropy_func( void *data, unsigned char *output, size_t len ) -{ - int ret, count = 0, i, reached; - entropy_context *ctx = (entropy_context *) data; - unsigned char buf[ENTROPY_BLOCK_SIZE]; - - if( len > ENTROPY_BLOCK_SIZE ) - return( POLARSSL_ERR_ENTROPY_SOURCE_FAILED ); - - /* - * Always gather extra entropy before a call - */ - do - { - if( count++ > ENTROPY_MAX_LOOP ) - return( POLARSSL_ERR_ENTROPY_SOURCE_FAILED ); - - if( ( ret = entropy_gather( ctx ) ) != 0 ) - return( ret ); - - reached = 0; - - for( i = 0; i < ctx->source_count; i++ ) - if( ctx->source[i].size >= ctx->source[i].threshold ) - reached++; - } - while( reached != ctx->source_count ); - - memset( buf, 0, ENTROPY_BLOCK_SIZE ); - - sha4_finish( &ctx->accumulator, buf ); - - /* - * Reset accumulator and counters and recycle existing entropy - */ - memset( &ctx->accumulator, 0, sizeof( sha4_context ) ); - sha4_starts( &ctx->accumulator, 0 ); - sha4_update( &ctx->accumulator, buf, ENTROPY_BLOCK_SIZE ); - - /* - * Perform second SHA-512 on entropy - */ - sha4( buf, ENTROPY_BLOCK_SIZE, buf, 0 ); - - for( i = 0; i < ctx->source_count; i++ ) - ctx->source[i].size = 0; - - memcpy( output, buf, len ); - - return( 0 ); -} - -#if defined(POLARSSL_FS_IO) -int entropy_write_seed_file( entropy_context *ctx, const char *path ) -{ - int ret = POLARSSL_ERR_ENTROPY_FILE_IO_ERROR; - FILE *f; - unsigned char buf[ENTROPY_BLOCK_SIZE]; - - if( ( f = fopen( path, "wb" ) ) == NULL ) - return( POLARSSL_ERR_ENTROPY_FILE_IO_ERROR ); - - if( ( ret = entropy_func( ctx, buf, ENTROPY_BLOCK_SIZE ) ) != 0 ) - goto exit; - - if( fwrite( buf, 1, ENTROPY_BLOCK_SIZE, f ) != ENTROPY_BLOCK_SIZE ) - { - ret = POLARSSL_ERR_ENTROPY_FILE_IO_ERROR; - goto exit; - } - - ret = 0; - -exit: - fclose( f ); - return( ret ); -} - -int entropy_update_seed_file( entropy_context *ctx, const char *path ) -{ - FILE *f; - size_t n; - unsigned char buf[ ENTROPY_MAX_SEED_SIZE ]; - - if( ( f = fopen( path, "rb" ) ) == NULL ) - return( POLARSSL_ERR_ENTROPY_FILE_IO_ERROR ); - - fseek( f, 0, SEEK_END ); - n = (size_t) ftell( f ); - fseek( f, 0, SEEK_SET ); - - if( n > ENTROPY_MAX_SEED_SIZE ) - n = ENTROPY_MAX_SEED_SIZE; - - if( fread( buf, 1, n, f ) != n ) - { - fclose( f ); - return( POLARSSL_ERR_ENTROPY_FILE_IO_ERROR ); - } - - fclose( f ); - - entropy_update_manual( ctx, buf, n ); - - return( entropy_write_seed_file( ctx, path ) ); -} -#endif /* POLARSSL_FS_IO */ - -#endif diff --git a/lib/libpolarssl/source/entropy_poll.c b/lib/libpolarssl/source/entropy_poll.c deleted file mode 100644 index 17be637..0000000 --- a/lib/libpolarssl/source/entropy_poll.c +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Platform-specific and custom entropy polling functions - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved - * - * This file is part of mbed TLS (https://polarssl.org) - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ - -#include "polarssl/config.h" - -#if defined(POLARSSL_ENTROPY_C) - -#include "polarssl/entropy.h" -#include "polarssl/entropy_poll.h" - -#if defined(POLARSSL_TIMING_C) -#include "polarssl/timing.h" -#endif -#if defined(POLARSSL_HAVEGE_C) -#include "polarssl/havege.h" -#endif - -#if !defined(POLARSSL_NO_PLATFORM_ENTROPY) -#if defined(_WIN32) - -#if !defined(_WIN32_WINNT) -#define _WIN32_WINNT 0x0400 -#endif -#include -#include - -int platform_entropy_poll( void *data, unsigned char *output, size_t len, - size_t *olen ) -{ - HCRYPTPROV provider; - ((void) data); - *olen = 0; - - if( CryptAcquireContext( &provider, NULL, NULL, - PROV_RSA_FULL, CRYPT_VERIFYCONTEXT ) == FALSE ) - { - return POLARSSL_ERR_ENTROPY_SOURCE_FAILED; - } - - if( CryptGenRandom( provider, len, output ) == FALSE ) - return POLARSSL_ERR_ENTROPY_SOURCE_FAILED; - - CryptReleaseContext( provider, 0 ); - *olen = len; - - return( 0 ); -} -#else - -#include - -int platform_entropy_poll( void *data, - unsigned char *output, size_t len, size_t *olen ) -{ - FILE *file; - size_t ret; - ((void) data); - - *olen = 0; - - file = fopen( "/dev/urandom", "rb" ); - if( file == NULL ) - return POLARSSL_ERR_ENTROPY_SOURCE_FAILED; - - ret = fread( output, 1, len, file ); - if( ret != len ) - { - fclose( file ); - return POLARSSL_ERR_ENTROPY_SOURCE_FAILED; - } - - fclose( file ); - *olen = len; - - return( 0 ); -} -#endif -#endif - -#if defined(POLARSSL_TIMING_C) -int hardclock_poll( void *data, - unsigned char *output, size_t len, size_t *olen ) -{ - unsigned long timer = hardclock(); - ((void) data); - *olen = 0; - - if( len < sizeof(unsigned long) ) - return( 0 ); - - memcpy( output, &timer, sizeof(unsigned long) ); - *olen = sizeof(unsigned long); - - return( 0 ); -} -#endif - -#if defined(POLARSSL_HAVEGE_C) -int havege_poll( void *data, - unsigned char *output, size_t len, size_t *olen ) -{ - havege_state *hs = (havege_state *) data; - *olen = 0; - - if( havege_random( hs, output, len ) != 0 ) - return POLARSSL_ERR_ENTROPY_SOURCE_FAILED; - - *olen = len; - - return( 0 ); -} -#endif - -#endif /* POLARSSL_ENTROPY_C */ diff --git a/lib/libpolarssl/source/md.c b/lib/libpolarssl/source/md.c deleted file mode 100644 index c16f2fb..0000000 --- a/lib/libpolarssl/source/md.c +++ /dev/null @@ -1,300 +0,0 @@ -/** - * \file md.c - * - * \brief Generic message digest wrapper for PolarSSL - * - * \author Adriaan de Jong - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved - * - * This file is part of mbed TLS (https://polarssl.org) - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ - -#include "polarssl/config.h" - -#if defined(POLARSSL_MD_C) - -#include "polarssl/md.h" -#include "polarssl/md_wrap.h" - -#include - -#if defined _MSC_VER && !defined strcasecmp -#define strcasecmp _stricmp -#endif - -/* Implementation that should never be optimized out by the compiler */ -static void polarssl_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - -static const int supported_digests[] = { - -#if defined(POLARSSL_MD2_C) - POLARSSL_MD_MD2, -#endif - -#if defined(POLARSSL_MD4_C) - POLARSSL_MD_MD4, -#endif - -#if defined(POLARSSL_MD5_C) - POLARSSL_MD_MD5, -#endif - -#if defined(POLARSSL_SHA1_C) - POLARSSL_MD_SHA1, -#endif - -#if defined(POLARSSL_SHA2_C) - POLARSSL_MD_SHA224, - POLARSSL_MD_SHA256, -#endif - -#if defined(POLARSSL_SHA4_C) - POLARSSL_MD_SHA384, - POLARSSL_MD_SHA512, -#endif - - 0 -}; - -const int *md_list( void ) -{ - return supported_digests; -} - -const md_info_t *md_info_from_string( const char *md_name ) -{ - if( NULL == md_name ) - return NULL; - - /* Get the appropriate digest information */ -#if defined(POLARSSL_MD2_C) - if( !strcasecmp( "MD2", md_name ) ) - return md_info_from_type( POLARSSL_MD_MD2 ); -#endif -#if defined(POLARSSL_MD4_C) - if( !strcasecmp( "MD4", md_name ) ) - return md_info_from_type( POLARSSL_MD_MD4 ); -#endif -#if defined(POLARSSL_MD5_C) - if( !strcasecmp( "MD5", md_name ) ) - return md_info_from_type( POLARSSL_MD_MD5 ); -#endif -#if defined(POLARSSL_SHA1_C) - if( !strcasecmp( "SHA1", md_name ) || !strcasecmp( "SHA", md_name ) ) - return md_info_from_type( POLARSSL_MD_SHA1 ); -#endif -#if defined(POLARSSL_SHA2_C) - if( !strcasecmp( "SHA224", md_name ) ) - return md_info_from_type( POLARSSL_MD_SHA224 ); - if( !strcasecmp( "SHA256", md_name ) ) - return md_info_from_type( POLARSSL_MD_SHA256 ); -#endif -#if defined(POLARSSL_SHA4_C) - if( !strcasecmp( "SHA384", md_name ) ) - return md_info_from_type( POLARSSL_MD_SHA384 ); - if( !strcasecmp( "SHA512", md_name ) ) - return md_info_from_type( POLARSSL_MD_SHA512 ); -#endif - return NULL; -} - -const md_info_t *md_info_from_type( md_type_t md_type ) -{ - switch( md_type ) - { -#if defined(POLARSSL_MD2_C) - case POLARSSL_MD_MD2: - return &md2_info; -#endif -#if defined(POLARSSL_MD4_C) - case POLARSSL_MD_MD4: - return &md4_info; -#endif -#if defined(POLARSSL_MD5_C) - case POLARSSL_MD_MD5: - return &md5_info; -#endif -#if defined(POLARSSL_SHA1_C) - case POLARSSL_MD_SHA1: - return &sha1_info; -#endif -#if defined(POLARSSL_SHA2_C) - case POLARSSL_MD_SHA224: - return &sha224_info; - case POLARSSL_MD_SHA256: - return &sha256_info; -#endif -#if defined(POLARSSL_SHA4_C) - case POLARSSL_MD_SHA384: - return &sha384_info; - case POLARSSL_MD_SHA512: - return &sha512_info; -#endif - default: - return NULL; - } -} - -int md_init_ctx( md_context_t *ctx, const md_info_t *md_info ) -{ - if( md_info == NULL || ctx == NULL ) - return POLARSSL_ERR_MD_BAD_INPUT_DATA; - - memset( ctx, 0, sizeof( md_context_t ) ); - - if( ( ctx->md_ctx = md_info->ctx_alloc_func() ) == NULL ) - return POLARSSL_ERR_MD_ALLOC_FAILED; - - ctx->md_info = md_info; - - md_info->starts_func( ctx->md_ctx ); - - return 0; -} - -int md_free_ctx( md_context_t *ctx ) -{ - if( ctx == NULL || ctx->md_info == NULL ) - return POLARSSL_ERR_MD_BAD_INPUT_DATA; - - ctx->md_info->ctx_free_func( ctx->md_ctx ); - - polarssl_zeroize( ctx, sizeof( md_context_t ) ); - - return 0; -} - -int md_starts( md_context_t *ctx ) -{ - if( ctx == NULL || ctx->md_info == NULL ) - return POLARSSL_ERR_MD_BAD_INPUT_DATA; - - ctx->md_info->starts_func( ctx->md_ctx ); - - return 0; -} - -int md_update( md_context_t *ctx, const unsigned char *input, size_t ilen ) -{ - if( ctx == NULL || ctx->md_info == NULL ) - return POLARSSL_ERR_MD_BAD_INPUT_DATA; - - ctx->md_info->update_func( ctx->md_ctx, input, ilen ); - - return 0; -} - -int md_finish( md_context_t *ctx, unsigned char *output ) -{ - if( ctx == NULL || ctx->md_info == NULL ) - return POLARSSL_ERR_MD_BAD_INPUT_DATA; - - ctx->md_info->finish_func( ctx->md_ctx, output ); - - return 0; -} - -int md( const md_info_t *md_info, const unsigned char *input, size_t ilen, - unsigned char *output ) -{ - if ( md_info == NULL ) - return POLARSSL_ERR_MD_BAD_INPUT_DATA; - - md_info->digest_func( input, ilen, output ); - - return 0; -} - -int md_file( const md_info_t *md_info, const char *path, unsigned char *output ) -{ -#if defined(POLARSSL_FS_IO) - int ret; -#endif - - if( md_info == NULL ) - return POLARSSL_ERR_MD_BAD_INPUT_DATA; - -#if defined(POLARSSL_FS_IO) - ret = md_info->file_func( path, output ); - if( ret != 0 ) - return( POLARSSL_ERR_MD_FILE_IO_ERROR + ret ); - - return( ret ); -#else - ((void) path); - ((void) output); - - return POLARSSL_ERR_MD_FEATURE_UNAVAILABLE; -#endif -} - -int md_hmac_starts( md_context_t *ctx, const unsigned char *key, size_t keylen ) -{ - if( ctx == NULL || ctx->md_info == NULL ) - return POLARSSL_ERR_MD_BAD_INPUT_DATA; - - ctx->md_info->hmac_starts_func( ctx->md_ctx, key, keylen); - - return 0; -} - -int md_hmac_update( md_context_t *ctx, const unsigned char *input, size_t ilen ) -{ - if( ctx == NULL || ctx->md_info == NULL ) - return POLARSSL_ERR_MD_BAD_INPUT_DATA; - - ctx->md_info->hmac_update_func( ctx->md_ctx, input, ilen ); - - return 0; -} - -int md_hmac_finish( md_context_t *ctx, unsigned char *output) -{ - if( ctx == NULL || ctx->md_info == NULL ) - return POLARSSL_ERR_MD_BAD_INPUT_DATA; - - ctx->md_info->hmac_finish_func( ctx->md_ctx, output); - - return 0; -} - -int md_hmac_reset( md_context_t *ctx ) -{ - if( ctx == NULL || ctx->md_info == NULL ) - return POLARSSL_ERR_MD_BAD_INPUT_DATA; - - ctx->md_info->hmac_reset_func( ctx->md_ctx); - - return 0; -} - -int md_hmac( const md_info_t *md_info, const unsigned char *key, size_t keylen, - const unsigned char *input, size_t ilen, - unsigned char *output ) -{ - if( md_info == NULL ) - return POLARSSL_ERR_MD_BAD_INPUT_DATA; - - md_info->hmac_func( key, keylen, input, ilen, output ); - - return 0; -} - -#endif diff --git a/lib/libpolarssl/source/md_wrap.c b/lib/libpolarssl/source/md_wrap.c deleted file mode 100644 index a612d02..0000000 --- a/lib/libpolarssl/source/md_wrap.c +++ /dev/null @@ -1,743 +0,0 @@ -/** - * \file md_wrap.c - - * \brief Generic message digest wrapper for PolarSSL - * - * \author Adriaan de Jong - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved - * - * This file is part of mbed TLS (https://polarssl.org) - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ - -#include "polarssl/config.h" - -#if defined(POLARSSL_MD_C) - -#include "polarssl/md_wrap.h" - -#if defined(POLARSSL_MD2_C) -#include "polarssl/md2.h" -#endif - -#if defined(POLARSSL_MD4_C) -#include "polarssl/md4.h" -#endif - -#if defined(POLARSSL_MD5_C) -#include "polarssl/md5.h" -#endif - -#if defined(POLARSSL_SHA1_C) -#include "polarssl/sha1.h" -#endif - -#if defined(POLARSSL_SHA2_C) -#include "polarssl/sha2.h" -#endif - -#if defined(POLARSSL_SHA4_C) -#include "polarssl/sha4.h" -#endif - -#include - -/* Implementation that should never be optimized out by the compiler */ -static void polarssl_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - -#if defined(POLARSSL_MD2_C) - -static void md2_starts_wrap( void *ctx ) -{ - md2_starts( (md2_context *) ctx ); -} - -static void md2_update_wrap( void *ctx, const unsigned char *input, size_t ilen ) -{ - md2_update( (md2_context *) ctx, input, ilen ); -} - -static void md2_finish_wrap( void *ctx, unsigned char *output ) -{ - md2_finish( (md2_context *) ctx, output ); -} - -static int md2_file_wrap( const char *path, unsigned char *output ) -{ -#if defined(POLARSSL_FS_IO) - return md2_file( path, output ); -#else - ((void) path); - ((void) output); - return POLARSSL_ERR_MD_FEATURE_UNAVAILABLE; -#endif -} - -static void md2_hmac_starts_wrap( void *ctx, const unsigned char *key, size_t keylen ) -{ - md2_hmac_starts( (md2_context *) ctx, key, keylen ); -} - -static void md2_hmac_update_wrap( void *ctx, const unsigned char *input, size_t ilen ) -{ - md2_hmac_update( (md2_context *) ctx, input, ilen ); -} - -static void md2_hmac_finish_wrap( void *ctx, unsigned char *output ) -{ - md2_hmac_finish( (md2_context *) ctx, output ); -} - -static void md2_hmac_reset_wrap( void *ctx ) -{ - md2_hmac_reset( (md2_context *) ctx ); -} - -static void * md2_ctx_alloc( void ) -{ - return malloc( sizeof( md2_context ) ); -} - -static void md2_ctx_free( void *ctx ) -{ - polarssl_zeroize( ctx, sizeof( md2_context ) ); - free( ctx ); -} - -const md_info_t md2_info = { - POLARSSL_MD_MD2, - "MD2", - 16, - md2_starts_wrap, - md2_update_wrap, - md2_finish_wrap, - md2, - md2_file_wrap, - md2_hmac_starts_wrap, - md2_hmac_update_wrap, - md2_hmac_finish_wrap, - md2_hmac_reset_wrap, - md2_hmac, - md2_ctx_alloc, - md2_ctx_free, -}; - -#endif - -#if defined(POLARSSL_MD4_C) - -static void md4_starts_wrap( void *ctx ) -{ - md4_starts( (md4_context *) ctx ); -} - -static void md4_update_wrap( void *ctx, const unsigned char *input, size_t ilen ) -{ - md4_update( (md4_context *) ctx, input, ilen ); -} - -static void md4_finish_wrap( void *ctx, unsigned char *output ) -{ - md4_finish( (md4_context *) ctx, output ); -} - -static int md4_file_wrap( const char *path, unsigned char *output ) -{ -#if defined(POLARSSL_FS_IO) - return md4_file( path, output ); -#else - ((void) path); - ((void) output); - return POLARSSL_ERR_MD_FEATURE_UNAVAILABLE; -#endif -} - -static void md4_hmac_starts_wrap( void *ctx, const unsigned char *key, size_t keylen ) -{ - md4_hmac_starts( (md4_context *) ctx, key, keylen ); -} - -static void md4_hmac_update_wrap( void *ctx, const unsigned char *input, size_t ilen ) -{ - md4_hmac_update( (md4_context *) ctx, input, ilen ); -} - -static void md4_hmac_finish_wrap( void *ctx, unsigned char *output ) -{ - md4_hmac_finish( (md4_context *) ctx, output ); -} - -static void md4_hmac_reset_wrap( void *ctx ) -{ - md4_hmac_reset( (md4_context *) ctx ); -} - -static void *md4_ctx_alloc( void ) -{ - return malloc( sizeof( md4_context ) ); -} - -static void md4_ctx_free( void *ctx ) -{ - polarssl_zeroize( ctx, sizeof( md4_context ) ); - free( ctx ); -} - -const md_info_t md4_info = { - POLARSSL_MD_MD4, - "MD4", - 16, - md4_starts_wrap, - md4_update_wrap, - md4_finish_wrap, - md4, - md4_file_wrap, - md4_hmac_starts_wrap, - md4_hmac_update_wrap, - md4_hmac_finish_wrap, - md4_hmac_reset_wrap, - md4_hmac, - md4_ctx_alloc, - md4_ctx_free, -}; - -#endif - -#if defined(POLARSSL_MD5_C) - -static void md5_starts_wrap( void *ctx ) -{ - md5_starts( (md5_context *) ctx ); -} - -static void md5_update_wrap( void *ctx, const unsigned char *input, size_t ilen ) -{ - md5_update( (md5_context *) ctx, input, ilen ); -} - -static void md5_finish_wrap( void *ctx, unsigned char *output ) -{ - md5_finish( (md5_context *) ctx, output ); -} - -static int md5_file_wrap( const char *path, unsigned char *output ) -{ -#if defined(POLARSSL_FS_IO) - return md5_file( path, output ); -#else - ((void) path); - ((void) output); - return POLARSSL_ERR_MD_FEATURE_UNAVAILABLE; -#endif -} - -static void md5_hmac_starts_wrap( void *ctx, const unsigned char *key, size_t keylen ) -{ - md5_hmac_starts( (md5_context *) ctx, key, keylen ); -} - -static void md5_hmac_update_wrap( void *ctx, const unsigned char *input, size_t ilen ) -{ - md5_hmac_update( (md5_context *) ctx, input, ilen ); -} - -static void md5_hmac_finish_wrap( void *ctx, unsigned char *output ) -{ - md5_hmac_finish( (md5_context *) ctx, output ); -} - -static void md5_hmac_reset_wrap( void *ctx ) -{ - md5_hmac_reset( (md5_context *) ctx ); -} - -static void * md5_ctx_alloc( void ) -{ - return malloc( sizeof( md5_context ) ); -} - -static void md5_ctx_free( void *ctx ) -{ - polarssl_zeroize( ctx, sizeof( md5_context ) ); - free( ctx ); -} - -const md_info_t md5_info = { - POLARSSL_MD_MD5, - "MD5", - 16, - md5_starts_wrap, - md5_update_wrap, - md5_finish_wrap, - md5, - md5_file_wrap, - md5_hmac_starts_wrap, - md5_hmac_update_wrap, - md5_hmac_finish_wrap, - md5_hmac_reset_wrap, - md5_hmac, - md5_ctx_alloc, - md5_ctx_free, -}; - -#endif - -#if defined(POLARSSL_SHA1_C) - -static void sha1_starts_wrap( void *ctx ) -{ - sha1_starts( (sha1_context *) ctx ); -} - -static void sha1_update_wrap( void *ctx, const unsigned char *input, size_t ilen ) -{ - sha1_update( (sha1_context *) ctx, input, ilen ); -} - -static void sha1_finish_wrap( void *ctx, unsigned char *output ) -{ - sha1_finish( (sha1_context *) ctx, output ); -} - -static int sha1_file_wrap( const char *path, unsigned char *output ) -{ -#if defined(POLARSSL_FS_IO) - return sha1_file( path, output ); -#else - ((void) path); - ((void) output); - return POLARSSL_ERR_MD_FEATURE_UNAVAILABLE; -#endif -} - -static void sha1_hmac_starts_wrap( void *ctx, const unsigned char *key, size_t keylen ) -{ - sha1_hmac_starts( (sha1_context *) ctx, key, keylen ); -} - -static void sha1_hmac_update_wrap( void *ctx, const unsigned char *input, size_t ilen ) -{ - sha1_hmac_update( (sha1_context *) ctx, input, ilen ); -} - -static void sha1_hmac_finish_wrap( void *ctx, unsigned char *output ) -{ - sha1_hmac_finish( (sha1_context *) ctx, output ); -} - -static void sha1_hmac_reset_wrap( void *ctx ) -{ - sha1_hmac_reset( (sha1_context *) ctx ); -} - -static void * sha1_ctx_alloc( void ) -{ - return malloc( sizeof( sha1_context ) ); -} - -static void sha1_ctx_free( void *ctx ) -{ - polarssl_zeroize( ctx, sizeof( sha1_context ) ); - free( ctx ); -} - -const md_info_t sha1_info = { - POLARSSL_MD_SHA1, - "SHA1", - 20, - sha1_starts_wrap, - sha1_update_wrap, - sha1_finish_wrap, - sha1, - sha1_file_wrap, - sha1_hmac_starts_wrap, - sha1_hmac_update_wrap, - sha1_hmac_finish_wrap, - sha1_hmac_reset_wrap, - sha1_hmac, - sha1_ctx_alloc, - sha1_ctx_free, -}; - -#endif - -/* - * Wrappers for generic message digests - */ -#if defined(POLARSSL_SHA2_C) - -static void sha224_starts_wrap( void *ctx ) -{ - sha2_starts( (sha2_context *) ctx, 1 ); -} - -static void sha224_update_wrap( void *ctx, const unsigned char *input, size_t ilen ) -{ - sha2_update( (sha2_context *) ctx, input, ilen ); -} - -static void sha224_finish_wrap( void *ctx, unsigned char *output ) -{ - sha2_finish( (sha2_context *) ctx, output ); -} - -static void sha224_wrap( const unsigned char *input, size_t ilen, - unsigned char *output ) -{ - sha2( input, ilen, output, 1 ); -} - -static int sha224_file_wrap( const char *path, unsigned char *output ) -{ -#if defined(POLARSSL_FS_IO) - return sha2_file( path, output, 1 ); -#else - ((void) path); - ((void) output); - return POLARSSL_ERR_MD_FEATURE_UNAVAILABLE; -#endif -} - -static void sha224_hmac_starts_wrap( void *ctx, const unsigned char *key, size_t keylen ) -{ - sha2_hmac_starts( (sha2_context *) ctx, key, keylen, 1 ); -} - -static void sha224_hmac_update_wrap( void *ctx, const unsigned char *input, size_t ilen ) -{ - sha2_hmac_update( (sha2_context *) ctx, input, ilen ); -} - -static void sha224_hmac_finish_wrap( void *ctx, unsigned char *output ) -{ - sha2_hmac_finish( (sha2_context *) ctx, output ); -} - -static void sha224_hmac_reset_wrap( void *ctx ) -{ - sha2_hmac_reset( (sha2_context *) ctx ); -} - -static void sha224_hmac_wrap( const unsigned char *key, size_t keylen, - const unsigned char *input, size_t ilen, - unsigned char *output ) -{ - sha2_hmac( key, keylen, input, ilen, output, 1 ); -} - -static void * sha224_ctx_alloc( void ) -{ - return malloc( sizeof( sha2_context ) ); -} - -static void sha224_ctx_free( void *ctx ) -{ - polarssl_zeroize( ctx, sizeof( sha2_context ) ); - free( ctx ); -} - -const md_info_t sha224_info = { - POLARSSL_MD_SHA224, - "SHA224", - 28, - sha224_starts_wrap, - sha224_update_wrap, - sha224_finish_wrap, - sha224_wrap, - sha224_file_wrap, - sha224_hmac_starts_wrap, - sha224_hmac_update_wrap, - sha224_hmac_finish_wrap, - sha224_hmac_reset_wrap, - sha224_hmac_wrap, - sha224_ctx_alloc, - sha224_ctx_free, -}; - -static void sha256_starts_wrap( void *ctx ) -{ - sha2_starts( (sha2_context *) ctx, 0 ); -} - -static void sha256_update_wrap( void *ctx, const unsigned char *input, size_t ilen ) -{ - sha2_update( (sha2_context *) ctx, input, ilen ); -} - -static void sha256_finish_wrap( void *ctx, unsigned char *output ) -{ - sha2_finish( (sha2_context *) ctx, output ); -} - -static void sha256_wrap( const unsigned char *input, size_t ilen, - unsigned char *output ) -{ - sha2( input, ilen, output, 0 ); -} - -static int sha256_file_wrap( const char *path, unsigned char *output ) -{ -#if defined(POLARSSL_FS_IO) - return sha2_file( path, output, 0 ); -#else - ((void) path); - ((void) output); - return POLARSSL_ERR_MD_FEATURE_UNAVAILABLE; -#endif -} - -static void sha256_hmac_starts_wrap( void *ctx, const unsigned char *key, size_t keylen ) -{ - sha2_hmac_starts( (sha2_context *) ctx, key, keylen, 0 ); -} - -static void sha256_hmac_update_wrap( void *ctx, const unsigned char *input, size_t ilen ) -{ - sha2_hmac_update( (sha2_context *) ctx, input, ilen ); -} - -static void sha256_hmac_finish_wrap( void *ctx, unsigned char *output ) -{ - sha2_hmac_finish( (sha2_context *) ctx, output ); -} - -static void sha256_hmac_reset_wrap( void *ctx ) -{ - sha2_hmac_reset( (sha2_context *) ctx ); -} - -static void sha256_hmac_wrap( const unsigned char *key, size_t keylen, - const unsigned char *input, size_t ilen, - unsigned char *output ) -{ - sha2_hmac( key, keylen, input, ilen, output, 0 ); -} - -static void * sha256_ctx_alloc( void ) -{ - return malloc( sizeof( sha2_context ) ); -} - -static void sha256_ctx_free( void *ctx ) -{ - polarssl_zeroize( ctx, sizeof( sha2_context ) ); - free( ctx ); -} - -const md_info_t sha256_info = { - POLARSSL_MD_SHA256, - "SHA256", - 32, - sha256_starts_wrap, - sha256_update_wrap, - sha256_finish_wrap, - sha256_wrap, - sha256_file_wrap, - sha256_hmac_starts_wrap, - sha256_hmac_update_wrap, - sha256_hmac_finish_wrap, - sha256_hmac_reset_wrap, - sha256_hmac_wrap, - sha256_ctx_alloc, - sha256_ctx_free, -}; - -#endif - -#if defined(POLARSSL_SHA4_C) - -static void sha384_starts_wrap( void *ctx ) -{ - sha4_starts( (sha4_context *) ctx, 1 ); -} - -static void sha384_update_wrap( void *ctx, const unsigned char *input, size_t ilen ) -{ - sha4_update( (sha4_context *) ctx, input, ilen ); -} - -static void sha384_finish_wrap( void *ctx, unsigned char *output ) -{ - sha4_finish( (sha4_context *) ctx, output ); -} - -static void sha384_wrap( const unsigned char *input, size_t ilen, - unsigned char *output ) -{ - sha4( input, ilen, output, 1 ); -} - -static int sha384_file_wrap( const char *path, unsigned char *output ) -{ -#if defined(POLARSSL_FS_IO) - return sha4_file( path, output, 1 ); -#else - ((void) path); - ((void) output); - return POLARSSL_ERR_MD_FEATURE_UNAVAILABLE; -#endif -} - -static void sha384_hmac_starts_wrap( void *ctx, const unsigned char *key, size_t keylen ) -{ - sha4_hmac_starts( (sha4_context *) ctx, key, keylen, 1 ); -} - -static void sha384_hmac_update_wrap( void *ctx, const unsigned char *input, size_t ilen ) -{ - sha4_hmac_update( (sha4_context *) ctx, input, ilen ); -} - -static void sha384_hmac_finish_wrap( void *ctx, unsigned char *output ) -{ - sha4_hmac_finish( (sha4_context *) ctx, output ); -} - -static void sha384_hmac_reset_wrap( void *ctx ) -{ - sha4_hmac_reset( (sha4_context *) ctx ); -} - -static void sha384_hmac_wrap( const unsigned char *key, size_t keylen, - const unsigned char *input, size_t ilen, - unsigned char *output ) -{ - sha4_hmac( key, keylen, input, ilen, output, 1 ); -} - -static void * sha384_ctx_alloc( void ) -{ - return malloc( sizeof( sha4_context ) ); -} - -static void sha384_ctx_free( void *ctx ) -{ - polarssl_zeroize( ctx, sizeof( sha4_context ) ); - free( ctx ); -} - -const md_info_t sha384_info = { - POLARSSL_MD_SHA384, - "SHA384", - 48, - sha384_starts_wrap, - sha384_update_wrap, - sha384_finish_wrap, - sha384_wrap, - sha384_file_wrap, - sha384_hmac_starts_wrap, - sha384_hmac_update_wrap, - sha384_hmac_finish_wrap, - sha384_hmac_reset_wrap, - sha384_hmac_wrap, - sha384_ctx_alloc, - sha384_ctx_free, -}; - -static void sha512_starts_wrap( void *ctx ) -{ - sha4_starts( (sha4_context *) ctx, 0 ); -} - -static void sha512_update_wrap( void *ctx, const unsigned char *input, size_t ilen ) -{ - sha4_update( (sha4_context *) ctx, input, ilen ); -} - -static void sha512_finish_wrap( void *ctx, unsigned char *output ) -{ - sha4_finish( (sha4_context *) ctx, output ); -} - -static void sha512_wrap( const unsigned char *input, size_t ilen, - unsigned char *output ) -{ - sha4( input, ilen, output, 0 ); -} - -static int sha512_file_wrap( const char *path, unsigned char *output ) -{ -#if defined(POLARSSL_FS_IO) - return sha4_file( path, output, 0 ); -#else - ((void) path); - ((void) output); - return POLARSSL_ERR_MD_FEATURE_UNAVAILABLE; -#endif -} - -static void sha512_hmac_starts_wrap( void *ctx, const unsigned char *key, size_t keylen ) -{ - sha4_hmac_starts( (sha4_context *) ctx, key, keylen, 0 ); -} - -static void sha512_hmac_update_wrap( void *ctx, const unsigned char *input, size_t ilen ) -{ - sha4_hmac_update( (sha4_context *) ctx, input, ilen ); -} - -static void sha512_hmac_finish_wrap( void *ctx, unsigned char *output ) -{ - sha4_hmac_finish( (sha4_context *) ctx, output ); -} - -static void sha512_hmac_reset_wrap( void *ctx ) -{ - sha4_hmac_reset( (sha4_context *) ctx ); -} - -static void sha512_hmac_wrap( const unsigned char *key, size_t keylen, - const unsigned char *input, size_t ilen, - unsigned char *output ) -{ - sha4_hmac( key, keylen, input, ilen, output, 0 ); -} - -static void * sha512_ctx_alloc( void ) -{ - return malloc( sizeof( sha4_context ) ); -} - -static void sha512_ctx_free( void *ctx ) -{ - polarssl_zeroize( ctx, sizeof( sha4_context ) ); - free( ctx ); -} - -const md_info_t sha512_info = { - POLARSSL_MD_SHA512, - "SHA512", - 64, - sha512_starts_wrap, - sha512_update_wrap, - sha512_finish_wrap, - sha512_wrap, - sha512_file_wrap, - sha512_hmac_starts_wrap, - sha512_hmac_update_wrap, - sha512_hmac_finish_wrap, - sha512_hmac_reset_wrap, - sha512_hmac_wrap, - sha512_ctx_alloc, - sha512_ctx_free, -}; - -#endif - -#endif diff --git a/lib/libpolarssl/source/rsa.c b/lib/libpolarssl/source/rsa.c deleted file mode 100644 index a877233..0000000 --- a/lib/libpolarssl/source/rsa.c +++ /dev/null @@ -1,1466 +0,0 @@ -/* - * The RSA public-key cryptosystem - * - * Copyright (C) 2006-2011, Brainspark B.V. - * - * This file is part of PolarSSL (http://www.polarssl.org) - * Lead Maintainer: Paul Bakker - * - * All rights reserved. - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ -/* - * RSA was designed by Ron Rivest, Adi Shamir and Len Adleman. - * - * http://theory.lcs.mit.edu/~rivest/rsapaper.pdf - * http://www.cacr.math.uwaterloo.ca/hac/about/chap8.pdf - */ - -#include - -#if defined(POLARSSL_RSA_C) - -#include - -#if defined(POLARSSL_PKCS1_V21) -#include -#endif - -#include -#include - -/* - * Initialize an RSA context - */ -void rsa_init( rsa_context *ctx, - int padding, - int hash_id ) -{ - memset( ctx, 0, sizeof( rsa_context ) ); - - ctx->padding = padding; - ctx->hash_id = hash_id; -} - -#if defined(POLARSSL_GENPRIME) - -/* - * Generate an RSA keypair - */ -int rsa_gen_key( rsa_context *ctx, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng, - unsigned int nbits, int exponent ) -{ - int ret; - mpi P1, Q1, H, G; - - if( f_rng == NULL || nbits < 128 || exponent < 3 ) - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - - mpi_init( &P1 ); mpi_init( &Q1 ); mpi_init( &H ); mpi_init( &G ); - - /* - * find primes P and Q with Q < P so that: - * GCD( E, (P-1)*(Q-1) ) == 1 - */ - MPI_CHK( mpi_lset( &ctx->E, exponent ) ); - - do - { - MPI_CHK( mpi_gen_prime( &ctx->P, ( nbits + 1 ) >> 1, 0, - f_rng, p_rng ) ); - - MPI_CHK( mpi_gen_prime( &ctx->Q, ( nbits + 1 ) >> 1, 0, - f_rng, p_rng ) ); - - if( mpi_cmp_mpi( &ctx->P, &ctx->Q ) < 0 ) - mpi_swap( &ctx->P, &ctx->Q ); - - if( mpi_cmp_mpi( &ctx->P, &ctx->Q ) == 0 ) - continue; - - MPI_CHK( mpi_mul_mpi( &ctx->N, &ctx->P, &ctx->Q ) ); - if( mpi_msb( &ctx->N ) != nbits ) - continue; - - MPI_CHK( mpi_sub_int( &P1, &ctx->P, 1 ) ); - MPI_CHK( mpi_sub_int( &Q1, &ctx->Q, 1 ) ); - MPI_CHK( mpi_mul_mpi( &H, &P1, &Q1 ) ); - MPI_CHK( mpi_gcd( &G, &ctx->E, &H ) ); - } - while( mpi_cmp_int( &G, 1 ) != 0 ); - - /* - * D = E^-1 mod ((P-1)*(Q-1)) - * DP = D mod (P - 1) - * DQ = D mod (Q - 1) - * QP = Q^-1 mod P - */ - MPI_CHK( mpi_inv_mod( &ctx->D , &ctx->E, &H ) ); - MPI_CHK( mpi_mod_mpi( &ctx->DP, &ctx->D, &P1 ) ); - MPI_CHK( mpi_mod_mpi( &ctx->DQ, &ctx->D, &Q1 ) ); - MPI_CHK( mpi_inv_mod( &ctx->QP, &ctx->Q, &ctx->P ) ); - - ctx->len = ( mpi_msb( &ctx->N ) + 7 ) >> 3; - -cleanup: - - mpi_free( &P1 ); mpi_free( &Q1 ); mpi_free( &H ); mpi_free( &G ); - - if( ret != 0 ) - { - rsa_free( ctx ); - return( POLARSSL_ERR_RSA_KEY_GEN_FAILED + ret ); - } - - return( 0 ); -} - -#endif - -/* - * Check a public RSA key - */ -int rsa_check_pubkey( const rsa_context *ctx ) -{ - if( !ctx->N.p || !ctx->E.p ) - return( POLARSSL_ERR_RSA_KEY_CHECK_FAILED ); - - if( ( ctx->N.p[0] & 1 ) == 0 || - ( ctx->E.p[0] & 1 ) == 0 ) - return( POLARSSL_ERR_RSA_KEY_CHECK_FAILED ); - - if( mpi_msb( &ctx->N ) < 128 || - mpi_msb( &ctx->N ) > POLARSSL_MPI_MAX_BITS ) - return( POLARSSL_ERR_RSA_KEY_CHECK_FAILED ); - - if( mpi_msb( &ctx->E ) < 2 || - mpi_msb( &ctx->E ) > 64 ) - return( POLARSSL_ERR_RSA_KEY_CHECK_FAILED ); - - return( 0 ); -} - -/* - * Check a private RSA key - */ -int rsa_check_privkey( const rsa_context *ctx ) -{ - int ret; - mpi PQ, DE, P1, Q1, H, I, G, G2, L1, L2, DP, DQ, QP; - - if( ( ret = rsa_check_pubkey( ctx ) ) != 0 ) - return( ret ); - - if( !ctx->P.p || !ctx->Q.p || !ctx->D.p ) - return( POLARSSL_ERR_RSA_KEY_CHECK_FAILED ); - - mpi_init( &PQ ); mpi_init( &DE ); mpi_init( &P1 ); mpi_init( &Q1 ); - mpi_init( &H ); mpi_init( &I ); mpi_init( &G ); mpi_init( &G2 ); - mpi_init( &L1 ); mpi_init( &L2 ); mpi_init( &DP ); mpi_init( &DQ ); - mpi_init( &QP ); - - MPI_CHK( mpi_mul_mpi( &PQ, &ctx->P, &ctx->Q ) ); - MPI_CHK( mpi_mul_mpi( &DE, &ctx->D, &ctx->E ) ); - MPI_CHK( mpi_sub_int( &P1, &ctx->P, 1 ) ); - MPI_CHK( mpi_sub_int( &Q1, &ctx->Q, 1 ) ); - MPI_CHK( mpi_mul_mpi( &H, &P1, &Q1 ) ); - MPI_CHK( mpi_gcd( &G, &ctx->E, &H ) ); - - MPI_CHK( mpi_gcd( &G2, &P1, &Q1 ) ); - MPI_CHK( mpi_div_mpi( &L1, &L2, &H, &G2 ) ); - MPI_CHK( mpi_mod_mpi( &I, &DE, &L1 ) ); - - MPI_CHK( mpi_mod_mpi( &DP, &ctx->D, &P1 ) ); - MPI_CHK( mpi_mod_mpi( &DQ, &ctx->D, &Q1 ) ); - MPI_CHK( mpi_inv_mod( &QP, &ctx->Q, &ctx->P ) ); - /* - * Check for a valid PKCS1v2 private key - */ - if( mpi_cmp_mpi( &PQ, &ctx->N ) != 0 || - mpi_cmp_mpi( &DP, &ctx->DP ) != 0 || - mpi_cmp_mpi( &DQ, &ctx->DQ ) != 0 || - mpi_cmp_mpi( &QP, &ctx->QP ) != 0 || - mpi_cmp_int( &L2, 0 ) != 0 || - mpi_cmp_int( &I, 1 ) != 0 || - mpi_cmp_int( &G, 1 ) != 0 ) - { - ret = POLARSSL_ERR_RSA_KEY_CHECK_FAILED; - } - -cleanup: - mpi_free( &PQ ); mpi_free( &DE ); mpi_free( &P1 ); mpi_free( &Q1 ); - mpi_free( &H ); mpi_free( &I ); mpi_free( &G ); mpi_free( &G2 ); - mpi_free( &L1 ); mpi_free( &L2 ); mpi_free( &DP ); mpi_free( &DQ ); - mpi_free( &QP ); - - if( ret == POLARSSL_ERR_RSA_KEY_CHECK_FAILED ) - return( ret ); - - if( ret != 0 ) - return( POLARSSL_ERR_RSA_KEY_CHECK_FAILED + ret ); - - return( 0 ); -} - -/* - * Do an RSA public key operation - */ -int rsa_public( rsa_context *ctx, - const unsigned char *input, - unsigned char *output ) -{ - int ret; - size_t olen; - mpi T; - - mpi_init( &T ); - - MPI_CHK( mpi_read_binary( &T, input, ctx->len ) ); - - if( mpi_cmp_mpi( &T, &ctx->N ) >= 0 ) - { - mpi_free( &T ); - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - } - - olen = ctx->len; - MPI_CHK( mpi_exp_mod( &T, &T, &ctx->E, &ctx->N, &ctx->RN ) ); - MPI_CHK( mpi_write_binary( &T, output, olen ) ); - -cleanup: - - mpi_free( &T ); - - if( ret != 0 ) - return( POLARSSL_ERR_RSA_PUBLIC_FAILED + ret ); - - return( 0 ); -} - -/* - * Do an RSA private key operation - */ -int rsa_private( rsa_context *ctx, - const unsigned char *input, - unsigned char *output ) -{ - int ret; - size_t olen; - mpi T, T1, T2; - - mpi_init( &T ); mpi_init( &T1 ); mpi_init( &T2 ); - - MPI_CHK( mpi_read_binary( &T, input, ctx->len ) ); - - if( mpi_cmp_mpi( &T, &ctx->N ) >= 0 ) - { - mpi_free( &T ); - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - } - -#if defined(POLARSSL_RSA_NO_CRT) - MPI_CHK( mpi_exp_mod( &T, &T, &ctx->D, &ctx->N, &ctx->RN ) ); -#else - /* - * faster decryption using the CRT - * - * T1 = input ^ dP mod P - * T2 = input ^ dQ mod Q - */ - MPI_CHK( mpi_exp_mod( &T1, &T, &ctx->DP, &ctx->P, &ctx->RP ) ); - MPI_CHK( mpi_exp_mod( &T2, &T, &ctx->DQ, &ctx->Q, &ctx->RQ ) ); - - /* - * T = (T1 - T2) * (Q^-1 mod P) mod P - */ - MPI_CHK( mpi_sub_mpi( &T, &T1, &T2 ) ); - MPI_CHK( mpi_mul_mpi( &T1, &T, &ctx->QP ) ); - MPI_CHK( mpi_mod_mpi( &T, &T1, &ctx->P ) ); - - /* - * output = T2 + T * Q - */ - MPI_CHK( mpi_mul_mpi( &T1, &T, &ctx->Q ) ); - MPI_CHK( mpi_add_mpi( &T, &T2, &T1 ) ); -#endif - - olen = ctx->len; - MPI_CHK( mpi_write_binary( &T, output, olen ) ); - -cleanup: - - mpi_free( &T ); mpi_free( &T1 ); mpi_free( &T2 ); - - if( ret != 0 ) - return( POLARSSL_ERR_RSA_PRIVATE_FAILED + ret ); - - return( 0 ); -} - -#if defined(POLARSSL_PKCS1_V21) -/** - * Generate and apply the MGF1 operation (from PKCS#1 v2.1) to a buffer. - * - * \param dst buffer to mask - * \param dlen length of destination buffer - * \param src source of the mask generation - * \param slen length of the source buffer - * \param md_ctx message digest context to use - */ -static void mgf_mask( unsigned char *dst, size_t dlen, unsigned char *src, size_t slen, - md_context_t *md_ctx ) -{ - unsigned char mask[POLARSSL_MD_MAX_SIZE]; - unsigned char counter[4]; - unsigned char *p; - unsigned int hlen; - size_t i, use_len; - - memset( mask, 0, POLARSSL_MD_MAX_SIZE ); - memset( counter, 0, 4 ); - - hlen = md_ctx->md_info->size; - - // Generate and apply dbMask - // - p = dst; - - while( dlen > 0 ) - { - use_len = hlen; - if( dlen < hlen ) - use_len = dlen; - - md_starts( md_ctx ); - md_update( md_ctx, src, slen ); - md_update( md_ctx, counter, 4 ); - md_finish( md_ctx, mask ); - - for( i = 0; i < use_len; ++i ) - *p++ ^= mask[i]; - - counter[3]++; - - dlen -= use_len; - } -} -#endif - -#if defined(POLARSSL_PKCS1_V21) -/* - * Implementation of the PKCS#1 v2.1 RSAES-OAEP-ENCRYPT function - */ -int rsa_rsaes_oaep_encrypt( rsa_context *ctx, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng, - int mode, - const unsigned char *label, size_t label_len, - size_t ilen, - const unsigned char *input, - unsigned char *output ) -{ - size_t olen; - int ret; - unsigned char *p = output; - unsigned int hlen; - const md_info_t *md_info; - md_context_t md_ctx; - - if( ctx->padding != RSA_PKCS_V21 || f_rng == NULL ) - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - - md_info = md_info_from_type( ctx->hash_id ); - - if( md_info == NULL ) - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - - olen = ctx->len; - hlen = md_get_size( md_info ); - - if( olen < ilen + 2 * hlen + 2 || f_rng == NULL ) - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - - memset( output, 0, olen ); - - *p++ = 0; - - // Generate a random octet string seed - // - if( ( ret = f_rng( p_rng, p, hlen ) ) != 0 ) - return( POLARSSL_ERR_RSA_RNG_FAILED + ret ); - - p += hlen; - - // Construct DB - // - md( md_info, label, label_len, p ); - p += hlen; - p += olen - 2 * hlen - 2 - ilen; - *p++ = 1; - memcpy( p, input, ilen ); - - md_init_ctx( &md_ctx, md_info ); - - // maskedDB: Apply dbMask to DB - // - mgf_mask( output + hlen + 1, olen - hlen - 1, output + 1, hlen, - &md_ctx ); - - // maskedSeed: Apply seedMask to seed - // - mgf_mask( output + 1, hlen, output + hlen + 1, olen - hlen - 1, - &md_ctx ); - - md_free_ctx( &md_ctx ); - - return( ( mode == RSA_PUBLIC ) - ? rsa_public( ctx, output, output ) - : rsa_private( ctx, output, output ) ); -} -#endif /* POLARSSL_PKCS1_V21 */ - -/* - * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-ENCRYPT function - */ -int rsa_rsaes_pkcs1_v15_encrypt( rsa_context *ctx, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng, - int mode, size_t ilen, - const unsigned char *input, - unsigned char *output ) -{ - size_t nb_pad, olen; - int ret; - unsigned char *p = output; - - if( ctx->padding != RSA_PKCS_V15 || f_rng == NULL ) - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - - olen = ctx->len; - - if( olen < ilen + 11 ) - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - - nb_pad = olen - 3 - ilen; - - *p++ = 0; - if( mode == RSA_PUBLIC ) - { - *p++ = RSA_CRYPT; - - while( nb_pad-- > 0 ) - { - int rng_dl = 100; - - do { - ret = f_rng( p_rng, p, 1 ); - } while( *p == 0 && --rng_dl && ret == 0 ); - - // Check if RNG failed to generate data - // - if( rng_dl == 0 || ret != 0) - return POLARSSL_ERR_RSA_RNG_FAILED + ret; - - p++; - } - } - else - { - *p++ = RSA_SIGN; - - while( nb_pad-- > 0 ) - *p++ = 0xFF; - } - - *p++ = 0; - memcpy( p, input, ilen ); - - return( ( mode == RSA_PUBLIC ) - ? rsa_public( ctx, output, output ) - : rsa_private( ctx, output, output ) ); -} - -/* - * Add the message padding, then do an RSA operation - */ -int rsa_pkcs1_encrypt( rsa_context *ctx, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng, - int mode, size_t ilen, - const unsigned char *input, - unsigned char *output ) -{ - switch( ctx->padding ) - { - case RSA_PKCS_V15: - return rsa_rsaes_pkcs1_v15_encrypt( ctx, f_rng, p_rng, mode, ilen, - input, output ); - -#if defined(POLARSSL_PKCS1_V21) - case RSA_PKCS_V21: - return rsa_rsaes_oaep_encrypt( ctx, f_rng, p_rng, mode, NULL, 0, - ilen, input, output ); -#endif - - default: - return( POLARSSL_ERR_RSA_INVALID_PADDING ); - } -} - -#if defined(POLARSSL_PKCS1_V21) -/* - * Implementation of the PKCS#1 v2.1 RSAES-OAEP-DECRYPT function - */ -int rsa_rsaes_oaep_decrypt( rsa_context *ctx, - int mode, - const unsigned char *label, size_t label_len, - size_t *olen, - const unsigned char *input, - unsigned char *output, - size_t output_max_len ) -{ - int ret; - size_t ilen; - unsigned char *p; - unsigned char buf[POLARSSL_MPI_MAX_SIZE]; - unsigned char lhash[POLARSSL_MD_MAX_SIZE]; - unsigned int hlen; - const md_info_t *md_info; - md_context_t md_ctx; - - if( ctx->padding != RSA_PKCS_V21 ) - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - - ilen = ctx->len; - - if( ilen < 16 || ilen > sizeof( buf ) ) - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - - ret = ( mode == RSA_PUBLIC ) - ? rsa_public( ctx, input, buf ) - : rsa_private( ctx, input, buf ); - - if( ret != 0 ) - return( ret ); - - p = buf; - - if( *p++ != 0 ) - return( POLARSSL_ERR_RSA_INVALID_PADDING ); - - md_info = md_info_from_type( ctx->hash_id ); - if( md_info == NULL ) - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - - hlen = md_get_size( md_info ); - - md_init_ctx( &md_ctx, md_info ); - - // Generate lHash - // - md( md_info, label, label_len, lhash ); - - // seed: Apply seedMask to maskedSeed - // - mgf_mask( buf + 1, hlen, buf + hlen + 1, ilen - hlen - 1, - &md_ctx ); - - // DB: Apply dbMask to maskedDB - // - mgf_mask( buf + hlen + 1, ilen - hlen - 1, buf + 1, hlen, - &md_ctx ); - - p += hlen; - md_free_ctx( &md_ctx ); - - // Check validity - // - if( memcmp( lhash, p, hlen ) != 0 ) - return( POLARSSL_ERR_RSA_INVALID_PADDING ); - - p += hlen; - - while( *p == 0 && p < buf + ilen ) - p++; - - if( p == buf + ilen ) - return( POLARSSL_ERR_RSA_INVALID_PADDING ); - - if( *p++ != 0x01 ) - return( POLARSSL_ERR_RSA_INVALID_PADDING ); - - if (ilen - (p - buf) > output_max_len) - return( POLARSSL_ERR_RSA_OUTPUT_TOO_LARGE ); - - *olen = ilen - (p - buf); - memcpy( output, p, *olen ); - - return( 0 ); -} -#endif /* POLARSSL_PKCS1_V21 */ - -/* - * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-DECRYPT function - */ -int rsa_rsaes_pkcs1_v15_decrypt( rsa_context *ctx, - int mode, size_t *olen, - const unsigned char *input, - unsigned char *output, - size_t output_max_len) -{ - int ret, correct = 1; - size_t ilen, pad_count = 0; - unsigned char *p, *q; - unsigned char bt; - unsigned char buf[POLARSSL_MPI_MAX_SIZE]; - - if( ctx->padding != RSA_PKCS_V15 ) - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - - ilen = ctx->len; - - if( ilen < 16 || ilen > sizeof( buf ) ) - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - - ret = ( mode == RSA_PUBLIC ) - ? rsa_public( ctx, input, buf ) - : rsa_private( ctx, input, buf ); - - if( ret != 0 ) - return( ret ); - - p = buf; - - if( *p++ != 0 ) - correct = 0; - - bt = *p++; - if( ( bt != RSA_CRYPT && mode == RSA_PRIVATE ) || - ( bt != RSA_SIGN && mode == RSA_PUBLIC ) ) - { - correct = 0; - } - - if( bt == RSA_CRYPT ) - { - while( *p != 0 && p < buf + ilen - 1 ) - pad_count += ( *p++ != 0 ); - - correct &= ( *p == 0 && p < buf + ilen - 1 ); - - q = p; - - // Also pass over all other bytes to reduce timing differences - // - while ( q < buf + ilen - 1 ) - pad_count += ( *q++ != 0 ); - - // Prevent compiler optimization of pad_count - // - correct |= pad_count & 0x100000; /* Always 0 unless 1M bit keys */ - p++; - } - else - { - while( *p == 0xFF && p < buf + ilen - 1 ) - pad_count += ( *p++ == 0xFF ); - - correct &= ( *p == 0 && p < buf + ilen - 1 ); - - q = p; - - // Also pass over all other bytes to reduce timing differences - // - while ( q < buf + ilen - 1 ) - pad_count += ( *q++ != 0 ); - - // Prevent compiler optimization of pad_count - // - correct |= pad_count & 0x100000; /* Always 0 unless 1M bit keys */ - p++; - } - - if( correct == 0 ) - return( POLARSSL_ERR_RSA_INVALID_PADDING ); - - if (ilen - (p - buf) > output_max_len) - return( POLARSSL_ERR_RSA_OUTPUT_TOO_LARGE ); - - *olen = ilen - (p - buf); - memcpy( output, p, *olen ); - - return( 0 ); -} - -/* - * Do an RSA operation, then remove the message padding - */ -int rsa_pkcs1_decrypt( rsa_context *ctx, - int mode, size_t *olen, - const unsigned char *input, - unsigned char *output, - size_t output_max_len) -{ - switch( ctx->padding ) - { - case RSA_PKCS_V15: - return rsa_rsaes_pkcs1_v15_decrypt( ctx, mode, olen, input, output, - output_max_len ); - -#if defined(POLARSSL_PKCS1_V21) - case RSA_PKCS_V21: - return rsa_rsaes_oaep_decrypt( ctx, mode, NULL, 0, olen, input, - output, output_max_len ); -#endif - - default: - return( POLARSSL_ERR_RSA_INVALID_PADDING ); - } -} - -#if defined(POLARSSL_PKCS1_V21) -/* - * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function - */ -int rsa_rsassa_pss_sign( rsa_context *ctx, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng, - int mode, - int hash_id, - unsigned int hashlen, - const unsigned char *hash, - unsigned char *sig ) -{ - size_t olen; - unsigned char *p = sig; - unsigned char salt[POLARSSL_MD_MAX_SIZE]; - unsigned int slen, hlen, offset = 0; - int ret; - size_t msb; - const md_info_t *md_info; - md_context_t md_ctx; - - if( ctx->padding != RSA_PKCS_V21 || f_rng == NULL ) - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - - olen = ctx->len; - - switch( hash_id ) - { - case SIG_RSA_MD2: - case SIG_RSA_MD4: - case SIG_RSA_MD5: - hashlen = 16; - break; - - case SIG_RSA_SHA1: - hashlen = 20; - break; - - case SIG_RSA_SHA224: - hashlen = 28; - break; - - case SIG_RSA_SHA256: - hashlen = 32; - break; - - case SIG_RSA_SHA384: - hashlen = 48; - break; - - case SIG_RSA_SHA512: - hashlen = 64; - break; - - default: - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - } - - md_info = md_info_from_type( ctx->hash_id ); - if( md_info == NULL ) - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - - hlen = md_get_size( md_info ); - slen = hlen; - - if( olen < hlen + slen + 2 ) - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - - memset( sig, 0, olen ); - - msb = mpi_msb( &ctx->N ) - 1; - - // Generate salt of length slen - // - if( ( ret = f_rng( p_rng, salt, slen ) ) != 0 ) - return( POLARSSL_ERR_RSA_RNG_FAILED + ret ); - - // Note: EMSA-PSS encoding is over the length of N - 1 bits - // - msb = mpi_msb( &ctx->N ) - 1; - p += olen - hlen * 2 - 2; - *p++ = 0x01; - memcpy( p, salt, slen ); - p += slen; - - md_init_ctx( &md_ctx, md_info ); - - // Generate H = Hash( M' ) - // - md_starts( &md_ctx ); - md_update( &md_ctx, p, 8 ); - md_update( &md_ctx, hash, hashlen ); - md_update( &md_ctx, salt, slen ); - md_finish( &md_ctx, p ); - - // Compensate for boundary condition when applying mask - // - if( msb % 8 == 0 ) - offset = 1; - - // maskedDB: Apply dbMask to DB - // - mgf_mask( sig + offset, olen - hlen - 1 - offset, p, hlen, &md_ctx ); - - md_free_ctx( &md_ctx ); - - msb = mpi_msb( &ctx->N ) - 1; - sig[0] &= 0xFF >> ( olen * 8 - msb ); - - p += hlen; - *p++ = 0xBC; - - return( ( mode == RSA_PUBLIC ) - ? rsa_public( ctx, sig, sig ) - : rsa_private( ctx, sig, sig ) ); -} -#endif /* POLARSSL_PKCS1_V21 */ - -/* - * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-V1_5-SIGN function - */ -/* - * Do an RSA operation to sign the message digest - */ -int rsa_rsassa_pkcs1_v15_sign( rsa_context *ctx, - int mode, - int hash_id, - unsigned int hashlen, - const unsigned char *hash, - unsigned char *sig ) -{ - size_t nb_pad, olen; - unsigned char *p = sig; - - if( ctx->padding != RSA_PKCS_V15 ) - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - - olen = ctx->len; - - switch( hash_id ) - { - case SIG_RSA_RAW: - nb_pad = olen - 3 - hashlen; - break; - - case SIG_RSA_MD2: - case SIG_RSA_MD4: - case SIG_RSA_MD5: - nb_pad = olen - 3 - 34; - break; - - case SIG_RSA_SHA1: - nb_pad = olen - 3 - 35; - break; - - case SIG_RSA_SHA224: - nb_pad = olen - 3 - 47; - break; - - case SIG_RSA_SHA256: - nb_pad = olen - 3 - 51; - break; - - case SIG_RSA_SHA384: - nb_pad = olen - 3 - 67; - break; - - case SIG_RSA_SHA512: - nb_pad = olen - 3 - 83; - break; - - - default: - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - } - - if( ( nb_pad < 8 ) || ( nb_pad > olen ) ) - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - - *p++ = 0; - *p++ = RSA_SIGN; - memset( p, 0xFF, nb_pad ); - p += nb_pad; - *p++ = 0; - - switch( hash_id ) - { - case SIG_RSA_RAW: - memcpy( p, hash, hashlen ); - break; - - case SIG_RSA_MD2: - memcpy( p, ASN1_HASH_MDX, 18 ); - memcpy( p + 18, hash, 16 ); - p[13] = 2; break; - - case SIG_RSA_MD4: - memcpy( p, ASN1_HASH_MDX, 18 ); - memcpy( p + 18, hash, 16 ); - p[13] = 4; break; - - case SIG_RSA_MD5: - memcpy( p, ASN1_HASH_MDX, 18 ); - memcpy( p + 18, hash, 16 ); - p[13] = 5; break; - - case SIG_RSA_SHA1: - memcpy( p, ASN1_HASH_SHA1, 15 ); - memcpy( p + 15, hash, 20 ); - break; - - case SIG_RSA_SHA224: - memcpy( p, ASN1_HASH_SHA2X, 19 ); - memcpy( p + 19, hash, 28 ); - p[1] += 28; p[14] = 4; p[18] += 28; break; - - case SIG_RSA_SHA256: - memcpy( p, ASN1_HASH_SHA2X, 19 ); - memcpy( p + 19, hash, 32 ); - p[1] += 32; p[14] = 1; p[18] += 32; break; - - case SIG_RSA_SHA384: - memcpy( p, ASN1_HASH_SHA2X, 19 ); - memcpy( p + 19, hash, 48 ); - p[1] += 48; p[14] = 2; p[18] += 48; break; - - case SIG_RSA_SHA512: - memcpy( p, ASN1_HASH_SHA2X, 19 ); - memcpy( p + 19, hash, 64 ); - p[1] += 64; p[14] = 3; p[18] += 64; break; - - default: - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - } - - return( ( mode == RSA_PUBLIC ) - ? rsa_public( ctx, sig, sig ) - : rsa_private( ctx, sig, sig ) ); -} - -/* - * Do an RSA operation to sign the message digest - */ -int rsa_pkcs1_sign( rsa_context *ctx, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng, - int mode, - int hash_id, - unsigned int hashlen, - const unsigned char *hash, - unsigned char *sig ) -{ - switch( ctx->padding ) - { - case RSA_PKCS_V15: - return rsa_rsassa_pkcs1_v15_sign( ctx, mode, hash_id, - hashlen, hash, sig ); - -#if defined(POLARSSL_PKCS1_V21) - case RSA_PKCS_V21: - return rsa_rsassa_pss_sign( ctx, f_rng, p_rng, mode, hash_id, - hashlen, hash, sig ); -#endif - - default: - return( POLARSSL_ERR_RSA_INVALID_PADDING ); - } -} - -#if defined(POLARSSL_PKCS1_V21) -/* - * Implementation of the PKCS#1 v2.1 RSASSA-PSS-VERIFY function - */ -int rsa_rsassa_pss_verify( rsa_context *ctx, - int mode, - int hash_id, - unsigned int hashlen, - const unsigned char *hash, - const unsigned char *sig ) -{ - int ret; - size_t siglen; - unsigned char *p; - unsigned char buf[POLARSSL_MPI_MAX_SIZE]; - unsigned char result[POLARSSL_MD_MAX_SIZE]; - unsigned char zeros[8]; - unsigned int hlen; - size_t slen, msb; - const md_info_t *md_info; - md_context_t md_ctx; - - if( ctx->padding != RSA_PKCS_V21 ) - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - - siglen = ctx->len; - - if( siglen < 16 || siglen > sizeof( buf ) ) - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - - ret = ( mode == RSA_PUBLIC ) - ? rsa_public( ctx, sig, buf ) - : rsa_private( ctx, sig, buf ); - - if( ret != 0 ) - return( ret ); - - p = buf; - - if( buf[siglen - 1] != 0xBC ) - return( POLARSSL_ERR_RSA_INVALID_PADDING ); - - switch( hash_id ) - { - case SIG_RSA_MD2: - case SIG_RSA_MD4: - case SIG_RSA_MD5: - hashlen = 16; - break; - - case SIG_RSA_SHA1: - hashlen = 20; - break; - - case SIG_RSA_SHA224: - hashlen = 28; - break; - - case SIG_RSA_SHA256: - hashlen = 32; - break; - - case SIG_RSA_SHA384: - hashlen = 48; - break; - - case SIG_RSA_SHA512: - hashlen = 64; - break; - - default: - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - } - - md_info = md_info_from_type( ctx->hash_id ); - if( md_info == NULL ) - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - - hlen = md_get_size( md_info ); - slen = siglen - hlen - 1; - - memset( zeros, 0, 8 ); - - // Note: EMSA-PSS verification is over the length of N - 1 bits - // - msb = mpi_msb( &ctx->N ) - 1; - - // Compensate for boundary condition when applying mask - // - if( msb % 8 == 0 ) - { - p++; - siglen -= 1; - } - if( buf[0] >> ( 8 - siglen * 8 + msb ) ) - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - - md_init_ctx( &md_ctx, md_info ); - - mgf_mask( p, siglen - hlen - 1, p + siglen - hlen - 1, hlen, &md_ctx ); - - buf[0] &= 0xFF >> ( siglen * 8 - msb ); - - while( *p == 0 && p < buf + siglen ) - p++; - - if( p == buf + siglen || - *p++ != 0x01 ) - { - md_free_ctx( &md_ctx ); - return( POLARSSL_ERR_RSA_INVALID_PADDING ); - } - - slen -= p - buf; - - // Generate H = Hash( M' ) - // - md_starts( &md_ctx ); - md_update( &md_ctx, zeros, 8 ); - md_update( &md_ctx, hash, hashlen ); - md_update( &md_ctx, p, slen ); - md_finish( &md_ctx, result ); - - md_free_ctx( &md_ctx ); - - if( memcmp( p + slen, result, hlen ) == 0 ) - return( 0 ); - else - return( POLARSSL_ERR_RSA_VERIFY_FAILED ); -} -#endif /* POLARSSL_PKCS1_V21 */ - -/* - * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-v1_5-VERIFY function - */ -int rsa_rsassa_pkcs1_v15_verify( rsa_context *ctx, - int mode, - int hash_id, - unsigned int hashlen, - const unsigned char *hash, - const unsigned char *sig ) -{ - int ret; - size_t len, siglen; - unsigned char *p, c; - unsigned char buf[POLARSSL_MPI_MAX_SIZE]; - - if( ctx->padding != RSA_PKCS_V15 ) - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - - siglen = ctx->len; - - if( siglen < 16 || siglen > sizeof( buf ) ) - return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); - - ret = ( mode == RSA_PUBLIC ) - ? rsa_public( ctx, sig, buf ) - : rsa_private( ctx, sig, buf ); - - if( ret != 0 ) - return( ret ); - - p = buf; - - if( *p++ != 0 || *p++ != RSA_SIGN ) - return( POLARSSL_ERR_RSA_INVALID_PADDING ); - - while( *p != 0 ) - { - if( p >= buf + siglen - 1 || *p != 0xFF ) - return( POLARSSL_ERR_RSA_INVALID_PADDING ); - p++; - } - p++; - - len = siglen - ( p - buf ); - - if( len == 33 && hash_id == SIG_RSA_SHA1 ) - { - if( memcmp( p, ASN1_HASH_SHA1_ALT, 13 ) == 0 && - memcmp( p + 13, hash, 20 ) == 0 ) - return( 0 ); - else - return( POLARSSL_ERR_RSA_VERIFY_FAILED ); - } - if( len == 34 ) - { - c = p[13]; - p[13] = 0; - - if( memcmp( p, ASN1_HASH_MDX, 18 ) != 0 ) - return( POLARSSL_ERR_RSA_VERIFY_FAILED ); - - if( ( c == 2 && hash_id == SIG_RSA_MD2 ) || - ( c == 4 && hash_id == SIG_RSA_MD4 ) || - ( c == 5 && hash_id == SIG_RSA_MD5 ) ) - { - if( memcmp( p + 18, hash, 16 ) == 0 ) - return( 0 ); - else - return( POLARSSL_ERR_RSA_VERIFY_FAILED ); - } - } - - if( len == 35 && hash_id == SIG_RSA_SHA1 ) - { - if( memcmp( p, ASN1_HASH_SHA1, 15 ) == 0 && - memcmp( p + 15, hash, 20 ) == 0 ) - return( 0 ); - else - return( POLARSSL_ERR_RSA_VERIFY_FAILED ); - } - if( ( len == 19 + 28 && p[14] == 4 && hash_id == SIG_RSA_SHA224 ) || - ( len == 19 + 32 && p[14] == 1 && hash_id == SIG_RSA_SHA256 ) || - ( len == 19 + 48 && p[14] == 2 && hash_id == SIG_RSA_SHA384 ) || - ( len == 19 + 64 && p[14] == 3 && hash_id == SIG_RSA_SHA512 ) ) - { - c = p[1] - 17; - p[1] = 17; - p[14] = 0; - - if( p[18] == c && - memcmp( p, ASN1_HASH_SHA2X, 18 ) == 0 && - memcmp( p + 19, hash, c ) == 0 ) - return( 0 ); - else - return( POLARSSL_ERR_RSA_VERIFY_FAILED ); - } - - if( len == hashlen && hash_id == SIG_RSA_RAW ) - { - if( memcmp( p, hash, hashlen ) == 0 ) - return( 0 ); - else - return( POLARSSL_ERR_RSA_VERIFY_FAILED ); - } - - return( POLARSSL_ERR_RSA_INVALID_PADDING ); -} - -/* - * Do an RSA operation and check the message digest - */ -int rsa_pkcs1_verify( rsa_context *ctx, - int mode, - int hash_id, - unsigned int hashlen, - const unsigned char *hash, - const unsigned char *sig ) -{ - switch( ctx->padding ) - { - case RSA_PKCS_V15: - return rsa_rsassa_pkcs1_v15_verify( ctx, mode, hash_id, - hashlen, hash, sig ); - -#if defined(POLARSSL_PKCS1_V21) - case RSA_PKCS_V21: - return rsa_rsassa_pss_verify( ctx, mode, hash_id, - hashlen, hash, sig ); -#endif - - default: - return( POLARSSL_ERR_RSA_INVALID_PADDING ); - } -} - -/* - * Free the components of an RSA key - */ -void rsa_free( rsa_context *ctx ) -{ - mpi_free( &ctx->RQ ); mpi_free( &ctx->RP ); mpi_free( &ctx->RN ); - mpi_free( &ctx->QP ); mpi_free( &ctx->DQ ); mpi_free( &ctx->DP ); - mpi_free( &ctx->Q ); mpi_free( &ctx->P ); mpi_free( &ctx->D ); - mpi_free( &ctx->E ); mpi_free( &ctx->N ); -} - -#if defined(POLARSSL_SELF_TEST) - -#include "polarssl/sha1.h" - -/* - * Example RSA-1024 keypair, for test purposes - */ -#define KEY_LEN 128 - -#define RSA_N "9292758453063D803DD603D5E777D788" \ - "8ED1D5BF35786190FA2F23EBC0848AEA" \ - "DDA92CA6C3D80B32C4D109BE0F36D6AE" \ - "7130B9CED7ACDF54CFC7555AC14EEBAB" \ - "93A89813FBF3C4F8066D2D800F7C38A8" \ - "1AE31942917403FF4946B0A83D3D3E05" \ - "EE57C6F5F5606FB5D4BC6CD34EE0801A" \ - "5E94BB77B07507233A0BC7BAC8F90F79" - -#define RSA_E "10001" - -#define RSA_D "24BF6185468786FDD303083D25E64EFC" \ - "66CA472BC44D253102F8B4A9D3BFA750" \ - "91386C0077937FE33FA3252D28855837" \ - "AE1B484A8A9A45F7EE8C0C634F99E8CD" \ - "DF79C5CE07EE72C7F123142198164234" \ - "CABB724CF78B8173B9F880FC86322407" \ - "AF1FEDFDDE2BEB674CA15F3E81A1521E" \ - "071513A1E85B5DFA031F21ECAE91A34D" - -#define RSA_P "C36D0EB7FCD285223CFB5AABA5BDA3D8" \ - "2C01CAD19EA484A87EA4377637E75500" \ - "FCB2005C5C7DD6EC4AC023CDA285D796" \ - "C3D9E75E1EFC42488BB4F1D13AC30A57" - -#define RSA_Q "C000DF51A7C77AE8D7C7370C1FF55B69" \ - "E211C2B9E5DB1ED0BF61D0D9899620F4" \ - "910E4168387E3C30AA1E00C339A79508" \ - "8452DD96A9A5EA5D9DCA68DA636032AF" - -#define RSA_DP "C1ACF567564274FB07A0BBAD5D26E298" \ - "3C94D22288ACD763FD8E5600ED4A702D" \ - "F84198A5F06C2E72236AE490C93F07F8" \ - "3CC559CD27BC2D1CA488811730BB5725" - -#define RSA_DQ "4959CBF6F8FEF750AEE6977C155579C7" \ - "D8AAEA56749EA28623272E4F7D0592AF" \ - "7C1F1313CAC9471B5C523BFE592F517B" \ - "407A1BD76C164B93DA2D32A383E58357" - -#define RSA_QP "9AE7FBC99546432DF71896FC239EADAE" \ - "F38D18D2B2F0E2DD275AA977E2BF4411" \ - "F5A3B2A5D33605AEBBCCBA7FEB9F2D2F" \ - "A74206CEC169D74BF5A8C50D6F48EA08" - -#define PT_LEN 24 -#define RSA_PT "\xAA\xBB\xCC\x03\x02\x01\x00\xFF\xFF\xFF\xFF\xFF" \ - "\x11\x22\x33\x0A\x0B\x0C\xCC\xDD\xDD\xDD\xDD\xDD" - -static int myrand( void *rng_state, unsigned char *output, size_t len ) -{ - size_t i; - - if( rng_state != NULL ) - rng_state = NULL; - - for( i = 0; i < len; ++i ) - output[i] = rand(); - - return( 0 ); -} - -/* - * Checkup routine - */ -int rsa_self_test( int verbose ) -{ - size_t len; - rsa_context rsa; - unsigned char rsa_plaintext[PT_LEN]; - unsigned char rsa_decrypted[PT_LEN]; - unsigned char rsa_ciphertext[KEY_LEN]; -#if defined(POLARSSL_SHA1_C) - unsigned char sha1sum[20]; -#endif - - rsa_init( &rsa, RSA_PKCS_V15, 0 ); - - rsa.len = KEY_LEN; - mpi_read_string( &rsa.N , 16, RSA_N ); - mpi_read_string( &rsa.E , 16, RSA_E ); - mpi_read_string( &rsa.D , 16, RSA_D ); - mpi_read_string( &rsa.P , 16, RSA_P ); - mpi_read_string( &rsa.Q , 16, RSA_Q ); - mpi_read_string( &rsa.DP, 16, RSA_DP ); - mpi_read_string( &rsa.DQ, 16, RSA_DQ ); - mpi_read_string( &rsa.QP, 16, RSA_QP ); - - if( verbose != 0 ) - printf( " RSA key validation: " ); - - if( rsa_check_pubkey( &rsa ) != 0 || - rsa_check_privkey( &rsa ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( verbose != 0 ) - printf( "passed\n PKCS#1 encryption : " ); - - memcpy( rsa_plaintext, RSA_PT, PT_LEN ); - - if( rsa_pkcs1_encrypt( &rsa, &myrand, NULL, RSA_PUBLIC, PT_LEN, - rsa_plaintext, rsa_ciphertext ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( verbose != 0 ) - printf( "passed\n PKCS#1 decryption : " ); - - if( rsa_pkcs1_decrypt( &rsa, RSA_PRIVATE, &len, - rsa_ciphertext, rsa_decrypted, - sizeof(rsa_decrypted) ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( memcmp( rsa_decrypted, rsa_plaintext, len ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - -#if defined(POLARSSL_SHA1_C) - if( verbose != 0 ) - printf( "passed\n PKCS#1 data sign : " ); - - sha1( rsa_plaintext, PT_LEN, sha1sum ); - - if( rsa_pkcs1_sign( &rsa, NULL, NULL, RSA_PRIVATE, SIG_RSA_SHA1, 20, - sha1sum, rsa_ciphertext ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( verbose != 0 ) - printf( "passed\n PKCS#1 sig. verify: " ); - - if( rsa_pkcs1_verify( &rsa, RSA_PUBLIC, SIG_RSA_SHA1, 20, - sha1sum, rsa_ciphertext ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( verbose != 0 ) - printf( "passed\n\n" ); -#endif /* POLARSSL_SHA1_C */ - - rsa_free( &rsa ); - - return( 0 ); -} - -#endif - -#endif diff --git a/lib/libpolarssl/source/sha1.c b/lib/libpolarssl/source/sha1.c deleted file mode 100644 index 36b4c73..0000000 --- a/lib/libpolarssl/source/sha1.c +++ /dev/null @@ -1,624 +0,0 @@ -/* - * FIPS-180-1 compliant SHA-1 implementation - * - * Copyright (C) 2006-2013, Brainspark B.V. - * - * This file is part of PolarSSL (http://www.polarssl.org) - * Lead Maintainer: Paul Bakker - * - * All rights reserved. - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ -/* - * The SHA-1 standard was published by NIST in 1993. - * - * http://www.itl.nist.gov/fipspubs/fip180-1.htm - */ - -#include - -#if defined(POLARSSL_SHA1_C) - -#include - -#if defined(POLARSSL_FS_IO) || defined(POLARSSL_SELF_TEST) -#include -#endif - -#if !defined(POLARSSL_SHA1_ALT) - -/* - * 32-bit integer manipulation macros (big endian) - */ -#ifndef GET_UINT32_BE -#define GET_UINT32_BE(n,b,i) \ -{ \ - (n) = ( (uint32_t) (b)[(i) ] << 24 ) \ - | ( (uint32_t) (b)[(i) + 1] << 16 ) \ - | ( (uint32_t) (b)[(i) + 2] << 8 ) \ - | ( (uint32_t) (b)[(i) + 3] ); \ -} -#endif - -#ifndef PUT_UINT32_BE -#define PUT_UINT32_BE(n,b,i) \ -{ \ - (b)[(i) ] = (unsigned char) ( (n) >> 24 ); \ - (b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \ - (b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \ - (b)[(i) + 3] = (unsigned char) ( (n) ); \ -} -#endif - -/* - * SHA-1 context setup - */ -void sha1_starts( sha1_context *ctx ) -{ - ctx->total[0] = 0; - ctx->total[1] = 0; - - ctx->state[0] = 0x67452301; - ctx->state[1] = 0xEFCDAB89; - ctx->state[2] = 0x98BADCFE; - ctx->state[3] = 0x10325476; - ctx->state[4] = 0xC3D2E1F0; -} - -void sha1_process( sha1_context *ctx, const unsigned char data[64] ) -{ - uint32_t temp, W[16], A, B, C, D, E; - - GET_UINT32_BE( W[ 0], data, 0 ); - GET_UINT32_BE( W[ 1], data, 4 ); - GET_UINT32_BE( W[ 2], data, 8 ); - GET_UINT32_BE( W[ 3], data, 12 ); - GET_UINT32_BE( W[ 4], data, 16 ); - GET_UINT32_BE( W[ 5], data, 20 ); - GET_UINT32_BE( W[ 6], data, 24 ); - GET_UINT32_BE( W[ 7], data, 28 ); - GET_UINT32_BE( W[ 8], data, 32 ); - GET_UINT32_BE( W[ 9], data, 36 ); - GET_UINT32_BE( W[10], data, 40 ); - GET_UINT32_BE( W[11], data, 44 ); - GET_UINT32_BE( W[12], data, 48 ); - GET_UINT32_BE( W[13], data, 52 ); - GET_UINT32_BE( W[14], data, 56 ); - GET_UINT32_BE( W[15], data, 60 ); - -#define S(x,n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n))) - -#define R(t) \ -( \ - temp = W[(t - 3) & 0x0F] ^ W[(t - 8) & 0x0F] ^ \ - W[(t - 14) & 0x0F] ^ W[ t & 0x0F], \ - ( W[t & 0x0F] = S(temp,1) ) \ -) - -#define P(a,b,c,d,e,x) \ -{ \ - e += S(a,5) + F(b,c,d) + K + x; b = S(b,30); \ -} - - A = ctx->state[0]; - B = ctx->state[1]; - C = ctx->state[2]; - D = ctx->state[3]; - E = ctx->state[4]; - -#define F(x,y,z) (z ^ (x & (y ^ z))) -#define K 0x5A827999 - - P( A, B, C, D, E, W[0] ); - P( E, A, B, C, D, W[1] ); - P( D, E, A, B, C, W[2] ); - P( C, D, E, A, B, W[3] ); - P( B, C, D, E, A, W[4] ); - P( A, B, C, D, E, W[5] ); - P( E, A, B, C, D, W[6] ); - P( D, E, A, B, C, W[7] ); - P( C, D, E, A, B, W[8] ); - P( B, C, D, E, A, W[9] ); - P( A, B, C, D, E, W[10] ); - P( E, A, B, C, D, W[11] ); - P( D, E, A, B, C, W[12] ); - P( C, D, E, A, B, W[13] ); - P( B, C, D, E, A, W[14] ); - P( A, B, C, D, E, W[15] ); - P( E, A, B, C, D, R(16) ); - P( D, E, A, B, C, R(17) ); - P( C, D, E, A, B, R(18) ); - P( B, C, D, E, A, R(19) ); - -#undef K -#undef F - -#define F(x,y,z) (x ^ y ^ z) -#define K 0x6ED9EBA1 - - P( A, B, C, D, E, R(20) ); - P( E, A, B, C, D, R(21) ); - P( D, E, A, B, C, R(22) ); - P( C, D, E, A, B, R(23) ); - P( B, C, D, E, A, R(24) ); - P( A, B, C, D, E, R(25) ); - P( E, A, B, C, D, R(26) ); - P( D, E, A, B, C, R(27) ); - P( C, D, E, A, B, R(28) ); - P( B, C, D, E, A, R(29) ); - P( A, B, C, D, E, R(30) ); - P( E, A, B, C, D, R(31) ); - P( D, E, A, B, C, R(32) ); - P( C, D, E, A, B, R(33) ); - P( B, C, D, E, A, R(34) ); - P( A, B, C, D, E, R(35) ); - P( E, A, B, C, D, R(36) ); - P( D, E, A, B, C, R(37) ); - P( C, D, E, A, B, R(38) ); - P( B, C, D, E, A, R(39) ); - -#undef K -#undef F - -#define F(x,y,z) ((x & y) | (z & (x | y))) -#define K 0x8F1BBCDC - - P( A, B, C, D, E, R(40) ); - P( E, A, B, C, D, R(41) ); - P( D, E, A, B, C, R(42) ); - P( C, D, E, A, B, R(43) ); - P( B, C, D, E, A, R(44) ); - P( A, B, C, D, E, R(45) ); - P( E, A, B, C, D, R(46) ); - P( D, E, A, B, C, R(47) ); - P( C, D, E, A, B, R(48) ); - P( B, C, D, E, A, R(49) ); - P( A, B, C, D, E, R(50) ); - P( E, A, B, C, D, R(51) ); - P( D, E, A, B, C, R(52) ); - P( C, D, E, A, B, R(53) ); - P( B, C, D, E, A, R(54) ); - P( A, B, C, D, E, R(55) ); - P( E, A, B, C, D, R(56) ); - P( D, E, A, B, C, R(57) ); - P( C, D, E, A, B, R(58) ); - P( B, C, D, E, A, R(59) ); - -#undef K -#undef F - -#define F(x,y,z) (x ^ y ^ z) -#define K 0xCA62C1D6 - - P( A, B, C, D, E, R(60) ); - P( E, A, B, C, D, R(61) ); - P( D, E, A, B, C, R(62) ); - P( C, D, E, A, B, R(63) ); - P( B, C, D, E, A, R(64) ); - P( A, B, C, D, E, R(65) ); - P( E, A, B, C, D, R(66) ); - P( D, E, A, B, C, R(67) ); - P( C, D, E, A, B, R(68) ); - P( B, C, D, E, A, R(69) ); - P( A, B, C, D, E, R(70) ); - P( E, A, B, C, D, R(71) ); - P( D, E, A, B, C, R(72) ); - P( C, D, E, A, B, R(73) ); - P( B, C, D, E, A, R(74) ); - P( A, B, C, D, E, R(75) ); - P( E, A, B, C, D, R(76) ); - P( D, E, A, B, C, R(77) ); - P( C, D, E, A, B, R(78) ); - P( B, C, D, E, A, R(79) ); - -#undef K -#undef F - - ctx->state[0] += A; - ctx->state[1] += B; - ctx->state[2] += C; - ctx->state[3] += D; - ctx->state[4] += E; -} - -/* - * SHA-1 process buffer - */ -void sha1_update( sha1_context *ctx, const unsigned char *input, size_t ilen ) -{ - size_t fill; - uint32_t left; - - if( ilen <= 0 ) - return; - - left = ctx->total[0] & 0x3F; - fill = 64 - left; - - ctx->total[0] += (uint32_t) ilen; - ctx->total[0] &= 0xFFFFFFFF; - - if( ctx->total[0] < (uint32_t) ilen ) - ctx->total[1]++; - - if( left && ilen >= fill ) - { - memcpy( (void *) (ctx->buffer + left), input, fill ); - sha1_process( ctx, ctx->buffer ); - input += fill; - ilen -= fill; - left = 0; - } - - while( ilen >= 64 ) - { - sha1_process( ctx, input ); - input += 64; - ilen -= 64; - } - - if( ilen > 0 ) - memcpy( (void *) (ctx->buffer + left), input, ilen ); -} - -static const unsigned char sha1_padding[64] = -{ - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -/* - * SHA-1 final digest - */ -void sha1_finish( sha1_context *ctx, unsigned char output[20] ) -{ - uint32_t last, padn; - uint32_t high, low; - unsigned char msglen[8]; - - high = ( ctx->total[0] >> 29 ) - | ( ctx->total[1] << 3 ); - low = ( ctx->total[0] << 3 ); - - PUT_UINT32_BE( high, msglen, 0 ); - PUT_UINT32_BE( low, msglen, 4 ); - - last = ctx->total[0] & 0x3F; - padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last ); - - sha1_update( ctx, sha1_padding, padn ); - sha1_update( ctx, msglen, 8 ); - - PUT_UINT32_BE( ctx->state[0], output, 0 ); - PUT_UINT32_BE( ctx->state[1], output, 4 ); - PUT_UINT32_BE( ctx->state[2], output, 8 ); - PUT_UINT32_BE( ctx->state[3], output, 12 ); - PUT_UINT32_BE( ctx->state[4], output, 16 ); -} - -#endif /* !POLARSSL_SHA1_ALT */ - -/* - * output = SHA-1( input buffer ) - */ -void sha1( const unsigned char *input, size_t ilen, unsigned char output[20] ) -{ - sha1_context ctx; - - sha1_starts( &ctx ); - sha1_update( &ctx, input, ilen ); - sha1_finish( &ctx, output ); - - memset( &ctx, 0, sizeof( sha1_context ) ); -} - -#if defined(POLARSSL_FS_IO) -/* - * output = SHA-1( file contents ) - */ -int sha1_file( const char *path, unsigned char output[20] ) -{ - FILE *f; - size_t n; - sha1_context ctx; - unsigned char buf[1024]; - - if( ( f = fopen( path, "rb" ) ) == NULL ) - return( POLARSSL_ERR_SHA1_FILE_IO_ERROR ); - - sha1_starts( &ctx ); - - while( ( n = fread( buf, 1, sizeof( buf ), f ) ) > 0 ) - sha1_update( &ctx, buf, n ); - - sha1_finish( &ctx, output ); - - memset( &ctx, 0, sizeof( sha1_context ) ); - - if( ferror( f ) != 0 ) - { - fclose( f ); - return( POLARSSL_ERR_SHA1_FILE_IO_ERROR ); - } - - fclose( f ); - return( 0 ); -} -#endif /* POLARSSL_FS_IO */ - -/* - * SHA-1 HMAC context setup - */ -void sha1_hmac_starts( sha1_context *ctx, const unsigned char *key, size_t keylen ) -{ - size_t i; - unsigned char sum[20]; - - if( keylen > 64 ) - { - sha1( key, keylen, sum ); - keylen = 20; - key = sum; - } - - memset( ctx->ipad, 0x36, 64 ); - memset( ctx->opad, 0x5C, 64 ); - - for( i = 0; i < keylen; i++ ) - { - ctx->ipad[i] = (unsigned char)( ctx->ipad[i] ^ key[i] ); - ctx->opad[i] = (unsigned char)( ctx->opad[i] ^ key[i] ); - } - - sha1_starts( ctx ); - sha1_update( ctx, ctx->ipad, 64 ); - - memset( sum, 0, sizeof( sum ) ); -} - -/* - * SHA-1 HMAC process buffer - */ -void sha1_hmac_update( sha1_context *ctx, const unsigned char *input, size_t ilen ) -{ - sha1_update( ctx, input, ilen ); -} - -/* - * SHA-1 HMAC final digest - */ -void sha1_hmac_finish( sha1_context *ctx, unsigned char output[20] ) -{ - unsigned char tmpbuf[20]; - - sha1_finish( ctx, tmpbuf ); - sha1_starts( ctx ); - sha1_update( ctx, ctx->opad, 64 ); - sha1_update( ctx, tmpbuf, 20 ); - sha1_finish( ctx, output ); - - memset( tmpbuf, 0, sizeof( tmpbuf ) ); -} - -/* - * SHA1 HMAC context reset - */ -void sha1_hmac_reset( sha1_context *ctx ) -{ - sha1_starts( ctx ); - sha1_update( ctx, ctx->ipad, 64 ); -} - -/* - * output = HMAC-SHA-1( hmac key, input buffer ) - */ -void sha1_hmac( const unsigned char *key, size_t keylen, - const unsigned char *input, size_t ilen, - unsigned char output[20] ) -{ - sha1_context ctx; - - sha1_hmac_starts( &ctx, key, keylen ); - sha1_hmac_update( &ctx, input, ilen ); - sha1_hmac_finish( &ctx, output ); - - memset( &ctx, 0, sizeof( sha1_context ) ); -} - -#if defined(POLARSSL_SELF_TEST) -/* - * FIPS-180-1 test vectors - */ -static unsigned char sha1_test_buf[3][57] = -{ - { "abc" }, - { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" }, - { "" } -}; - -static const int sha1_test_buflen[3] = -{ - 3, 56, 1000 -}; - -static const unsigned char sha1_test_sum[3][20] = -{ - { 0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A, 0xBA, 0x3E, - 0x25, 0x71, 0x78, 0x50, 0xC2, 0x6C, 0x9C, 0xD0, 0xD8, 0x9D }, - { 0x84, 0x98, 0x3E, 0x44, 0x1C, 0x3B, 0xD2, 0x6E, 0xBA, 0xAE, - 0x4A, 0xA1, 0xF9, 0x51, 0x29, 0xE5, 0xE5, 0x46, 0x70, 0xF1 }, - { 0x34, 0xAA, 0x97, 0x3C, 0xD4, 0xC4, 0xDA, 0xA4, 0xF6, 0x1E, - 0xEB, 0x2B, 0xDB, 0xAD, 0x27, 0x31, 0x65, 0x34, 0x01, 0x6F } -}; - -/* - * RFC 2202 test vectors - */ -static unsigned char sha1_hmac_test_key[7][26] = -{ - { "\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B" - "\x0B\x0B\x0B\x0B" }, - { "Jefe" }, - { "\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA" - "\xAA\xAA\xAA\xAA" }, - { "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10" - "\x11\x12\x13\x14\x15\x16\x17\x18\x19" }, - { "\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C" - "\x0C\x0C\x0C\x0C" }, - { "" }, /* 0xAA 80 times */ - { "" } -}; - -static const int sha1_hmac_test_keylen[7] = -{ - 20, 4, 20, 25, 20, 80, 80 -}; - -static unsigned char sha1_hmac_test_buf[7][74] = -{ - { "Hi There" }, - { "what do ya want for nothing?" }, - { "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD" - "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD" - "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD" - "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD" - "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD" }, - { "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" - "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" - "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" - "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" - "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" }, - { "Test With Truncation" }, - { "Test Using Larger Than Block-Size Key - Hash Key First" }, - { "Test Using Larger Than Block-Size Key and Larger" - " Than One Block-Size Data" } -}; - -static const int sha1_hmac_test_buflen[7] = -{ - 8, 28, 50, 50, 20, 54, 73 -}; - -static const unsigned char sha1_hmac_test_sum[7][20] = -{ - { 0xB6, 0x17, 0x31, 0x86, 0x55, 0x05, 0x72, 0x64, 0xE2, 0x8B, - 0xC0, 0xB6, 0xFB, 0x37, 0x8C, 0x8E, 0xF1, 0x46, 0xBE, 0x00 }, - { 0xEF, 0xFC, 0xDF, 0x6A, 0xE5, 0xEB, 0x2F, 0xA2, 0xD2, 0x74, - 0x16, 0xD5, 0xF1, 0x84, 0xDF, 0x9C, 0x25, 0x9A, 0x7C, 0x79 }, - { 0x12, 0x5D, 0x73, 0x42, 0xB9, 0xAC, 0x11, 0xCD, 0x91, 0xA3, - 0x9A, 0xF4, 0x8A, 0xA1, 0x7B, 0x4F, 0x63, 0xF1, 0x75, 0xD3 }, - { 0x4C, 0x90, 0x07, 0xF4, 0x02, 0x62, 0x50, 0xC6, 0xBC, 0x84, - 0x14, 0xF9, 0xBF, 0x50, 0xC8, 0x6C, 0x2D, 0x72, 0x35, 0xDA }, - { 0x4C, 0x1A, 0x03, 0x42, 0x4B, 0x55, 0xE0, 0x7F, 0xE7, 0xF2, - 0x7B, 0xE1 }, - { 0xAA, 0x4A, 0xE5, 0xE1, 0x52, 0x72, 0xD0, 0x0E, 0x95, 0x70, - 0x56, 0x37, 0xCE, 0x8A, 0x3B, 0x55, 0xED, 0x40, 0x21, 0x12 }, - { 0xE8, 0xE9, 0x9D, 0x0F, 0x45, 0x23, 0x7D, 0x78, 0x6D, 0x6B, - 0xBA, 0xA7, 0x96, 0x5C, 0x78, 0x08, 0xBB, 0xFF, 0x1A, 0x91 } -}; - -/* - * Checkup routine - */ -int sha1_self_test( int verbose ) -{ - int i, j, buflen; - unsigned char buf[1024]; - unsigned char sha1sum[20]; - sha1_context ctx; - - /* - * SHA-1 - */ - for( i = 0; i < 3; i++ ) - { - if( verbose != 0 ) - printf( " SHA-1 test #%d: ", i + 1 ); - - sha1_starts( &ctx ); - - if( i == 2 ) - { - memset( buf, 'a', buflen = 1000 ); - - for( j = 0; j < 1000; j++ ) - sha1_update( &ctx, buf, buflen ); - } - else - sha1_update( &ctx, sha1_test_buf[i], - sha1_test_buflen[i] ); - - sha1_finish( &ctx, sha1sum ); - - if( memcmp( sha1sum, sha1_test_sum[i], 20 ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( verbose != 0 ) - printf( "passed\n" ); - } - - if( verbose != 0 ) - printf( "\n" ); - - for( i = 0; i < 7; i++ ) - { - if( verbose != 0 ) - printf( " HMAC-SHA-1 test #%d: ", i + 1 ); - - if( i == 5 || i == 6 ) - { - memset( buf, '\xAA', buflen = 80 ); - sha1_hmac_starts( &ctx, buf, buflen ); - } - else - sha1_hmac_starts( &ctx, sha1_hmac_test_key[i], - sha1_hmac_test_keylen[i] ); - - sha1_hmac_update( &ctx, sha1_hmac_test_buf[i], - sha1_hmac_test_buflen[i] ); - - sha1_hmac_finish( &ctx, sha1sum ); - - buflen = ( i == 4 ) ? 12 : 20; - - if( memcmp( sha1sum, sha1_hmac_test_sum[i], buflen ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( verbose != 0 ) - printf( "passed\n" ); - } - - if( verbose != 0 ) - printf( "\n" ); - - return( 0 ); -} - -#endif - -#endif diff --git a/lib/libpolarssl/source/sha2.c b/lib/libpolarssl/source/sha2.c deleted file mode 100644 index 6c19082..0000000 --- a/lib/libpolarssl/source/sha2.c +++ /dev/null @@ -1,705 +0,0 @@ -/* - * FIPS-180-2 compliant SHA-256 implementation - * - * Copyright (C) 2006-2013, Brainspark B.V. - * - * This file is part of PolarSSL (http://www.polarssl.org) - * Lead Maintainer: Paul Bakker - * - * All rights reserved. - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ -/* - * The SHA-256 Secure Hash Standard was published by NIST in 2002. - * - * http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf - */ - -#include - -#if defined(POLARSSL_SHA2_C) - -#include - -#if defined(POLARSSL_FS_IO) || defined(POLARSSL_SELF_TEST) -#include -#endif - -#if !defined(POLARSSL_SHA2_ALT) - -/* - * 32-bit integer manipulation macros (big endian) - */ -#ifndef GET_UINT32_BE -#define GET_UINT32_BE(n,b,i) \ -{ \ - (n) = ( (uint32_t) (b)[(i) ] << 24 ) \ - | ( (uint32_t) (b)[(i) + 1] << 16 ) \ - | ( (uint32_t) (b)[(i) + 2] << 8 ) \ - | ( (uint32_t) (b)[(i) + 3] ); \ -} -#endif - -#ifndef PUT_UINT32_BE -#define PUT_UINT32_BE(n,b,i) \ -{ \ - (b)[(i) ] = (unsigned char) ( (n) >> 24 ); \ - (b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \ - (b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \ - (b)[(i) + 3] = (unsigned char) ( (n) ); \ -} -#endif - -/* - * SHA-256 context setup - */ -void sha2_starts( sha2_context *ctx, int is224 ) -{ - ctx->total[0] = 0; - ctx->total[1] = 0; - - if( is224 == 0 ) - { - /* SHA-256 */ - ctx->state[0] = 0x6A09E667; - ctx->state[1] = 0xBB67AE85; - ctx->state[2] = 0x3C6EF372; - ctx->state[3] = 0xA54FF53A; - ctx->state[4] = 0x510E527F; - ctx->state[5] = 0x9B05688C; - ctx->state[6] = 0x1F83D9AB; - ctx->state[7] = 0x5BE0CD19; - } - else - { - /* SHA-224 */ - ctx->state[0] = 0xC1059ED8; - ctx->state[1] = 0x367CD507; - ctx->state[2] = 0x3070DD17; - ctx->state[3] = 0xF70E5939; - ctx->state[4] = 0xFFC00B31; - ctx->state[5] = 0x68581511; - ctx->state[6] = 0x64F98FA7; - ctx->state[7] = 0xBEFA4FA4; - } - - ctx->is224 = is224; -} - -void sha2_process( sha2_context *ctx, const unsigned char data[64] ) -{ - uint32_t temp1, temp2, W[64]; - uint32_t A, B, C, D, E, F, G, H; - - GET_UINT32_BE( W[ 0], data, 0 ); - GET_UINT32_BE( W[ 1], data, 4 ); - GET_UINT32_BE( W[ 2], data, 8 ); - GET_UINT32_BE( W[ 3], data, 12 ); - GET_UINT32_BE( W[ 4], data, 16 ); - GET_UINT32_BE( W[ 5], data, 20 ); - GET_UINT32_BE( W[ 6], data, 24 ); - GET_UINT32_BE( W[ 7], data, 28 ); - GET_UINT32_BE( W[ 8], data, 32 ); - GET_UINT32_BE( W[ 9], data, 36 ); - GET_UINT32_BE( W[10], data, 40 ); - GET_UINT32_BE( W[11], data, 44 ); - GET_UINT32_BE( W[12], data, 48 ); - GET_UINT32_BE( W[13], data, 52 ); - GET_UINT32_BE( W[14], data, 56 ); - GET_UINT32_BE( W[15], data, 60 ); - -#define SHR(x,n) ((x & 0xFFFFFFFF) >> n) -#define ROTR(x,n) (SHR(x,n) | (x << (32 - n))) - -#define S0(x) (ROTR(x, 7) ^ ROTR(x,18) ^ SHR(x, 3)) -#define S1(x) (ROTR(x,17) ^ ROTR(x,19) ^ SHR(x,10)) - -#define S2(x) (ROTR(x, 2) ^ ROTR(x,13) ^ ROTR(x,22)) -#define S3(x) (ROTR(x, 6) ^ ROTR(x,11) ^ ROTR(x,25)) - -#define F0(x,y,z) ((x & y) | (z & (x | y))) -#define F1(x,y,z) (z ^ (x & (y ^ z))) - -#define R(t) \ -( \ - W[t] = S1(W[t - 2]) + W[t - 7] + \ - S0(W[t - 15]) + W[t - 16] \ -) - -#define P(a,b,c,d,e,f,g,h,x,K) \ -{ \ - temp1 = h + S3(e) + F1(e,f,g) + K + x; \ - temp2 = S2(a) + F0(a,b,c); \ - d += temp1; h = temp1 + temp2; \ -} - - A = ctx->state[0]; - B = ctx->state[1]; - C = ctx->state[2]; - D = ctx->state[3]; - E = ctx->state[4]; - F = ctx->state[5]; - G = ctx->state[6]; - H = ctx->state[7]; - - P( A, B, C, D, E, F, G, H, W[ 0], 0x428A2F98 ); - P( H, A, B, C, D, E, F, G, W[ 1], 0x71374491 ); - P( G, H, A, B, C, D, E, F, W[ 2], 0xB5C0FBCF ); - P( F, G, H, A, B, C, D, E, W[ 3], 0xE9B5DBA5 ); - P( E, F, G, H, A, B, C, D, W[ 4], 0x3956C25B ); - P( D, E, F, G, H, A, B, C, W[ 5], 0x59F111F1 ); - P( C, D, E, F, G, H, A, B, W[ 6], 0x923F82A4 ); - P( B, C, D, E, F, G, H, A, W[ 7], 0xAB1C5ED5 ); - P( A, B, C, D, E, F, G, H, W[ 8], 0xD807AA98 ); - P( H, A, B, C, D, E, F, G, W[ 9], 0x12835B01 ); - P( G, H, A, B, C, D, E, F, W[10], 0x243185BE ); - P( F, G, H, A, B, C, D, E, W[11], 0x550C7DC3 ); - P( E, F, G, H, A, B, C, D, W[12], 0x72BE5D74 ); - P( D, E, F, G, H, A, B, C, W[13], 0x80DEB1FE ); - P( C, D, E, F, G, H, A, B, W[14], 0x9BDC06A7 ); - P( B, C, D, E, F, G, H, A, W[15], 0xC19BF174 ); - P( A, B, C, D, E, F, G, H, R(16), 0xE49B69C1 ); - P( H, A, B, C, D, E, F, G, R(17), 0xEFBE4786 ); - P( G, H, A, B, C, D, E, F, R(18), 0x0FC19DC6 ); - P( F, G, H, A, B, C, D, E, R(19), 0x240CA1CC ); - P( E, F, G, H, A, B, C, D, R(20), 0x2DE92C6F ); - P( D, E, F, G, H, A, B, C, R(21), 0x4A7484AA ); - P( C, D, E, F, G, H, A, B, R(22), 0x5CB0A9DC ); - P( B, C, D, E, F, G, H, A, R(23), 0x76F988DA ); - P( A, B, C, D, E, F, G, H, R(24), 0x983E5152 ); - P( H, A, B, C, D, E, F, G, R(25), 0xA831C66D ); - P( G, H, A, B, C, D, E, F, R(26), 0xB00327C8 ); - P( F, G, H, A, B, C, D, E, R(27), 0xBF597FC7 ); - P( E, F, G, H, A, B, C, D, R(28), 0xC6E00BF3 ); - P( D, E, F, G, H, A, B, C, R(29), 0xD5A79147 ); - P( C, D, E, F, G, H, A, B, R(30), 0x06CA6351 ); - P( B, C, D, E, F, G, H, A, R(31), 0x14292967 ); - P( A, B, C, D, E, F, G, H, R(32), 0x27B70A85 ); - P( H, A, B, C, D, E, F, G, R(33), 0x2E1B2138 ); - P( G, H, A, B, C, D, E, F, R(34), 0x4D2C6DFC ); - P( F, G, H, A, B, C, D, E, R(35), 0x53380D13 ); - P( E, F, G, H, A, B, C, D, R(36), 0x650A7354 ); - P( D, E, F, G, H, A, B, C, R(37), 0x766A0ABB ); - P( C, D, E, F, G, H, A, B, R(38), 0x81C2C92E ); - P( B, C, D, E, F, G, H, A, R(39), 0x92722C85 ); - P( A, B, C, D, E, F, G, H, R(40), 0xA2BFE8A1 ); - P( H, A, B, C, D, E, F, G, R(41), 0xA81A664B ); - P( G, H, A, B, C, D, E, F, R(42), 0xC24B8B70 ); - P( F, G, H, A, B, C, D, E, R(43), 0xC76C51A3 ); - P( E, F, G, H, A, B, C, D, R(44), 0xD192E819 ); - P( D, E, F, G, H, A, B, C, R(45), 0xD6990624 ); - P( C, D, E, F, G, H, A, B, R(46), 0xF40E3585 ); - P( B, C, D, E, F, G, H, A, R(47), 0x106AA070 ); - P( A, B, C, D, E, F, G, H, R(48), 0x19A4C116 ); - P( H, A, B, C, D, E, F, G, R(49), 0x1E376C08 ); - P( G, H, A, B, C, D, E, F, R(50), 0x2748774C ); - P( F, G, H, A, B, C, D, E, R(51), 0x34B0BCB5 ); - P( E, F, G, H, A, B, C, D, R(52), 0x391C0CB3 ); - P( D, E, F, G, H, A, B, C, R(53), 0x4ED8AA4A ); - P( C, D, E, F, G, H, A, B, R(54), 0x5B9CCA4F ); - P( B, C, D, E, F, G, H, A, R(55), 0x682E6FF3 ); - P( A, B, C, D, E, F, G, H, R(56), 0x748F82EE ); - P( H, A, B, C, D, E, F, G, R(57), 0x78A5636F ); - P( G, H, A, B, C, D, E, F, R(58), 0x84C87814 ); - P( F, G, H, A, B, C, D, E, R(59), 0x8CC70208 ); - P( E, F, G, H, A, B, C, D, R(60), 0x90BEFFFA ); - P( D, E, F, G, H, A, B, C, R(61), 0xA4506CEB ); - P( C, D, E, F, G, H, A, B, R(62), 0xBEF9A3F7 ); - P( B, C, D, E, F, G, H, A, R(63), 0xC67178F2 ); - - ctx->state[0] += A; - ctx->state[1] += B; - ctx->state[2] += C; - ctx->state[3] += D; - ctx->state[4] += E; - ctx->state[5] += F; - ctx->state[6] += G; - ctx->state[7] += H; -} - -/* - * SHA-256 process buffer - */ -void sha2_update( sha2_context *ctx, const unsigned char *input, size_t ilen ) -{ - size_t fill; - uint32_t left; - - if( ilen <= 0 ) - return; - - left = ctx->total[0] & 0x3F; - fill = 64 - left; - - ctx->total[0] += (uint32_t) ilen; - ctx->total[0] &= 0xFFFFFFFF; - - if( ctx->total[0] < (uint32_t) ilen ) - ctx->total[1]++; - - if( left && ilen >= fill ) - { - memcpy( (void *) (ctx->buffer + left), input, fill ); - sha2_process( ctx, ctx->buffer ); - input += fill; - ilen -= fill; - left = 0; - } - - while( ilen >= 64 ) - { - sha2_process( ctx, input ); - input += 64; - ilen -= 64; - } - - if( ilen > 0 ) - memcpy( (void *) (ctx->buffer + left), input, ilen ); -} - -static const unsigned char sha2_padding[64] = -{ - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -/* - * SHA-256 final digest - */ -void sha2_finish( sha2_context *ctx, unsigned char output[32] ) -{ - uint32_t last, padn; - uint32_t high, low; - unsigned char msglen[8]; - - high = ( ctx->total[0] >> 29 ) - | ( ctx->total[1] << 3 ); - low = ( ctx->total[0] << 3 ); - - PUT_UINT32_BE( high, msglen, 0 ); - PUT_UINT32_BE( low, msglen, 4 ); - - last = ctx->total[0] & 0x3F; - padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last ); - - sha2_update( ctx, sha2_padding, padn ); - sha2_update( ctx, msglen, 8 ); - - PUT_UINT32_BE( ctx->state[0], output, 0 ); - PUT_UINT32_BE( ctx->state[1], output, 4 ); - PUT_UINT32_BE( ctx->state[2], output, 8 ); - PUT_UINT32_BE( ctx->state[3], output, 12 ); - PUT_UINT32_BE( ctx->state[4], output, 16 ); - PUT_UINT32_BE( ctx->state[5], output, 20 ); - PUT_UINT32_BE( ctx->state[6], output, 24 ); - - if( ctx->is224 == 0 ) - PUT_UINT32_BE( ctx->state[7], output, 28 ); -} - -#endif /* !POLARSSL_SHA2_ALT */ - -/* - * output = SHA-256( input buffer ) - */ -void sha2( const unsigned char *input, size_t ilen, - unsigned char output[32], int is224 ) -{ - sha2_context ctx; - - sha2_starts( &ctx, is224 ); - sha2_update( &ctx, input, ilen ); - sha2_finish( &ctx, output ); - - memset( &ctx, 0, sizeof( sha2_context ) ); -} - -#if defined(POLARSSL_FS_IO) -/* - * output = SHA-256( file contents ) - */ -int sha2_file( const char *path, unsigned char output[32], int is224 ) -{ - FILE *f; - size_t n; - sha2_context ctx; - unsigned char buf[1024]; - - if( ( f = fopen( path, "rb" ) ) == NULL ) - return( POLARSSL_ERR_SHA2_FILE_IO_ERROR ); - - sha2_starts( &ctx, is224 ); - - while( ( n = fread( buf, 1, sizeof( buf ), f ) ) > 0 ) - sha2_update( &ctx, buf, n ); - - sha2_finish( &ctx, output ); - - memset( &ctx, 0, sizeof( sha2_context ) ); - - if( ferror( f ) != 0 ) - { - fclose( f ); - return( POLARSSL_ERR_SHA2_FILE_IO_ERROR ); - } - - fclose( f ); - return( 0 ); -} -#endif /* POLARSSL_FS_IO */ - -/* - * SHA-256 HMAC context setup - */ -void sha2_hmac_starts( sha2_context *ctx, const unsigned char *key, size_t keylen, - int is224 ) -{ - size_t i; - unsigned char sum[32]; - - if( keylen > 64 ) - { - sha2( key, keylen, sum, is224 ); - keylen = ( is224 ) ? 28 : 32; - key = sum; - } - - memset( ctx->ipad, 0x36, 64 ); - memset( ctx->opad, 0x5C, 64 ); - - for( i = 0; i < keylen; i++ ) - { - ctx->ipad[i] = (unsigned char)( ctx->ipad[i] ^ key[i] ); - ctx->opad[i] = (unsigned char)( ctx->opad[i] ^ key[i] ); - } - - sha2_starts( ctx, is224 ); - sha2_update( ctx, ctx->ipad, 64 ); - - memset( sum, 0, sizeof( sum ) ); -} - -/* - * SHA-256 HMAC process buffer - */ -void sha2_hmac_update( sha2_context *ctx, const unsigned char *input, size_t ilen ) -{ - sha2_update( ctx, input, ilen ); -} - -/* - * SHA-256 HMAC final digest - */ -void sha2_hmac_finish( sha2_context *ctx, unsigned char output[32] ) -{ - int is224, hlen; - unsigned char tmpbuf[32]; - - is224 = ctx->is224; - hlen = ( is224 == 0 ) ? 32 : 28; - - sha2_finish( ctx, tmpbuf ); - sha2_starts( ctx, is224 ); - sha2_update( ctx, ctx->opad, 64 ); - sha2_update( ctx, tmpbuf, hlen ); - sha2_finish( ctx, output ); - - memset( tmpbuf, 0, sizeof( tmpbuf ) ); -} - -/* - * SHA-256 HMAC context reset - */ -void sha2_hmac_reset( sha2_context *ctx ) -{ - sha2_starts( ctx, ctx->is224 ); - sha2_update( ctx, ctx->ipad, 64 ); -} - -/* - * output = HMAC-SHA-256( hmac key, input buffer ) - */ -void sha2_hmac( const unsigned char *key, size_t keylen, - const unsigned char *input, size_t ilen, - unsigned char output[32], int is224 ) -{ - sha2_context ctx; - - sha2_hmac_starts( &ctx, key, keylen, is224 ); - sha2_hmac_update( &ctx, input, ilen ); - sha2_hmac_finish( &ctx, output ); - - memset( &ctx, 0, sizeof( sha2_context ) ); -} - -#if defined(POLARSSL_SELF_TEST) -/* - * FIPS-180-2 test vectors - */ -static unsigned char sha2_test_buf[3][57] = -{ - { "abc" }, - { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" }, - { "" } -}; - -static const int sha2_test_buflen[3] = -{ - 3, 56, 1000 -}; - -static const unsigned char sha2_test_sum[6][32] = -{ - /* - * SHA-224 test vectors - */ - { 0x23, 0x09, 0x7D, 0x22, 0x34, 0x05, 0xD8, 0x22, - 0x86, 0x42, 0xA4, 0x77, 0xBD, 0xA2, 0x55, 0xB3, - 0x2A, 0xAD, 0xBC, 0xE4, 0xBD, 0xA0, 0xB3, 0xF7, - 0xE3, 0x6C, 0x9D, 0xA7 }, - { 0x75, 0x38, 0x8B, 0x16, 0x51, 0x27, 0x76, 0xCC, - 0x5D, 0xBA, 0x5D, 0xA1, 0xFD, 0x89, 0x01, 0x50, - 0xB0, 0xC6, 0x45, 0x5C, 0xB4, 0xF5, 0x8B, 0x19, - 0x52, 0x52, 0x25, 0x25 }, - { 0x20, 0x79, 0x46, 0x55, 0x98, 0x0C, 0x91, 0xD8, - 0xBB, 0xB4, 0xC1, 0xEA, 0x97, 0x61, 0x8A, 0x4B, - 0xF0, 0x3F, 0x42, 0x58, 0x19, 0x48, 0xB2, 0xEE, - 0x4E, 0xE7, 0xAD, 0x67 }, - - /* - * SHA-256 test vectors - */ - { 0xBA, 0x78, 0x16, 0xBF, 0x8F, 0x01, 0xCF, 0xEA, - 0x41, 0x41, 0x40, 0xDE, 0x5D, 0xAE, 0x22, 0x23, - 0xB0, 0x03, 0x61, 0xA3, 0x96, 0x17, 0x7A, 0x9C, - 0xB4, 0x10, 0xFF, 0x61, 0xF2, 0x00, 0x15, 0xAD }, - { 0x24, 0x8D, 0x6A, 0x61, 0xD2, 0x06, 0x38, 0xB8, - 0xE5, 0xC0, 0x26, 0x93, 0x0C, 0x3E, 0x60, 0x39, - 0xA3, 0x3C, 0xE4, 0x59, 0x64, 0xFF, 0x21, 0x67, - 0xF6, 0xEC, 0xED, 0xD4, 0x19, 0xDB, 0x06, 0xC1 }, - { 0xCD, 0xC7, 0x6E, 0x5C, 0x99, 0x14, 0xFB, 0x92, - 0x81, 0xA1, 0xC7, 0xE2, 0x84, 0xD7, 0x3E, 0x67, - 0xF1, 0x80, 0x9A, 0x48, 0xA4, 0x97, 0x20, 0x0E, - 0x04, 0x6D, 0x39, 0xCC, 0xC7, 0x11, 0x2C, 0xD0 } -}; - -/* - * RFC 4231 test vectors - */ -static unsigned char sha2_hmac_test_key[7][26] = -{ - { "\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B" - "\x0B\x0B\x0B\x0B" }, - { "Jefe" }, - { "\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA" - "\xAA\xAA\xAA\xAA" }, - { "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10" - "\x11\x12\x13\x14\x15\x16\x17\x18\x19" }, - { "\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C" - "\x0C\x0C\x0C\x0C" }, - { "" }, /* 0xAA 131 times */ - { "" } -}; - -static const int sha2_hmac_test_keylen[7] = -{ - 20, 4, 20, 25, 20, 131, 131 -}; - -static unsigned char sha2_hmac_test_buf[7][153] = -{ - { "Hi There" }, - { "what do ya want for nothing?" }, - { "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD" - "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD" - "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD" - "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD" - "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD" }, - { "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" - "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" - "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" - "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" - "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" }, - { "Test With Truncation" }, - { "Test Using Larger Than Block-Size Key - Hash Key First" }, - { "This is a test using a larger than block-size key " - "and a larger than block-size data. The key needs to " - "be hashed before being used by the HMAC algorithm." } -}; - -static const int sha2_hmac_test_buflen[7] = -{ - 8, 28, 50, 50, 20, 54, 152 -}; - -static const unsigned char sha2_hmac_test_sum[14][32] = -{ - /* - * HMAC-SHA-224 test vectors - */ - { 0x89, 0x6F, 0xB1, 0x12, 0x8A, 0xBB, 0xDF, 0x19, - 0x68, 0x32, 0x10, 0x7C, 0xD4, 0x9D, 0xF3, 0x3F, - 0x47, 0xB4, 0xB1, 0x16, 0x99, 0x12, 0xBA, 0x4F, - 0x53, 0x68, 0x4B, 0x22 }, - { 0xA3, 0x0E, 0x01, 0x09, 0x8B, 0xC6, 0xDB, 0xBF, - 0x45, 0x69, 0x0F, 0x3A, 0x7E, 0x9E, 0x6D, 0x0F, - 0x8B, 0xBE, 0xA2, 0xA3, 0x9E, 0x61, 0x48, 0x00, - 0x8F, 0xD0, 0x5E, 0x44 }, - { 0x7F, 0xB3, 0xCB, 0x35, 0x88, 0xC6, 0xC1, 0xF6, - 0xFF, 0xA9, 0x69, 0x4D, 0x7D, 0x6A, 0xD2, 0x64, - 0x93, 0x65, 0xB0, 0xC1, 0xF6, 0x5D, 0x69, 0xD1, - 0xEC, 0x83, 0x33, 0xEA }, - { 0x6C, 0x11, 0x50, 0x68, 0x74, 0x01, 0x3C, 0xAC, - 0x6A, 0x2A, 0xBC, 0x1B, 0xB3, 0x82, 0x62, 0x7C, - 0xEC, 0x6A, 0x90, 0xD8, 0x6E, 0xFC, 0x01, 0x2D, - 0xE7, 0xAF, 0xEC, 0x5A }, - { 0x0E, 0x2A, 0xEA, 0x68, 0xA9, 0x0C, 0x8D, 0x37, - 0xC9, 0x88, 0xBC, 0xDB, 0x9F, 0xCA, 0x6F, 0xA8 }, - { 0x95, 0xE9, 0xA0, 0xDB, 0x96, 0x20, 0x95, 0xAD, - 0xAE, 0xBE, 0x9B, 0x2D, 0x6F, 0x0D, 0xBC, 0xE2, - 0xD4, 0x99, 0xF1, 0x12, 0xF2, 0xD2, 0xB7, 0x27, - 0x3F, 0xA6, 0x87, 0x0E }, - { 0x3A, 0x85, 0x41, 0x66, 0xAC, 0x5D, 0x9F, 0x02, - 0x3F, 0x54, 0xD5, 0x17, 0xD0, 0xB3, 0x9D, 0xBD, - 0x94, 0x67, 0x70, 0xDB, 0x9C, 0x2B, 0x95, 0xC9, - 0xF6, 0xF5, 0x65, 0xD1 }, - - /* - * HMAC-SHA-256 test vectors - */ - { 0xB0, 0x34, 0x4C, 0x61, 0xD8, 0xDB, 0x38, 0x53, - 0x5C, 0xA8, 0xAF, 0xCE, 0xAF, 0x0B, 0xF1, 0x2B, - 0x88, 0x1D, 0xC2, 0x00, 0xC9, 0x83, 0x3D, 0xA7, - 0x26, 0xE9, 0x37, 0x6C, 0x2E, 0x32, 0xCF, 0xF7 }, - { 0x5B, 0xDC, 0xC1, 0x46, 0xBF, 0x60, 0x75, 0x4E, - 0x6A, 0x04, 0x24, 0x26, 0x08, 0x95, 0x75, 0xC7, - 0x5A, 0x00, 0x3F, 0x08, 0x9D, 0x27, 0x39, 0x83, - 0x9D, 0xEC, 0x58, 0xB9, 0x64, 0xEC, 0x38, 0x43 }, - { 0x77, 0x3E, 0xA9, 0x1E, 0x36, 0x80, 0x0E, 0x46, - 0x85, 0x4D, 0xB8, 0xEB, 0xD0, 0x91, 0x81, 0xA7, - 0x29, 0x59, 0x09, 0x8B, 0x3E, 0xF8, 0xC1, 0x22, - 0xD9, 0x63, 0x55, 0x14, 0xCE, 0xD5, 0x65, 0xFE }, - { 0x82, 0x55, 0x8A, 0x38, 0x9A, 0x44, 0x3C, 0x0E, - 0xA4, 0xCC, 0x81, 0x98, 0x99, 0xF2, 0x08, 0x3A, - 0x85, 0xF0, 0xFA, 0xA3, 0xE5, 0x78, 0xF8, 0x07, - 0x7A, 0x2E, 0x3F, 0xF4, 0x67, 0x29, 0x66, 0x5B }, - { 0xA3, 0xB6, 0x16, 0x74, 0x73, 0x10, 0x0E, 0xE0, - 0x6E, 0x0C, 0x79, 0x6C, 0x29, 0x55, 0x55, 0x2B }, - { 0x60, 0xE4, 0x31, 0x59, 0x1E, 0xE0, 0xB6, 0x7F, - 0x0D, 0x8A, 0x26, 0xAA, 0xCB, 0xF5, 0xB7, 0x7F, - 0x8E, 0x0B, 0xC6, 0x21, 0x37, 0x28, 0xC5, 0x14, - 0x05, 0x46, 0x04, 0x0F, 0x0E, 0xE3, 0x7F, 0x54 }, - { 0x9B, 0x09, 0xFF, 0xA7, 0x1B, 0x94, 0x2F, 0xCB, - 0x27, 0x63, 0x5F, 0xBC, 0xD5, 0xB0, 0xE9, 0x44, - 0xBF, 0xDC, 0x63, 0x64, 0x4F, 0x07, 0x13, 0x93, - 0x8A, 0x7F, 0x51, 0x53, 0x5C, 0x3A, 0x35, 0xE2 } -}; - -/* - * Checkup routine - */ -int sha2_self_test( int verbose ) -{ - int i, j, k, buflen; - unsigned char buf[1024]; - unsigned char sha2sum[32]; - sha2_context ctx; - - for( i = 0; i < 6; i++ ) - { - j = i % 3; - k = i < 3; - - if( verbose != 0 ) - printf( " SHA-%d test #%d: ", 256 - k * 32, j + 1 ); - - sha2_starts( &ctx, k ); - - if( j == 2 ) - { - memset( buf, 'a', buflen = 1000 ); - - for( j = 0; j < 1000; j++ ) - sha2_update( &ctx, buf, buflen ); - } - else - sha2_update( &ctx, sha2_test_buf[j], - sha2_test_buflen[j] ); - - sha2_finish( &ctx, sha2sum ); - - if( memcmp( sha2sum, sha2_test_sum[i], 32 - k * 4 ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( verbose != 0 ) - printf( "passed\n" ); - } - - if( verbose != 0 ) - printf( "\n" ); - - for( i = 0; i < 14; i++ ) - { - j = i % 7; - k = i < 7; - - if( verbose != 0 ) - printf( " HMAC-SHA-%d test #%d: ", 256 - k * 32, j + 1 ); - - if( j == 5 || j == 6 ) - { - memset( buf, '\xAA', buflen = 131 ); - sha2_hmac_starts( &ctx, buf, buflen, k ); - } - else - sha2_hmac_starts( &ctx, sha2_hmac_test_key[j], - sha2_hmac_test_keylen[j], k ); - - sha2_hmac_update( &ctx, sha2_hmac_test_buf[j], - sha2_hmac_test_buflen[j] ); - - sha2_hmac_finish( &ctx, sha2sum ); - - buflen = ( j == 4 ) ? 16 : 32 - k * 4; - - if( memcmp( sha2sum, sha2_hmac_test_sum[i], buflen ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( verbose != 0 ) - printf( "passed\n" ); - } - - if( verbose != 0 ) - printf( "\n" ); - - return( 0 ); -} - -#endif - -#endif diff --git a/lib/libpolarssl/source/sha4.c b/lib/libpolarssl/source/sha4.c deleted file mode 100644 index ebdc997..0000000 --- a/lib/libpolarssl/source/sha4.c +++ /dev/null @@ -1,762 +0,0 @@ -/* - * FIPS-180-2 compliant SHA-384/512 implementation - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved - * - * This file is part of mbed TLS (https://polarssl.org) - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ -/* - * The SHA-512 Secure Hash Standard was published by NIST in 2002. - * - * http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf - */ - -#include "polarssl/config.h" - -#if defined(POLARSSL_SHA4_C) - -#include "polarssl/sha4.h" - -#if defined(POLARSSL_FS_IO) || defined(POLARSSL_SELF_TEST) -#include -#endif - -#if !defined(POLARSSL_SHA4_ALT) - -/* Implementation that should never be optimized out by the compiler */ -static void polarssl_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - -/* - * 64-bit integer manipulation macros (big endian) - */ -#ifndef GET_UINT64_BE -#define GET_UINT64_BE(n,b,i) \ -{ \ - (n) = ( (uint64_t) (b)[(i) ] << 56 ) \ - | ( (uint64_t) (b)[(i) + 1] << 48 ) \ - | ( (uint64_t) (b)[(i) + 2] << 40 ) \ - | ( (uint64_t) (b)[(i) + 3] << 32 ) \ - | ( (uint64_t) (b)[(i) + 4] << 24 ) \ - | ( (uint64_t) (b)[(i) + 5] << 16 ) \ - | ( (uint64_t) (b)[(i) + 6] << 8 ) \ - | ( (uint64_t) (b)[(i) + 7] ); \ -} -#endif - -#ifndef PUT_UINT64_BE -#define PUT_UINT64_BE(n,b,i) \ -{ \ - (b)[(i) ] = (unsigned char) ( (n) >> 56 ); \ - (b)[(i) + 1] = (unsigned char) ( (n) >> 48 ); \ - (b)[(i) + 2] = (unsigned char) ( (n) >> 40 ); \ - (b)[(i) + 3] = (unsigned char) ( (n) >> 32 ); \ - (b)[(i) + 4] = (unsigned char) ( (n) >> 24 ); \ - (b)[(i) + 5] = (unsigned char) ( (n) >> 16 ); \ - (b)[(i) + 6] = (unsigned char) ( (n) >> 8 ); \ - (b)[(i) + 7] = (unsigned char) ( (n) ); \ -} -#endif - -/* - * Round constants - */ -static const uint64_t K[80] = -{ - UL64(0x428A2F98D728AE22), UL64(0x7137449123EF65CD), - UL64(0xB5C0FBCFEC4D3B2F), UL64(0xE9B5DBA58189DBBC), - UL64(0x3956C25BF348B538), UL64(0x59F111F1B605D019), - UL64(0x923F82A4AF194F9B), UL64(0xAB1C5ED5DA6D8118), - UL64(0xD807AA98A3030242), UL64(0x12835B0145706FBE), - UL64(0x243185BE4EE4B28C), UL64(0x550C7DC3D5FFB4E2), - UL64(0x72BE5D74F27B896F), UL64(0x80DEB1FE3B1696B1), - UL64(0x9BDC06A725C71235), UL64(0xC19BF174CF692694), - UL64(0xE49B69C19EF14AD2), UL64(0xEFBE4786384F25E3), - UL64(0x0FC19DC68B8CD5B5), UL64(0x240CA1CC77AC9C65), - UL64(0x2DE92C6F592B0275), UL64(0x4A7484AA6EA6E483), - UL64(0x5CB0A9DCBD41FBD4), UL64(0x76F988DA831153B5), - UL64(0x983E5152EE66DFAB), UL64(0xA831C66D2DB43210), - UL64(0xB00327C898FB213F), UL64(0xBF597FC7BEEF0EE4), - UL64(0xC6E00BF33DA88FC2), UL64(0xD5A79147930AA725), - UL64(0x06CA6351E003826F), UL64(0x142929670A0E6E70), - UL64(0x27B70A8546D22FFC), UL64(0x2E1B21385C26C926), - UL64(0x4D2C6DFC5AC42AED), UL64(0x53380D139D95B3DF), - UL64(0x650A73548BAF63DE), UL64(0x766A0ABB3C77B2A8), - UL64(0x81C2C92E47EDAEE6), UL64(0x92722C851482353B), - UL64(0xA2BFE8A14CF10364), UL64(0xA81A664BBC423001), - UL64(0xC24B8B70D0F89791), UL64(0xC76C51A30654BE30), - UL64(0xD192E819D6EF5218), UL64(0xD69906245565A910), - UL64(0xF40E35855771202A), UL64(0x106AA07032BBD1B8), - UL64(0x19A4C116B8D2D0C8), UL64(0x1E376C085141AB53), - UL64(0x2748774CDF8EEB99), UL64(0x34B0BCB5E19B48A8), - UL64(0x391C0CB3C5C95A63), UL64(0x4ED8AA4AE3418ACB), - UL64(0x5B9CCA4F7763E373), UL64(0x682E6FF3D6B2B8A3), - UL64(0x748F82EE5DEFB2FC), UL64(0x78A5636F43172F60), - UL64(0x84C87814A1F0AB72), UL64(0x8CC702081A6439EC), - UL64(0x90BEFFFA23631E28), UL64(0xA4506CEBDE82BDE9), - UL64(0xBEF9A3F7B2C67915), UL64(0xC67178F2E372532B), - UL64(0xCA273ECEEA26619C), UL64(0xD186B8C721C0C207), - UL64(0xEADA7DD6CDE0EB1E), UL64(0xF57D4F7FEE6ED178), - UL64(0x06F067AA72176FBA), UL64(0x0A637DC5A2C898A6), - UL64(0x113F9804BEF90DAE), UL64(0x1B710B35131C471B), - UL64(0x28DB77F523047D84), UL64(0x32CAAB7B40C72493), - UL64(0x3C9EBE0A15C9BEBC), UL64(0x431D67C49C100D4C), - UL64(0x4CC5D4BECB3E42B6), UL64(0x597F299CFC657E2A), - UL64(0x5FCB6FAB3AD6FAEC), UL64(0x6C44198C4A475817) -}; - -/* - * SHA-512 context setup - */ -void sha4_starts( sha4_context *ctx, int is384 ) -{ - ctx->total[0] = 0; - ctx->total[1] = 0; - - if( is384 == 0 ) - { - /* SHA-512 */ - ctx->state[0] = UL64(0x6A09E667F3BCC908); - ctx->state[1] = UL64(0xBB67AE8584CAA73B); - ctx->state[2] = UL64(0x3C6EF372FE94F82B); - ctx->state[3] = UL64(0xA54FF53A5F1D36F1); - ctx->state[4] = UL64(0x510E527FADE682D1); - ctx->state[5] = UL64(0x9B05688C2B3E6C1F); - ctx->state[6] = UL64(0x1F83D9ABFB41BD6B); - ctx->state[7] = UL64(0x5BE0CD19137E2179); - } - else - { - /* SHA-384 */ - ctx->state[0] = UL64(0xCBBB9D5DC1059ED8); - ctx->state[1] = UL64(0x629A292A367CD507); - ctx->state[2] = UL64(0x9159015A3070DD17); - ctx->state[3] = UL64(0x152FECD8F70E5939); - ctx->state[4] = UL64(0x67332667FFC00B31); - ctx->state[5] = UL64(0x8EB44A8768581511); - ctx->state[6] = UL64(0xDB0C2E0D64F98FA7); - ctx->state[7] = UL64(0x47B5481DBEFA4FA4); - } - - ctx->is384 = is384; -} - -static void sha4_process( sha4_context *ctx, const unsigned char data[128] ) -{ - int i; - uint64_t temp1, temp2, W[80]; - uint64_t A, B, C, D, E, F, G, H; - -#define SHR(x,n) (x >> n) -#define ROTR(x,n) (SHR(x,n) | (x << (64 - n))) - -#define S0(x) (ROTR(x, 1) ^ ROTR(x, 8) ^ SHR(x, 7)) -#define S1(x) (ROTR(x,19) ^ ROTR(x,61) ^ SHR(x, 6)) - -#define S2(x) (ROTR(x,28) ^ ROTR(x,34) ^ ROTR(x,39)) -#define S3(x) (ROTR(x,14) ^ ROTR(x,18) ^ ROTR(x,41)) - -#define F0(x,y,z) ((x & y) | (z & (x | y))) -#define F1(x,y,z) (z ^ (x & (y ^ z))) - -#define P(a,b,c,d,e,f,g,h,x,K) \ -{ \ - temp1 = h + S3(e) + F1(e,f,g) + K + x; \ - temp2 = S2(a) + F0(a,b,c); \ - d += temp1; h = temp1 + temp2; \ -} - - for( i = 0; i < 16; i++ ) - { - GET_UINT64_BE( W[i], data, i << 3 ); - } - - for( ; i < 80; i++ ) - { - W[i] = S1(W[i - 2]) + W[i - 7] + - S0(W[i - 15]) + W[i - 16]; - } - - A = ctx->state[0]; - B = ctx->state[1]; - C = ctx->state[2]; - D = ctx->state[3]; - E = ctx->state[4]; - F = ctx->state[5]; - G = ctx->state[6]; - H = ctx->state[7]; - i = 0; - - do - { - P( A, B, C, D, E, F, G, H, W[i], K[i] ); i++; - P( H, A, B, C, D, E, F, G, W[i], K[i] ); i++; - P( G, H, A, B, C, D, E, F, W[i], K[i] ); i++; - P( F, G, H, A, B, C, D, E, W[i], K[i] ); i++; - P( E, F, G, H, A, B, C, D, W[i], K[i] ); i++; - P( D, E, F, G, H, A, B, C, W[i], K[i] ); i++; - P( C, D, E, F, G, H, A, B, W[i], K[i] ); i++; - P( B, C, D, E, F, G, H, A, W[i], K[i] ); i++; - } - while( i < 80 ); - - ctx->state[0] += A; - ctx->state[1] += B; - ctx->state[2] += C; - ctx->state[3] += D; - ctx->state[4] += E; - ctx->state[5] += F; - ctx->state[6] += G; - ctx->state[7] += H; -} - -/* - * SHA-512 process buffer - */ -void sha4_update( sha4_context *ctx, const unsigned char *input, size_t ilen ) -{ - size_t fill; - unsigned int left; - - if( ilen <= 0 ) - return; - - left = (unsigned int) (ctx->total[0] & 0x7F); - fill = 128 - left; - - ctx->total[0] += (uint64_t) ilen; - - if( ctx->total[0] < (uint64_t) ilen ) - ctx->total[1]++; - - if( left && ilen >= fill ) - { - memcpy( (void *) (ctx->buffer + left), input, fill ); - sha4_process( ctx, ctx->buffer ); - input += fill; - ilen -= fill; - left = 0; - } - - while( ilen >= 128 ) - { - sha4_process( ctx, input ); - input += 128; - ilen -= 128; - } - - if( ilen > 0 ) - memcpy( (void *) (ctx->buffer + left), input, ilen ); -} - -static const unsigned char sha4_padding[128] = -{ - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -/* - * SHA-512 final digest - */ -void sha4_finish( sha4_context *ctx, unsigned char output[64] ) -{ - size_t last, padn; - uint64_t high, low; - unsigned char msglen[16]; - - high = ( ctx->total[0] >> 61 ) - | ( ctx->total[1] << 3 ); - low = ( ctx->total[0] << 3 ); - - PUT_UINT64_BE( high, msglen, 0 ); - PUT_UINT64_BE( low, msglen, 8 ); - - last = (size_t)( ctx->total[0] & 0x7F ); - padn = ( last < 112 ) ? ( 112 - last ) : ( 240 - last ); - - sha4_update( ctx, sha4_padding, padn ); - sha4_update( ctx, msglen, 16 ); - - PUT_UINT64_BE( ctx->state[0], output, 0 ); - PUT_UINT64_BE( ctx->state[1], output, 8 ); - PUT_UINT64_BE( ctx->state[2], output, 16 ); - PUT_UINT64_BE( ctx->state[3], output, 24 ); - PUT_UINT64_BE( ctx->state[4], output, 32 ); - PUT_UINT64_BE( ctx->state[5], output, 40 ); - - if( ctx->is384 == 0 ) - { - PUT_UINT64_BE( ctx->state[6], output, 48 ); - PUT_UINT64_BE( ctx->state[7], output, 56 ); - } -} - -#endif /* !POLARSSL_SHA4_ALT */ - -/* - * output = SHA-512( input buffer ) - */ -void sha4( const unsigned char *input, size_t ilen, - unsigned char output[64], int is384 ) -{ - sha4_context ctx; - - sha4_starts( &ctx, is384 ); - sha4_update( &ctx, input, ilen ); - sha4_finish( &ctx, output ); - - polarssl_zeroize( &ctx, sizeof( sha4_context ) ); -} - -#if defined(POLARSSL_FS_IO) -/* - * output = SHA-512( file contents ) - */ -int sha4_file( const char *path, unsigned char output[64], int is384 ) -{ - FILE *f; - size_t n; - sha4_context ctx; - unsigned char buf[1024]; - - if( ( f = fopen( path, "rb" ) ) == NULL ) - return( POLARSSL_ERR_SHA4_FILE_IO_ERROR ); - - sha4_starts( &ctx, is384 ); - - while( ( n = fread( buf, 1, sizeof( buf ), f ) ) > 0 ) - sha4_update( &ctx, buf, n ); - - sha4_finish( &ctx, output ); - - polarssl_zeroize( &ctx, sizeof( sha4_context ) ); - - if( ferror( f ) != 0 ) - { - fclose( f ); - return( POLARSSL_ERR_SHA4_FILE_IO_ERROR ); - } - - fclose( f ); - return( 0 ); -} -#endif /* POLARSSL_FS_IO */ - -/* - * SHA-512 HMAC context setup - */ -void sha4_hmac_starts( sha4_context *ctx, const unsigned char *key, size_t keylen, - int is384 ) -{ - size_t i; - unsigned char sum[64]; - - if( keylen > 128 ) - { - sha4( key, keylen, sum, is384 ); - keylen = ( is384 ) ? 48 : 64; - key = sum; - } - - memset( ctx->ipad, 0x36, 128 ); - memset( ctx->opad, 0x5C, 128 ); - - for( i = 0; i < keylen; i++ ) - { - ctx->ipad[i] = (unsigned char)( ctx->ipad[i] ^ key[i] ); - ctx->opad[i] = (unsigned char)( ctx->opad[i] ^ key[i] ); - } - - sha4_starts( ctx, is384 ); - sha4_update( ctx, ctx->ipad, 128 ); - - polarssl_zeroize( sum, sizeof( sum ) ); -} - -/* - * SHA-512 HMAC process buffer - */ -void sha4_hmac_update( sha4_context *ctx, - const unsigned char *input, size_t ilen ) -{ - sha4_update( ctx, input, ilen ); -} - -/* - * SHA-512 HMAC final digest - */ -void sha4_hmac_finish( sha4_context *ctx, unsigned char output[64] ) -{ - int is384, hlen; - unsigned char tmpbuf[64]; - - is384 = ctx->is384; - hlen = ( is384 == 0 ) ? 64 : 48; - - sha4_finish( ctx, tmpbuf ); - sha4_starts( ctx, is384 ); - sha4_update( ctx, ctx->opad, 128 ); - sha4_update( ctx, tmpbuf, hlen ); - sha4_finish( ctx, output ); - - polarssl_zeroize( tmpbuf, sizeof( tmpbuf ) ); -} - -/* - * SHA-512 HMAC context reset - */ -void sha4_hmac_reset( sha4_context *ctx ) -{ - sha4_starts( ctx, ctx->is384 ); - sha4_update( ctx, ctx->ipad, 128 ); -} - -/* - * output = HMAC-SHA-512( hmac key, input buffer ) - */ -void sha4_hmac( const unsigned char *key, size_t keylen, - const unsigned char *input, size_t ilen, - unsigned char output[64], int is384 ) -{ - sha4_context ctx; - - sha4_hmac_starts( &ctx, key, keylen, is384 ); - sha4_hmac_update( &ctx, input, ilen ); - sha4_hmac_finish( &ctx, output ); - - polarssl_zeroize( &ctx, sizeof( sha4_context ) ); -} - -#if defined(POLARSSL_SELF_TEST) - -/* - * FIPS-180-2 test vectors - */ -static unsigned char sha4_test_buf[3][113] = -{ - { "abc" }, - { "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn" - "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu" }, - { "" } -}; - -static const int sha4_test_buflen[3] = -{ - 3, 112, 1000 -}; - -static const unsigned char sha4_test_sum[6][64] = -{ - /* - * SHA-384 test vectors - */ - { 0xCB, 0x00, 0x75, 0x3F, 0x45, 0xA3, 0x5E, 0x8B, - 0xB5, 0xA0, 0x3D, 0x69, 0x9A, 0xC6, 0x50, 0x07, - 0x27, 0x2C, 0x32, 0xAB, 0x0E, 0xDE, 0xD1, 0x63, - 0x1A, 0x8B, 0x60, 0x5A, 0x43, 0xFF, 0x5B, 0xED, - 0x80, 0x86, 0x07, 0x2B, 0xA1, 0xE7, 0xCC, 0x23, - 0x58, 0xBA, 0xEC, 0xA1, 0x34, 0xC8, 0x25, 0xA7 }, - { 0x09, 0x33, 0x0C, 0x33, 0xF7, 0x11, 0x47, 0xE8, - 0x3D, 0x19, 0x2F, 0xC7, 0x82, 0xCD, 0x1B, 0x47, - 0x53, 0x11, 0x1B, 0x17, 0x3B, 0x3B, 0x05, 0xD2, - 0x2F, 0xA0, 0x80, 0x86, 0xE3, 0xB0, 0xF7, 0x12, - 0xFC, 0xC7, 0xC7, 0x1A, 0x55, 0x7E, 0x2D, 0xB9, - 0x66, 0xC3, 0xE9, 0xFA, 0x91, 0x74, 0x60, 0x39 }, - { 0x9D, 0x0E, 0x18, 0x09, 0x71, 0x64, 0x74, 0xCB, - 0x08, 0x6E, 0x83, 0x4E, 0x31, 0x0A, 0x4A, 0x1C, - 0xED, 0x14, 0x9E, 0x9C, 0x00, 0xF2, 0x48, 0x52, - 0x79, 0x72, 0xCE, 0xC5, 0x70, 0x4C, 0x2A, 0x5B, - 0x07, 0xB8, 0xB3, 0xDC, 0x38, 0xEC, 0xC4, 0xEB, - 0xAE, 0x97, 0xDD, 0xD8, 0x7F, 0x3D, 0x89, 0x85 }, - - /* - * SHA-512 test vectors - */ - { 0xDD, 0xAF, 0x35, 0xA1, 0x93, 0x61, 0x7A, 0xBA, - 0xCC, 0x41, 0x73, 0x49, 0xAE, 0x20, 0x41, 0x31, - 0x12, 0xE6, 0xFA, 0x4E, 0x89, 0xA9, 0x7E, 0xA2, - 0x0A, 0x9E, 0xEE, 0xE6, 0x4B, 0x55, 0xD3, 0x9A, - 0x21, 0x92, 0x99, 0x2A, 0x27, 0x4F, 0xC1, 0xA8, - 0x36, 0xBA, 0x3C, 0x23, 0xA3, 0xFE, 0xEB, 0xBD, - 0x45, 0x4D, 0x44, 0x23, 0x64, 0x3C, 0xE8, 0x0E, - 0x2A, 0x9A, 0xC9, 0x4F, 0xA5, 0x4C, 0xA4, 0x9F }, - { 0x8E, 0x95, 0x9B, 0x75, 0xDA, 0xE3, 0x13, 0xDA, - 0x8C, 0xF4, 0xF7, 0x28, 0x14, 0xFC, 0x14, 0x3F, - 0x8F, 0x77, 0x79, 0xC6, 0xEB, 0x9F, 0x7F, 0xA1, - 0x72, 0x99, 0xAE, 0xAD, 0xB6, 0x88, 0x90, 0x18, - 0x50, 0x1D, 0x28, 0x9E, 0x49, 0x00, 0xF7, 0xE4, - 0x33, 0x1B, 0x99, 0xDE, 0xC4, 0xB5, 0x43, 0x3A, - 0xC7, 0xD3, 0x29, 0xEE, 0xB6, 0xDD, 0x26, 0x54, - 0x5E, 0x96, 0xE5, 0x5B, 0x87, 0x4B, 0xE9, 0x09 }, - { 0xE7, 0x18, 0x48, 0x3D, 0x0C, 0xE7, 0x69, 0x64, - 0x4E, 0x2E, 0x42, 0xC7, 0xBC, 0x15, 0xB4, 0x63, - 0x8E, 0x1F, 0x98, 0xB1, 0x3B, 0x20, 0x44, 0x28, - 0x56, 0x32, 0xA8, 0x03, 0xAF, 0xA9, 0x73, 0xEB, - 0xDE, 0x0F, 0xF2, 0x44, 0x87, 0x7E, 0xA6, 0x0A, - 0x4C, 0xB0, 0x43, 0x2C, 0xE5, 0x77, 0xC3, 0x1B, - 0xEB, 0x00, 0x9C, 0x5C, 0x2C, 0x49, 0xAA, 0x2E, - 0x4E, 0xAD, 0xB2, 0x17, 0xAD, 0x8C, 0xC0, 0x9B } -}; - -/* - * RFC 4231 test vectors - */ -static unsigned char sha4_hmac_test_key[7][26] = -{ - { "\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B" - "\x0B\x0B\x0B\x0B" }, - { "Jefe" }, - { "\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA" - "\xAA\xAA\xAA\xAA" }, - { "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10" - "\x11\x12\x13\x14\x15\x16\x17\x18\x19" }, - { "\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C" - "\x0C\x0C\x0C\x0C" }, - { "" }, /* 0xAA 131 times */ - { "" } -}; - -static const int sha4_hmac_test_keylen[7] = -{ - 20, 4, 20, 25, 20, 131, 131 -}; - -static unsigned char sha4_hmac_test_buf[7][153] = -{ - { "Hi There" }, - { "what do ya want for nothing?" }, - { "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD" - "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD" - "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD" - "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD" - "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD" }, - { "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" - "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" - "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" - "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" - "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" }, - { "Test With Truncation" }, - { "Test Using Larger Than Block-Size Key - Hash Key First" }, - { "This is a test using a larger than block-size key " - "and a larger than block-size data. The key needs to " - "be hashed before being used by the HMAC algorithm." } -}; - -static const int sha4_hmac_test_buflen[7] = -{ - 8, 28, 50, 50, 20, 54, 152 -}; - -static const unsigned char sha4_hmac_test_sum[14][64] = -{ - /* - * HMAC-SHA-384 test vectors - */ - { 0xAF, 0xD0, 0x39, 0x44, 0xD8, 0x48, 0x95, 0x62, - 0x6B, 0x08, 0x25, 0xF4, 0xAB, 0x46, 0x90, 0x7F, - 0x15, 0xF9, 0xDA, 0xDB, 0xE4, 0x10, 0x1E, 0xC6, - 0x82, 0xAA, 0x03, 0x4C, 0x7C, 0xEB, 0xC5, 0x9C, - 0xFA, 0xEA, 0x9E, 0xA9, 0x07, 0x6E, 0xDE, 0x7F, - 0x4A, 0xF1, 0x52, 0xE8, 0xB2, 0xFA, 0x9C, 0xB6 }, - { 0xAF, 0x45, 0xD2, 0xE3, 0x76, 0x48, 0x40, 0x31, - 0x61, 0x7F, 0x78, 0xD2, 0xB5, 0x8A, 0x6B, 0x1B, - 0x9C, 0x7E, 0xF4, 0x64, 0xF5, 0xA0, 0x1B, 0x47, - 0xE4, 0x2E, 0xC3, 0x73, 0x63, 0x22, 0x44, 0x5E, - 0x8E, 0x22, 0x40, 0xCA, 0x5E, 0x69, 0xE2, 0xC7, - 0x8B, 0x32, 0x39, 0xEC, 0xFA, 0xB2, 0x16, 0x49 }, - { 0x88, 0x06, 0x26, 0x08, 0xD3, 0xE6, 0xAD, 0x8A, - 0x0A, 0xA2, 0xAC, 0xE0, 0x14, 0xC8, 0xA8, 0x6F, - 0x0A, 0xA6, 0x35, 0xD9, 0x47, 0xAC, 0x9F, 0xEB, - 0xE8, 0x3E, 0xF4, 0xE5, 0x59, 0x66, 0x14, 0x4B, - 0x2A, 0x5A, 0xB3, 0x9D, 0xC1, 0x38, 0x14, 0xB9, - 0x4E, 0x3A, 0xB6, 0xE1, 0x01, 0xA3, 0x4F, 0x27 }, - { 0x3E, 0x8A, 0x69, 0xB7, 0x78, 0x3C, 0x25, 0x85, - 0x19, 0x33, 0xAB, 0x62, 0x90, 0xAF, 0x6C, 0xA7, - 0x7A, 0x99, 0x81, 0x48, 0x08, 0x50, 0x00, 0x9C, - 0xC5, 0x57, 0x7C, 0x6E, 0x1F, 0x57, 0x3B, 0x4E, - 0x68, 0x01, 0xDD, 0x23, 0xC4, 0xA7, 0xD6, 0x79, - 0xCC, 0xF8, 0xA3, 0x86, 0xC6, 0x74, 0xCF, 0xFB }, - { 0x3A, 0xBF, 0x34, 0xC3, 0x50, 0x3B, 0x2A, 0x23, - 0xA4, 0x6E, 0xFC, 0x61, 0x9B, 0xAE, 0xF8, 0x97 }, - { 0x4E, 0xCE, 0x08, 0x44, 0x85, 0x81, 0x3E, 0x90, - 0x88, 0xD2, 0xC6, 0x3A, 0x04, 0x1B, 0xC5, 0xB4, - 0x4F, 0x9E, 0xF1, 0x01, 0x2A, 0x2B, 0x58, 0x8F, - 0x3C, 0xD1, 0x1F, 0x05, 0x03, 0x3A, 0xC4, 0xC6, - 0x0C, 0x2E, 0xF6, 0xAB, 0x40, 0x30, 0xFE, 0x82, - 0x96, 0x24, 0x8D, 0xF1, 0x63, 0xF4, 0x49, 0x52 }, - { 0x66, 0x17, 0x17, 0x8E, 0x94, 0x1F, 0x02, 0x0D, - 0x35, 0x1E, 0x2F, 0x25, 0x4E, 0x8F, 0xD3, 0x2C, - 0x60, 0x24, 0x20, 0xFE, 0xB0, 0xB8, 0xFB, 0x9A, - 0xDC, 0xCE, 0xBB, 0x82, 0x46, 0x1E, 0x99, 0xC5, - 0xA6, 0x78, 0xCC, 0x31, 0xE7, 0x99, 0x17, 0x6D, - 0x38, 0x60, 0xE6, 0x11, 0x0C, 0x46, 0x52, 0x3E }, - - /* - * HMAC-SHA-512 test vectors - */ - { 0x87, 0xAA, 0x7C, 0xDE, 0xA5, 0xEF, 0x61, 0x9D, - 0x4F, 0xF0, 0xB4, 0x24, 0x1A, 0x1D, 0x6C, 0xB0, - 0x23, 0x79, 0xF4, 0xE2, 0xCE, 0x4E, 0xC2, 0x78, - 0x7A, 0xD0, 0xB3, 0x05, 0x45, 0xE1, 0x7C, 0xDE, - 0xDA, 0xA8, 0x33, 0xB7, 0xD6, 0xB8, 0xA7, 0x02, - 0x03, 0x8B, 0x27, 0x4E, 0xAE, 0xA3, 0xF4, 0xE4, - 0xBE, 0x9D, 0x91, 0x4E, 0xEB, 0x61, 0xF1, 0x70, - 0x2E, 0x69, 0x6C, 0x20, 0x3A, 0x12, 0x68, 0x54 }, - { 0x16, 0x4B, 0x7A, 0x7B, 0xFC, 0xF8, 0x19, 0xE2, - 0xE3, 0x95, 0xFB, 0xE7, 0x3B, 0x56, 0xE0, 0xA3, - 0x87, 0xBD, 0x64, 0x22, 0x2E, 0x83, 0x1F, 0xD6, - 0x10, 0x27, 0x0C, 0xD7, 0xEA, 0x25, 0x05, 0x54, - 0x97, 0x58, 0xBF, 0x75, 0xC0, 0x5A, 0x99, 0x4A, - 0x6D, 0x03, 0x4F, 0x65, 0xF8, 0xF0, 0xE6, 0xFD, - 0xCA, 0xEA, 0xB1, 0xA3, 0x4D, 0x4A, 0x6B, 0x4B, - 0x63, 0x6E, 0x07, 0x0A, 0x38, 0xBC, 0xE7, 0x37 }, - { 0xFA, 0x73, 0xB0, 0x08, 0x9D, 0x56, 0xA2, 0x84, - 0xEF, 0xB0, 0xF0, 0x75, 0x6C, 0x89, 0x0B, 0xE9, - 0xB1, 0xB5, 0xDB, 0xDD, 0x8E, 0xE8, 0x1A, 0x36, - 0x55, 0xF8, 0x3E, 0x33, 0xB2, 0x27, 0x9D, 0x39, - 0xBF, 0x3E, 0x84, 0x82, 0x79, 0xA7, 0x22, 0xC8, - 0x06, 0xB4, 0x85, 0xA4, 0x7E, 0x67, 0xC8, 0x07, - 0xB9, 0x46, 0xA3, 0x37, 0xBE, 0xE8, 0x94, 0x26, - 0x74, 0x27, 0x88, 0x59, 0xE1, 0x32, 0x92, 0xFB }, - { 0xB0, 0xBA, 0x46, 0x56, 0x37, 0x45, 0x8C, 0x69, - 0x90, 0xE5, 0xA8, 0xC5, 0xF6, 0x1D, 0x4A, 0xF7, - 0xE5, 0x76, 0xD9, 0x7F, 0xF9, 0x4B, 0x87, 0x2D, - 0xE7, 0x6F, 0x80, 0x50, 0x36, 0x1E, 0xE3, 0xDB, - 0xA9, 0x1C, 0xA5, 0xC1, 0x1A, 0xA2, 0x5E, 0xB4, - 0xD6, 0x79, 0x27, 0x5C, 0xC5, 0x78, 0x80, 0x63, - 0xA5, 0xF1, 0x97, 0x41, 0x12, 0x0C, 0x4F, 0x2D, - 0xE2, 0xAD, 0xEB, 0xEB, 0x10, 0xA2, 0x98, 0xDD }, - { 0x41, 0x5F, 0xAD, 0x62, 0x71, 0x58, 0x0A, 0x53, - 0x1D, 0x41, 0x79, 0xBC, 0x89, 0x1D, 0x87, 0xA6 }, - { 0x80, 0xB2, 0x42, 0x63, 0xC7, 0xC1, 0xA3, 0xEB, - 0xB7, 0x14, 0x93, 0xC1, 0xDD, 0x7B, 0xE8, 0xB4, - 0x9B, 0x46, 0xD1, 0xF4, 0x1B, 0x4A, 0xEE, 0xC1, - 0x12, 0x1B, 0x01, 0x37, 0x83, 0xF8, 0xF3, 0x52, - 0x6B, 0x56, 0xD0, 0x37, 0xE0, 0x5F, 0x25, 0x98, - 0xBD, 0x0F, 0xD2, 0x21, 0x5D, 0x6A, 0x1E, 0x52, - 0x95, 0xE6, 0x4F, 0x73, 0xF6, 0x3F, 0x0A, 0xEC, - 0x8B, 0x91, 0x5A, 0x98, 0x5D, 0x78, 0x65, 0x98 }, - { 0xE3, 0x7B, 0x6A, 0x77, 0x5D, 0xC8, 0x7D, 0xBA, - 0xA4, 0xDF, 0xA9, 0xF9, 0x6E, 0x5E, 0x3F, 0xFD, - 0xDE, 0xBD, 0x71, 0xF8, 0x86, 0x72, 0x89, 0x86, - 0x5D, 0xF5, 0xA3, 0x2D, 0x20, 0xCD, 0xC9, 0x44, - 0xB6, 0x02, 0x2C, 0xAC, 0x3C, 0x49, 0x82, 0xB1, - 0x0D, 0x5E, 0xEB, 0x55, 0xC3, 0xE4, 0xDE, 0x15, - 0x13, 0x46, 0x76, 0xFB, 0x6D, 0xE0, 0x44, 0x60, - 0x65, 0xC9, 0x74, 0x40, 0xFA, 0x8C, 0x6A, 0x58 } -}; - -/* - * Checkup routine - */ -int sha4_self_test( int verbose ) -{ - int i, j, k, buflen; - unsigned char buf[1024]; - unsigned char sha4sum[64]; - sha4_context ctx; - - for( i = 0; i < 6; i++ ) - { - j = i % 3; - k = i < 3; - - if( verbose != 0 ) - printf( " SHA-%d test #%d: ", 512 - k * 128, j + 1 ); - - sha4_starts( &ctx, k ); - - if( j == 2 ) - { - memset( buf, 'a', buflen = 1000 ); - - for( j = 0; j < 1000; j++ ) - sha4_update( &ctx, buf, buflen ); - } - else - sha4_update( &ctx, sha4_test_buf[j], - sha4_test_buflen[j] ); - - sha4_finish( &ctx, sha4sum ); - - if( memcmp( sha4sum, sha4_test_sum[i], 64 - k * 16 ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( verbose != 0 ) - printf( "passed\n" ); - } - - if( verbose != 0 ) - printf( "\n" ); - - for( i = 0; i < 14; i++ ) - { - j = i % 7; - k = i < 7; - - if( verbose != 0 ) - printf( " HMAC-SHA-%d test #%d: ", 512 - k * 128, j + 1 ); - - if( j == 5 || j == 6 ) - { - memset( buf, '\xAA', buflen = 131 ); - sha4_hmac_starts( &ctx, buf, buflen, k ); - } - else - sha4_hmac_starts( &ctx, sha4_hmac_test_key[j], - sha4_hmac_test_keylen[j], k ); - - sha4_hmac_update( &ctx, sha4_hmac_test_buf[j], - sha4_hmac_test_buflen[j] ); - - sha4_hmac_finish( &ctx, sha4sum ); - - buflen = ( j == 4 ) ? 16 : 64 - k * 16; - - if( memcmp( sha4sum, sha4_hmac_test_sum[i], buflen ) != 0 ) - { - if( verbose != 0 ) - printf( "failed\n" ); - - return( 1 ); - } - - if( verbose != 0 ) - printf( "passed\n" ); - } - - if( verbose != 0 ) - printf( "\n" ); - - return( 0 ); -} - -#endif - -#endif diff --git a/makefile b/makefile index 2897e51..bd9fc60 100644 --- a/makefile +++ b/makefile @@ -1,22 +1,142 @@ -PROJECT_DIR = "$(CURDIR)" -LIB_DIR = $(PROJECT_DIR)/lib -PROGRAM_DIR = $(PROJECT_DIR)/programs -BIN_DIR = $(PROJECT_DIR)/bin +# Project Defines +PROJECT_NAME = nstool +PROJECT_PATH = $(CURDIR) +PROJECT_SRC_PATH = ./src +PROJECT_INCLUDE_PATH = +PROJECT_TEST_PATH = +PROJECT_BIN_PATH = ./bin +PROJECT_DOCS_PATH = +PROJECT_DOXYFILE_PATH = -LIBS = libpolarssl liblz4 libfnd libes libpki libhac libhac-hb -PROGS = nstool +# Project Library Defines +PROJECT_LIB_VER_MAJOR = 0 +PROJECT_LIB_VER_MINOR = 1 +PROJECT_LIB_VER_PATCH = 0 +PROJECT_SONAME = $(PROJECT_NAME).so.$(PROJECT_LIB_VER_MAJOR) +PROJECT_SO_FILENAME = $(PROJECT_SONAME).$(PROJECT_LIB_VER_MINOR).$(PROJECT_LIB_VER_PATCH) -main: build +# Project Dependencies +PROJECT_DEPEND = nintendo-hac-hb nintendo-hac nintendo-es nintendo-pki fnd polarssl lz4 -rebuild: clean build +# Check if this is the root makefile +ifeq ($(ROOT_PROJECT_NAME),) + export ROOT_PROJECT_NAME = $(PROJECT_NAME) + export ROOT_PROJECT_PATH = $(PROJECT_PATH) + export ROOT_PROJECT_DEPENDENCY_PATH = $(ROOT_PROJECT_PATH)/deps +endif -build: - mkdir -p $(BIN_DIR) - @$(foreach lib,$(LIBS), cd $(LIB_DIR)/$(lib) && $(MAKE) && cd $(PROJECT_DIR);) - @$(foreach prog,$(PROGS), cd $(PROGRAM_DIR)/$(prog) && $(MAKE) && cd $(PROJECT_DIR) && cp -r $(PROGRAM_DIR)/$(prog)/bin/* $(BIN_DIR);) +# Compiler Flags +ifneq ($(PROJECT_INCLUDE_PATH),) + INC += -I"$(PROJECT_INCLUDE_PATH)" +endif +ifneq ($(PROJECT_DEPEND),) + LIB += $(foreach dep,$(PROJECT_DEPEND), -L"$(ROOT_PROJECT_DEPENDENCY_PATH)/lib$(dep)/bin" -l$(dep)) + INC += $(foreach dep,$(PROJECT_DEPEND), -I"$(ROOT_PROJECT_DEPENDENCY_PATH)/lib$(dep)/include") +endif +CXXFLAGS = -std=c++11 $(INC) -fPIC -D__STDC_FORMAT_MACROS -Wall -Wno-unused-value +CFLAGS = -std=c11 $(INC) -fPIC -Wall -Wno-unused-value +ARFLAGS = cr -o +ifeq ($(OS),Windows_NT) + # Windows Only Flags/Libs + CC = x86_64-w64-mingw32-gcc + CXX = x86_64-w64-mingw32-g++ + CFLAGS += -Wno-unused-but-set-variable + CXXFLAGS += -Wno-unused-but-set-variable + LIB += -static +else + UNAME = $(shell uname -s) + ifeq ($(UNAME), Darwin) + # MacOS Only Flags/Libs + CFLAGS += -Wno-unused-private-field + CXXFLAGS += -Wno-unused-private-field + LIB += + ARFLAGS = rc + else + # *nix Only Flags/Libs + CFLAGS += -Wno-unused-but-set-variable + CXXFLAGS += -Wno-unused-but-set-variable + LIB += + endif +endif +ifeq ($(OS),Windows_NT) + # Windows Only Flags/Libs + CC = x86_64-w64-mingw32-gcc + CXX = x86_64-w64-mingw32-g++ + CFLAGS += -Wno-unused-but-set-variable + CXXFLAGS += -Wno-unused-but-set-variable + LIBS += -static +else + UNAME = $(shell uname -s) + ifeq ($(UNAME), Darwin) + # MacOS Only Flags/Libs + CFLAGS += -Wno-unused-private-field + CXXFLAGS += -Wno-unused-private-field + LIBS += + else + # *nix Only Flags/Libs + CFLAGS += -Wno-unused-but-set-variable + CXXFLAGS += -Wno-unused-but-set-variable + LIBS += + endif +endif + +# Object Files +SRC_DIR = $(PROJECT_SRC_PATH) +SRC_OBJ = $(foreach dir,$(SRC_DIR),$(subst .cpp,.o,$(wildcard $(dir)/*.cpp))) +TEST_DIR = $(PROJECT_TEST_PATH) +TEST_OBJ = $(foreach dir,$(TEST_DIR),$(subst .cpp,.o,$(wildcard $(dir)/*.cpp))) + +# all is the default, user should specify what the default should do +# - 'static_lib' for building static library +# - 'shared_lib' for building shared library +# - 'program' for building the program +# - 'test_program' for building the test program +# These can typically be used together however *_lib and program should not be used together +all: program +clean: clean_objs clean_bin_dir -clean: - rm -rf $(BIN_DIR) - @$(foreach lib,$(LIBS), cd $(LIB_DIR)/$(lib) && $(MAKE) clean && cd $(PROJECT_DIR);) - @$(foreach prog,$(PROGS), cd $(PROGRAM_DIR)/$(prog) && $(MAKE) clean && cd $(PROJECT_DIR);) \ No newline at end of file +# Binary Directory +.PHONY: bin_dir +bin_dir: + @mkdir -p "$(PROJECT_BIN_PATH)" + +.PHONY: clean_bin_dir +clean_bin_dir: + @rm -rf "$(PROJECT_BIN_PATH)" + +.PHONY: clean_objs +clean_objs: + @rm -f $(SRC_OBJ) $(TEST_OBJ) + +# Build Library +static_lib: $(SRC_OBJ) bin_dir + ar $(ARFLAGS) "$(PROJECT_BIN_PATH)/$(PROJECT_NAME).a" $(SRC_OBJ) + +shared_lib: $(SRC_OBJ) bin_dir + gcc -shared -Wl,-soname,$(PROJECT_SONAME) -o "$(PROJECT_BIN_PATH)/$(PROJECT_SO_FILENAME)" $(SRC_OBJ) + +# Build Program +program: $(SRC_OBJ) bin_dir + $(CXX) $(SRC_OBJ) $(LIB) -o "$(PROJECT_BIN_PATH)/$(PROJECT_NAME)" + +# Build Test Program +test_program: $(TEST_OBJ) $(SRC_OBJ) bin_dir + $(CXX) $(TEST_OBJ) $(SRC_OBJ) $(LIB) -o "$(PROJECT_BIN_PATH)/$(PROJECT_NAME)_test" + +# Documentation +docs: + doxygen $(PROJECT_DOXYFILE_PATH) + +.PHONY: clean_docs +clean_docs: + @rm -rf $(PROJECT_DOCS_PATH) + +# Dependencies +.PHONY: build_deps +build_deps: + @$(foreach lib,$(PROJECT_DEPEND), cd $(ROOT_PROJECT_DEPENDENCY_PATH)/lib$(lib) && $(MAKE) static_lib && cd $(PROJECT_PATH);) + +.PHONY: clean_deps +clean_deps: + @$(foreach lib,$(PROJECT_DEPEND), cd $(ROOT_PROJECT_DEPENDENCY_PATH)/lib$(lib) && $(MAKE) clean && cd $(PROJECT_PATH);) \ No newline at end of file diff --git a/programs/nstool/README.md b/programs/nstool/README.md deleted file mode 100644 index 4b46e3a..0000000 --- a/programs/nstool/README.md +++ /dev/null @@ -1,80 +0,0 @@ -# Nintendo Switch Tool (NSTool) ![DeviceTag](https://img.shields.io/badge/Device-SWITCH-e60012.svg) -General purpose reading/extraction tool for Nintendo Switch file formats. - -## Supported File Formats -* Meta (.npdm) -* PartitionFS (and HashedPartitionFS) (includes raw .nsp) -* RomFS -* GameCard Image (.xci) -* Nintendo Content Archive (.nca) -* Content Metadata (.cnmt) -* Nintendo Software Object (.nso) -* Nintendo Relocatable Software Object (.nro) -* Kernel Initial Process List (.ini) -* Kernel Initial Process (.kip) -* Nintendo Application Control Property (.nacp) -* ES Ticket (v2 only) (.tik) -* PKI Certificate (.cert) - -# Usage -``` -Usage: nstool [options... ] - - General Options: - -d, --dev Use devkit keyset. - -k, --keyset Specify keyset file. - -t, --type Specify input file type. [xci, pfs, romfs, nca, meta, cnmt, nso, nro, ini, kip, nacp, aset, cert, tik] - -y, --verify Verify file. - - Output Options: - --showkeys Show keys generated. - --showlayout Show layout metadata. - -v, --verbose Verbose output. - - XCI (GameCard Image) - nstool [--listfs] [--update --logo --normal --secure ] <.xci file> - --listfs Print file system in embedded partitions. - --update Extract "update" partition to directory. - --logo Extract "logo" partition to directory. - --normal Extract "normal" partition to directory. - --secure Extract "secure" partition to directory. - - PFS0/HFS0 (PartitionFs), RomFs, NSP (Ninendo Submission Package) - nstool [--listfs] [--fsdir ] - --listfs Print file system. - --fsdir Extract file system to directory. - - NCA (Nintendo Content Archive) - nstool [--listfs] [--bodykey --titlekey ] [--part0 ...] <.nca file> - --listfs Print file system in embedded partitions. - --titlekey Specify title key extracted from ticket. - --bodykey Specify body encryption key. - --tik Specify ticket to source title key. - --cert Specify certificate chain to verify ticket. - --part0 Extract "partition 0" to directory. - --part1 Extract "partition 1" to directory. - --part2 Extract "partition 2" to directory. - --part3 Extract "partition 3" to directory. - - NSO (Nintendo Software Object), NRO (Nintendo Relocatable Object) - nstool [--listapi --listsym] [--insttype ] - --listapi Print SDK API List. - --listsym Print Code Symbols. - --insttype Specify instruction type [64bit|32bit] (64bit is assumed). - - INI (Initial Process List Blob) - nstool [--kipdir ] - --kipdir Extract embedded KIPs to directory. - - ASET (Homebrew Asset Blob) - nstool [--listfs] [--icon --nacp --fsdir ] - --listfs Print filesystem in embedded RomFS partition. - --icon Extract icon partition to file. - --nacp Extract NACP partition to file. - --fsdir Extract RomFS partition to directory. -``` - -# External Keys -NSTool doesn't embed any keys that are copyright protected. However keys can be imported via various keyset files. - -See [SWITCH_KEYS.md](/SWITCH_KEYS.md) for more info. diff --git a/programs/nstool/makefile b/programs/nstool/makefile deleted file mode 100644 index 91999dc..0000000 --- a/programs/nstool/makefile +++ /dev/null @@ -1,48 +0,0 @@ -# Sources -SRC_DIR = source -OBJS = $(foreach dir,$(SRC_DIR),$(subst .cpp,.o,$(wildcard $(dir)/*.cpp))) $(foreach dir,$(SRC_DIR),$(subst .c,.o,$(wildcard $(dir)/*.c))) - -# External dependencies -DEPENDS = hac-hb hac es pki fnd polarssl lz4 -LIB_DIR = ../../lib -LIBS = $(foreach dep,$(DEPENDS), -L"$(LIB_DIR)/lib$(dep)" -l$(dep)) -INCS = $(foreach dep,$(DEPENDS), -I"$(LIB_DIR)/lib$(dep)/include") - -# Compiler Settings -CXXFLAGS = -std=c++11 $(INCS) -D__STDC_FORMAT_MACROS -Wall -Wno-unused-value -CFLAGS = -std=c11 $(INCS) -Wall -Wno-unused-value -ifeq ($(OS),Windows_NT) - # Windows Only Flags/Libs - CC = x86_64-w64-mingw32-gcc - CXX = x86_64-w64-mingw32-g++ - CFLAGS += -Wno-unused-but-set-variable - CXXFLAGS += -Wno-unused-but-set-variable - LIBS += -static -else - UNAME = $(shell uname -s) - ifeq ($(UNAME), Darwin) - # MacOS Only Flags/Libs - CFLAGS += -Wno-unused-private-field - CXXFLAGS += -Wno-unused-private-field - LIBS += - else - # *nix Only Flags/Libs - CFLAGS += -Wno-unused-but-set-variable - CXXFLAGS += -Wno-unused-but-set-variable - LIBS += - endif -endif - -BIN_DIR = bin -OUTPUT = $(BIN_DIR)/$(shell basename "$(CURDIR)") - -all: build - -rebuild: clean build - -build: $(OBJS) - mkdir -p $(BIN_DIR) - $(CXX) $(OBJS) $(LIBS) -o $(OUTPUT) - -clean: - rm -rf $(OBJS) $(OUTPUT) $(BIN_DIR) \ No newline at end of file diff --git a/programs/nstool/nstool.vcxproj b/programs/nstool/nstool.vcxproj deleted file mode 100644 index 78c2ecc..0000000 --- a/programs/nstool/nstool.vcxproj +++ /dev/null @@ -1,230 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 15.0 - {AF09FA96-4463-417D-8FE6-526063F41349} - Win32Proj - nstool - 10.0.16299.0 - - - - Application - true - v141 - Unicode - - - Application - false - v141 - true - Unicode - - - Application - true - v141 - Unicode - - - Application - false - v141 - true - Unicode - - - - - - - - - - - - - - - - - - - - - true - - - true - - - false - - - false - - - - NotUsing - Level3 - Disabled - true - _DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - ..\..\lib\libpki\include;..\..\lib\libes\include;..\..\lib\libfnd\include;..\..\lib\libhac\include;..\..\lib\libhac-hb\include - - - Console - true - - - - - NotUsing - Level3 - Disabled - true - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - ..\..\lib\libpki\include;..\..\lib\libes\include;..\..\lib\libfnd\include;..\..\lib\libhac\include;..\..\lib\libhac-hb\include - - - Console - true - - - - - NotUsing - Level3 - MaxSpeed - true - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - ..\..\lib\libpki\include;..\..\lib\libes\include;..\..\lib\libfnd\include;..\..\lib\libhac\include;..\..\lib\libhac-hb\include - - - Console - true - true - true - - - - - NotUsing - Level3 - MaxSpeed - true - true - true - NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - ..\..\lib\libpki\include;..\..\lib\libes\include;..\..\lib\libfnd\include;..\..\lib\libhac\include;..\..\lib\libhac-hb\include - - - Console - true - true - true - - - - - {394EFC16-BD3A-4538-B33D-7BA1EDB8DAC1} - - - {AB0C3362-63AB-480A-ADBC-2EF7D859778B} - - - {7be99936-0d40-410d-944b-4513c2eff8dc} - - - {4d27edb9-5110-44fe-8ce2-d46c5ad3c55b} - - - {738cb4fc-cd9e-4b81-a04b-deadbfa71c63} - - - {91ba9e79-8242-4f7d-b997-0dfec95ea22b} - - - {b9113734-6e84-44ff-8cf7-58199aa815c5} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/programs/nstool/nstool.vcxproj.user b/programs/nstool/nstool.vcxproj.user deleted file mode 100644 index 50d33be..0000000 --- a/programs/nstool/nstool.vcxproj.user +++ /dev/null @@ -1,23 +0,0 @@ - - - - --titlekey F28921A36270C34B5476A384A212FC18 --part1 winromfsext test\nsp\nsout\32a23f30763ca916909399fc03c57bd2.nca - WindowsLocalDebugger - ..\.. - - - --titlekey F28921A36270C34B5476A384A212FC18 --part1 winromfsext test\nsp\nsout\32a23f30763ca916909399fc03c57bd2.nca - WindowsLocalDebugger - ..\.. - - - --titlekey F28921A36270C34B5476A384A212FC18 --part1 winromfsext test\nsp\nsout\32a23f30763ca916909399fc03c57bd2.nca - WindowsLocalDebugger - ..\.. - - - --titlekey F28921A36270C34B5476A384A212FC18 --part1 winromfsext test\nsp\nsout\32a23f30763ca916909399fc03c57bd2.nca - WindowsLocalDebugger - ..\.. - - \ No newline at end of file diff --git a/programs/nstool/source/AssetProcess.cpp b/src/AssetProcess.cpp similarity index 100% rename from programs/nstool/source/AssetProcess.cpp rename to src/AssetProcess.cpp diff --git a/programs/nstool/source/AssetProcess.h b/src/AssetProcess.h similarity index 100% rename from programs/nstool/source/AssetProcess.h rename to src/AssetProcess.h diff --git a/programs/nstool/source/CnmtProcess.cpp b/src/CnmtProcess.cpp similarity index 97% rename from programs/nstool/source/CnmtProcess.cpp rename to src/CnmtProcess.cpp index dfcf9ea..54c7777 100644 --- a/programs/nstool/source/CnmtProcess.cpp +++ b/src/CnmtProcess.cpp @@ -1,249 +1,249 @@ -#include -#include -#include -#include -#include "CnmtProcess.h" - -CnmtProcess::CnmtProcess() : - mFile(), - mCliOutputMode(_BIT(OUTPUT_BASIC)), - mVerify(false) -{ -} - -void CnmtProcess::process() -{ - importCnmt(); - - if (_HAS_BIT(mCliOutputMode, OUTPUT_BASIC)) - displayCnmt(); -} - -void CnmtProcess::setInputFile(const fnd::SharedPtr& file) -{ - mFile = file; -} - -void CnmtProcess::setCliOutputMode(CliOutputMode type) -{ - mCliOutputMode = type; -} - -void CnmtProcess::setVerifyMode(bool verify) -{ - mVerify = verify; -} - -const nn::hac::ContentMeta& CnmtProcess::getContentMeta() const -{ - return mCnmt; -} - -void CnmtProcess::importCnmt() -{ - fnd::Vec scratch; - - if (*mFile == nullptr) - { - throw fnd::Exception(kModuleName, "No file reader set."); - } - - scratch.alloc((*mFile)->size()); - (*mFile)->read(scratch.data(), 0, scratch.size()); - - mCnmt.fromBytes(scratch.data(), scratch.size()); -} - -void CnmtProcess::displayCnmt() -{ -#define _SPLIT_VER(ver) (uint32_t)((ver>>26) & 0x3f) << "." << (uint32_t)((ver>>20) & 0x3f) << "." << (uint32_t)((ver>>16) & 0xf) << "." << (uint32_t)(ver & 0xffff) - - std::cout << "[ContentMeta]" << std::endl; - std::cout << " TitleId: 0x" << std::hex << std::setw(16) << std::setfill('0') << mCnmt.getTitleId() << std::endl; - std::cout << " Version: v" << std::dec << mCnmt.getTitleVersion() << " (" << _SPLIT_VER(mCnmt.getTitleVersion()) << ")"<< std::endl; - std::cout << " Type: " << getContentMetaTypeStr(mCnmt.getContentMetaType()) << " (" << std::dec << mCnmt.getContentMetaType() << ")" << std::endl; - std::cout << " Attributes: 0x" << std::hex << (uint32_t)mCnmt.getAttributes() << std::endl; - std::cout << " IncludesExFatDriver: " << getBoolStr(_HAS_BIT(mCnmt.getAttributes(), nn::hac::cnmt::ATTRIBUTE_INCLUDES_EX_FAT_DRIVER)) << std::endl; - std::cout << " Rebootless: " << getBoolStr(_HAS_BIT(mCnmt.getAttributes(), nn::hac::cnmt::ATTRIBUTE_REBOOTLESS)) << std::endl; - std::cout << " RequiredDownloadSystemVersion: v" << mCnmt.getRequiredDownloadSystemVersion() << " (" << _SPLIT_VER(mCnmt.getRequiredDownloadSystemVersion()) << ")"<< std::endl; - switch(mCnmt.getContentMetaType()) - { - case (nn::hac::cnmt::METATYPE_APPLICATION): - std::cout << " ApplicationExtendedHeader:" << std::endl; - std::cout << " RequiredSystemVersion: v" << std::dec << mCnmt.getApplicationMetaExtendedHeader().getRequiredSystemVersion() << " (" << _SPLIT_VER(mCnmt.getApplicationMetaExtendedHeader().getRequiredSystemVersion()) << ")"<< std::endl; - std::cout << " PatchId: 0x" << std::hex << std::setw(16) << std::setfill('0') << mCnmt.getApplicationMetaExtendedHeader().getPatchId() << std::endl; - break; - case (nn::hac::cnmt::METATYPE_PATCH): - std::cout << " PatchMetaExtendedHeader:" << std::endl; - std::cout << " RequiredSystemVersion: v" << std::dec << mCnmt.getPatchMetaExtendedHeader().getRequiredSystemVersion() << " (" << _SPLIT_VER(mCnmt.getPatchMetaExtendedHeader().getRequiredSystemVersion()) << ")"<< std::endl; - std::cout << " ApplicationId: 0x" << std::hex << std::setw(16) << std::setfill('0') << mCnmt.getPatchMetaExtendedHeader().getApplicationId() << std::endl; - break; - case (nn::hac::cnmt::METATYPE_ADD_ON_CONTENT): - std::cout << " AddOnContentMetaExtendedHeader:" << std::endl; - std::cout << " RequiredApplicationVersion: v" << std::dec << mCnmt.getAddOnContentMetaExtendedHeader().getRequiredApplicationVersion() << " (" << _SPLIT_VER(mCnmt.getAddOnContentMetaExtendedHeader().getRequiredApplicationVersion()) << ")" << std::endl; - std::cout << " ApplicationId: 0x" << std::hex << std::setw(16) << std::setfill('0') << mCnmt.getAddOnContentMetaExtendedHeader().getApplicationId() << std::endl; - break; - case (nn::hac::cnmt::METATYPE_DELTA): - std::cout << " DeltaMetaExtendedHeader:" << std::endl; - std::cout << " ApplicationId: 0x" << std::hex << std::setw(16) << std::setfill('0') << mCnmt.getDeltaMetaExtendedHeader().getApplicationId() << std::endl; - break; - default: - break; - } - if (mCnmt.getContentInfo().size() > 0) - { - printf(" ContentInfo:\n"); - for (size_t i = 0; i < mCnmt.getContentInfo().size(); i++) - { - const nn::hac::ContentInfo& info = mCnmt.getContentInfo()[i]; - std::cout << " " << std::dec << i << std::endl; - std::cout << " Type: " << getContentTypeStr(info.getContentType()) << " (" << std::dec << info.getContentType() << ")" << std::endl; - std::cout << " Id: " << fnd::SimpleTextOutput::arrayToString(info.getContentId().data, nn::hac::cnmt::kContentIdLen, false, "") << std::endl; - std::cout << " Size: 0x" << std::hex << info.getContentSize() << std::endl; - std::cout << " Hash: " << fnd::SimpleTextOutput::arrayToString(info.getContentHash().bytes, sizeof(info.getContentHash()), false, "") << std::endl; - } - } - if (mCnmt.getContentMetaInfo().size() > 0) - { - std::cout << " ContentMetaInfo:" << std::endl; - for (size_t i = 0; i < mCnmt.getContentMetaInfo().size(); i++) - { - const nn::hac::ContentMetaInfo& info = mCnmt.getContentMetaInfo()[i]; - std::cout << " " << std::dec << i << std::endl; - std::cout << " Id: 0x" << std::hex << std::setw(16) << std::setfill('0') << info.getTitleId() << std::endl; - std::cout << " Version: v" << std::dec << info.getTitleVersion() << " (" << _SPLIT_VER(info.getTitleVersion()) << ")"<< std::endl; - std::cout << " Type: " << getContentMetaTypeStr(info.getContentMetaType()) << " (" << std::dec << info.getContentMetaType() << ")" << std::endl; - std::cout << " Attributes: 0x" << std::hex << (uint32_t)info.getAttributes() << std::endl; - std::cout << " IncludesExFatDriver: " << getBoolStr(_HAS_BIT(info.getAttributes(), nn::hac::cnmt::ATTRIBUTE_INCLUDES_EX_FAT_DRIVER)) << std::endl; - std::cout << " Rebootless: " << getBoolStr(_HAS_BIT(info.getAttributes(), nn::hac::cnmt::ATTRIBUTE_REBOOTLESS)) << std::endl; - } - } - - std::cout << " Digest: " << fnd::SimpleTextOutput::arrayToString(mCnmt.getDigest().data, nn::hac::cnmt::kDigestLen, false, "") << std::endl; - -#undef _SPLIT_VER -} - -const char* CnmtProcess::getBoolStr(bool state) const -{ - return state? "TRUE" : "FALSE"; -} - -const char* CnmtProcess::getContentTypeStr(nn::hac::cnmt::ContentType type) const -{ - const char* str = nullptr; - - switch (type) - { - case (nn::hac::cnmt::TYPE_META): - str = "Meta"; - break; - case (nn::hac::cnmt::TYPE_PROGRAM): - str = "Program"; - break; - case (nn::hac::cnmt::TYPE_DATA): - str = "Data"; - break; - case (nn::hac::cnmt::TYPE_CONTROL): - str = "Control"; - break; - case (nn::hac::cnmt::TYPE_HTML_DOCUMENT): - str = "HtmlDocument"; - break; - case (nn::hac::cnmt::TYPE_LEGAL_INFORMATION): - str = "LegalInformation"; - break; - case (nn::hac::cnmt::TYPE_DELTA_FRAGMENT): - str = "DeltaFragment"; - break; - default: - str = "Unknown"; - break; - } - - return str; -} - -const char* CnmtProcess::getContentMetaTypeStr(nn::hac::cnmt::ContentMetaType type) const -{ - const char* str = nullptr; - - switch (type) - { - case (nn::hac::cnmt::METATYPE_SYSTEM_PROGRAM): - str = "SystemProgram"; - break; - case (nn::hac::cnmt::METATYPE_SYSTEM_DATA): - str = "SystemData"; - break; - case (nn::hac::cnmt::METATYPE_SYSTEM_UPDATE): - str = "SystemUpdate"; - break; - case (nn::hac::cnmt::METATYPE_BOOT_IMAGE_PACKAGE): - str = "BootImagePackage"; - break; - case (nn::hac::cnmt::METATYPE_BOOT_IMAGE_PACKAGE_SAFE): - str = "BootImagePackageSafe"; - break; - case (nn::hac::cnmt::METATYPE_APPLICATION): - str = "Application"; - break; - case (nn::hac::cnmt::METATYPE_PATCH): - str = "Patch"; - break; - case (nn::hac::cnmt::METATYPE_ADD_ON_CONTENT): - str = "AddOnContent"; - break; - case (nn::hac::cnmt::METATYPE_DELTA): - str = "Delta"; - break; - default: - str = "Unknown"; - break; - } - - return str; -} - -const char* CnmtProcess::getUpdateTypeStr(nn::hac::cnmt::UpdateType type) const -{ - const char* str = nullptr; - - switch (type) - { - case (nn::hac::cnmt::UPDATETYPE_APPLY_AS_DELTA): - str = "ApplyAsDelta"; - break; - case (nn::hac::cnmt::UPDATETYPE_OVERWRITE): - str = "Overwrite"; - break; - case (nn::hac::cnmt::UPDATETYPE_CREATE): - str = "Create"; - break; - default: - str = "Unknown"; - break; - } - - return str; -} - -const char* CnmtProcess::getContentMetaAttrStr(nn::hac::cnmt::ContentMetaAttribute attr) const -{ - const char* str = nullptr; - - switch (attr) - { - case (nn::hac::cnmt::ATTRIBUTE_INCLUDES_EX_FAT_DRIVER): - str = "IncludesExFatDriver"; - break; - case (nn::hac::cnmt::ATTRIBUTE_REBOOTLESS): - str = "Rebootless"; - break; - default: - str = "Unknown"; - break; - } - - return str; -} +#include +#include +#include +#include +#include "CnmtProcess.h" + +CnmtProcess::CnmtProcess() : + mFile(), + mCliOutputMode(_BIT(OUTPUT_BASIC)), + mVerify(false) +{ +} + +void CnmtProcess::process() +{ + importCnmt(); + + if (_HAS_BIT(mCliOutputMode, OUTPUT_BASIC)) + displayCnmt(); +} + +void CnmtProcess::setInputFile(const fnd::SharedPtr& file) +{ + mFile = file; +} + +void CnmtProcess::setCliOutputMode(CliOutputMode type) +{ + mCliOutputMode = type; +} + +void CnmtProcess::setVerifyMode(bool verify) +{ + mVerify = verify; +} + +const nn::hac::ContentMeta& CnmtProcess::getContentMeta() const +{ + return mCnmt; +} + +void CnmtProcess::importCnmt() +{ + fnd::Vec scratch; + + if (*mFile == nullptr) + { + throw fnd::Exception(kModuleName, "No file reader set."); + } + + scratch.alloc((*mFile)->size()); + (*mFile)->read(scratch.data(), 0, scratch.size()); + + mCnmt.fromBytes(scratch.data(), scratch.size()); +} + +void CnmtProcess::displayCnmt() +{ +#define _SPLIT_VER(ver) (uint32_t)((ver>>26) & 0x3f) << "." << (uint32_t)((ver>>20) & 0x3f) << "." << (uint32_t)((ver>>16) & 0xf) << "." << (uint32_t)(ver & 0xffff) + + std::cout << "[ContentMeta]" << std::endl; + std::cout << " TitleId: 0x" << std::hex << std::setw(16) << std::setfill('0') << mCnmt.getTitleId() << std::endl; + std::cout << " Version: v" << std::dec << mCnmt.getTitleVersion() << " (" << _SPLIT_VER(mCnmt.getTitleVersion()) << ")"<< std::endl; + std::cout << " Type: " << getContentMetaTypeStr(mCnmt.getContentMetaType()) << " (" << std::dec << mCnmt.getContentMetaType() << ")" << std::endl; + std::cout << " Attributes: 0x" << std::hex << (uint32_t)mCnmt.getAttributes() << std::endl; + std::cout << " IncludesExFatDriver: " << getBoolStr(_HAS_BIT(mCnmt.getAttributes(), nn::hac::cnmt::ATTRIBUTE_INCLUDES_EX_FAT_DRIVER)) << std::endl; + std::cout << " Rebootless: " << getBoolStr(_HAS_BIT(mCnmt.getAttributes(), nn::hac::cnmt::ATTRIBUTE_REBOOTLESS)) << std::endl; + std::cout << " RequiredDownloadSystemVersion: v" << mCnmt.getRequiredDownloadSystemVersion() << " (" << _SPLIT_VER(mCnmt.getRequiredDownloadSystemVersion()) << ")"<< std::endl; + switch(mCnmt.getContentMetaType()) + { + case (nn::hac::cnmt::METATYPE_APPLICATION): + std::cout << " ApplicationExtendedHeader:" << std::endl; + std::cout << " RequiredSystemVersion: v" << std::dec << mCnmt.getApplicationMetaExtendedHeader().getRequiredSystemVersion() << " (" << _SPLIT_VER(mCnmt.getApplicationMetaExtendedHeader().getRequiredSystemVersion()) << ")"<< std::endl; + std::cout << " PatchId: 0x" << std::hex << std::setw(16) << std::setfill('0') << mCnmt.getApplicationMetaExtendedHeader().getPatchId() << std::endl; + break; + case (nn::hac::cnmt::METATYPE_PATCH): + std::cout << " PatchMetaExtendedHeader:" << std::endl; + std::cout << " RequiredSystemVersion: v" << std::dec << mCnmt.getPatchMetaExtendedHeader().getRequiredSystemVersion() << " (" << _SPLIT_VER(mCnmt.getPatchMetaExtendedHeader().getRequiredSystemVersion()) << ")"<< std::endl; + std::cout << " ApplicationId: 0x" << std::hex << std::setw(16) << std::setfill('0') << mCnmt.getPatchMetaExtendedHeader().getApplicationId() << std::endl; + break; + case (nn::hac::cnmt::METATYPE_ADD_ON_CONTENT): + std::cout << " AddOnContentMetaExtendedHeader:" << std::endl; + std::cout << " RequiredApplicationVersion: v" << std::dec << mCnmt.getAddOnContentMetaExtendedHeader().getRequiredApplicationVersion() << " (" << _SPLIT_VER(mCnmt.getAddOnContentMetaExtendedHeader().getRequiredApplicationVersion()) << ")" << std::endl; + std::cout << " ApplicationId: 0x" << std::hex << std::setw(16) << std::setfill('0') << mCnmt.getAddOnContentMetaExtendedHeader().getApplicationId() << std::endl; + break; + case (nn::hac::cnmt::METATYPE_DELTA): + std::cout << " DeltaMetaExtendedHeader:" << std::endl; + std::cout << " ApplicationId: 0x" << std::hex << std::setw(16) << std::setfill('0') << mCnmt.getDeltaMetaExtendedHeader().getApplicationId() << std::endl; + break; + default: + break; + } + if (mCnmt.getContentInfo().size() > 0) + { + printf(" ContentInfo:\n"); + for (size_t i = 0; i < mCnmt.getContentInfo().size(); i++) + { + const nn::hac::ContentInfo& info = mCnmt.getContentInfo()[i]; + std::cout << " " << std::dec << i << std::endl; + std::cout << " Type: " << getContentTypeStr(info.getContentType()) << " (" << std::dec << info.getContentType() << ")" << std::endl; + std::cout << " Id: " << fnd::SimpleTextOutput::arrayToString(info.getContentId().data, nn::hac::cnmt::kContentIdLen, false, "") << std::endl; + std::cout << " Size: 0x" << std::hex << info.getContentSize() << std::endl; + std::cout << " Hash: " << fnd::SimpleTextOutput::arrayToString(info.getContentHash().bytes, sizeof(info.getContentHash()), false, "") << std::endl; + } + } + if (mCnmt.getContentMetaInfo().size() > 0) + { + std::cout << " ContentMetaInfo:" << std::endl; + for (size_t i = 0; i < mCnmt.getContentMetaInfo().size(); i++) + { + const nn::hac::ContentMetaInfo& info = mCnmt.getContentMetaInfo()[i]; + std::cout << " " << std::dec << i << std::endl; + std::cout << " Id: 0x" << std::hex << std::setw(16) << std::setfill('0') << info.getTitleId() << std::endl; + std::cout << " Version: v" << std::dec << info.getTitleVersion() << " (" << _SPLIT_VER(info.getTitleVersion()) << ")"<< std::endl; + std::cout << " Type: " << getContentMetaTypeStr(info.getContentMetaType()) << " (" << std::dec << info.getContentMetaType() << ")" << std::endl; + std::cout << " Attributes: 0x" << std::hex << (uint32_t)info.getAttributes() << std::endl; + std::cout << " IncludesExFatDriver: " << getBoolStr(_HAS_BIT(info.getAttributes(), nn::hac::cnmt::ATTRIBUTE_INCLUDES_EX_FAT_DRIVER)) << std::endl; + std::cout << " Rebootless: " << getBoolStr(_HAS_BIT(info.getAttributes(), nn::hac::cnmt::ATTRIBUTE_REBOOTLESS)) << std::endl; + } + } + + std::cout << " Digest: " << fnd::SimpleTextOutput::arrayToString(mCnmt.getDigest().data, nn::hac::cnmt::kDigestLen, false, "") << std::endl; + +#undef _SPLIT_VER +} + +const char* CnmtProcess::getBoolStr(bool state) const +{ + return state? "TRUE" : "FALSE"; +} + +const char* CnmtProcess::getContentTypeStr(nn::hac::cnmt::ContentType type) const +{ + const char* str = nullptr; + + switch (type) + { + case (nn::hac::cnmt::TYPE_META): + str = "Meta"; + break; + case (nn::hac::cnmt::TYPE_PROGRAM): + str = "Program"; + break; + case (nn::hac::cnmt::TYPE_DATA): + str = "Data"; + break; + case (nn::hac::cnmt::TYPE_CONTROL): + str = "Control"; + break; + case (nn::hac::cnmt::TYPE_HTML_DOCUMENT): + str = "HtmlDocument"; + break; + case (nn::hac::cnmt::TYPE_LEGAL_INFORMATION): + str = "LegalInformation"; + break; + case (nn::hac::cnmt::TYPE_DELTA_FRAGMENT): + str = "DeltaFragment"; + break; + default: + str = "Unknown"; + break; + } + + return str; +} + +const char* CnmtProcess::getContentMetaTypeStr(nn::hac::cnmt::ContentMetaType type) const +{ + const char* str = nullptr; + + switch (type) + { + case (nn::hac::cnmt::METATYPE_SYSTEM_PROGRAM): + str = "SystemProgram"; + break; + case (nn::hac::cnmt::METATYPE_SYSTEM_DATA): + str = "SystemData"; + break; + case (nn::hac::cnmt::METATYPE_SYSTEM_UPDATE): + str = "SystemUpdate"; + break; + case (nn::hac::cnmt::METATYPE_BOOT_IMAGE_PACKAGE): + str = "BootImagePackage"; + break; + case (nn::hac::cnmt::METATYPE_BOOT_IMAGE_PACKAGE_SAFE): + str = "BootImagePackageSafe"; + break; + case (nn::hac::cnmt::METATYPE_APPLICATION): + str = "Application"; + break; + case (nn::hac::cnmt::METATYPE_PATCH): + str = "Patch"; + break; + case (nn::hac::cnmt::METATYPE_ADD_ON_CONTENT): + str = "AddOnContent"; + break; + case (nn::hac::cnmt::METATYPE_DELTA): + str = "Delta"; + break; + default: + str = "Unknown"; + break; + } + + return str; +} + +const char* CnmtProcess::getUpdateTypeStr(nn::hac::cnmt::UpdateType type) const +{ + const char* str = nullptr; + + switch (type) + { + case (nn::hac::cnmt::UPDATETYPE_APPLY_AS_DELTA): + str = "ApplyAsDelta"; + break; + case (nn::hac::cnmt::UPDATETYPE_OVERWRITE): + str = "Overwrite"; + break; + case (nn::hac::cnmt::UPDATETYPE_CREATE): + str = "Create"; + break; + default: + str = "Unknown"; + break; + } + + return str; +} + +const char* CnmtProcess::getContentMetaAttrStr(nn::hac::cnmt::ContentMetaAttribute attr) const +{ + const char* str = nullptr; + + switch (attr) + { + case (nn::hac::cnmt::ATTRIBUTE_INCLUDES_EX_FAT_DRIVER): + str = "IncludesExFatDriver"; + break; + case (nn::hac::cnmt::ATTRIBUTE_REBOOTLESS): + str = "Rebootless"; + break; + default: + str = "Unknown"; + break; + } + + return str; +} diff --git a/programs/nstool/source/CnmtProcess.h b/src/CnmtProcess.h similarity index 96% rename from programs/nstool/source/CnmtProcess.h rename to src/CnmtProcess.h index 36cef2a..a9834fa 100644 --- a/programs/nstool/source/CnmtProcess.h +++ b/src/CnmtProcess.h @@ -1,40 +1,40 @@ -#pragma once -#include -#include -#include -#include -#include - -#include "common.h" - -class CnmtProcess -{ -public: - CnmtProcess(); - - void process(); - - void setInputFile(const fnd::SharedPtr& file); - void setCliOutputMode(CliOutputMode type); - void setVerifyMode(bool verify); - - const nn::hac::ContentMeta& getContentMeta() const; - -private: - const std::string kModuleName = "CnmtProcess"; - - fnd::SharedPtr mFile; - CliOutputMode mCliOutputMode; - bool mVerify; - - nn::hac::ContentMeta mCnmt; - - void importCnmt(); - void displayCnmt(); - - const char* getBoolStr(bool state) const; - const char* getContentTypeStr(nn::hac::cnmt::ContentType type) const; - const char* getContentMetaTypeStr(nn::hac::cnmt::ContentMetaType type) const; - const char* getUpdateTypeStr(nn::hac::cnmt::UpdateType type) const; - const char* getContentMetaAttrStr(nn::hac::cnmt::ContentMetaAttribute attr) const; +#pragma once +#include +#include +#include +#include +#include + +#include "common.h" + +class CnmtProcess +{ +public: + CnmtProcess(); + + void process(); + + void setInputFile(const fnd::SharedPtr& file); + void setCliOutputMode(CliOutputMode type); + void setVerifyMode(bool verify); + + const nn::hac::ContentMeta& getContentMeta() const; + +private: + const std::string kModuleName = "CnmtProcess"; + + fnd::SharedPtr mFile; + CliOutputMode mCliOutputMode; + bool mVerify; + + nn::hac::ContentMeta mCnmt; + + void importCnmt(); + void displayCnmt(); + + const char* getBoolStr(bool state) const; + const char* getContentTypeStr(nn::hac::cnmt::ContentType type) const; + const char* getContentMetaTypeStr(nn::hac::cnmt::ContentMetaType type) const; + const char* getUpdateTypeStr(nn::hac::cnmt::UpdateType type) const; + const char* getContentMetaAttrStr(nn::hac::cnmt::ContentMetaAttribute attr) const; }; \ No newline at end of file diff --git a/programs/nstool/source/ElfSymbolParser.cpp b/src/ElfSymbolParser.cpp similarity index 100% rename from programs/nstool/source/ElfSymbolParser.cpp rename to src/ElfSymbolParser.cpp diff --git a/programs/nstool/source/ElfSymbolParser.h b/src/ElfSymbolParser.h similarity index 100% rename from programs/nstool/source/ElfSymbolParser.h rename to src/ElfSymbolParser.h diff --git a/programs/nstool/source/EsTikProcess.cpp b/src/EsTikProcess.cpp similarity index 100% rename from programs/nstool/source/EsTikProcess.cpp rename to src/EsTikProcess.cpp diff --git a/programs/nstool/source/EsTikProcess.h b/src/EsTikProcess.h similarity index 100% rename from programs/nstool/source/EsTikProcess.h rename to src/EsTikProcess.h diff --git a/programs/nstool/source/GameCardProcess.cpp b/src/GameCardProcess.cpp similarity index 100% rename from programs/nstool/source/GameCardProcess.cpp rename to src/GameCardProcess.cpp diff --git a/programs/nstool/source/GameCardProcess.h b/src/GameCardProcess.h similarity index 100% rename from programs/nstool/source/GameCardProcess.h rename to src/GameCardProcess.h diff --git a/programs/nstool/source/IniProcess.cpp b/src/IniProcess.cpp similarity index 100% rename from programs/nstool/source/IniProcess.cpp rename to src/IniProcess.cpp diff --git a/programs/nstool/source/IniProcess.h b/src/IniProcess.h similarity index 100% rename from programs/nstool/source/IniProcess.h rename to src/IniProcess.h diff --git a/programs/nstool/source/KeyConfiguration.cpp b/src/KeyConfiguration.cpp similarity index 97% rename from programs/nstool/source/KeyConfiguration.cpp rename to src/KeyConfiguration.cpp index d674319..d268096 100644 --- a/programs/nstool/source/KeyConfiguration.cpp +++ b/src/KeyConfiguration.cpp @@ -1,376 +1,376 @@ -#include "KeyConfiguration.h" -#include -#include -#include -#include - -KeyConfiguration::KeyConfiguration() -{ - clearGeneralKeyConfiguration(); - clearNcaExternalKeys(); -} - -KeyConfiguration::KeyConfiguration(const KeyConfiguration& other) -{ - *this = other; -} - -void KeyConfiguration::operator=(const KeyConfiguration& other) -{ - mAcidSignKey = other.mAcidSignKey; - mPkg2SignKey = other.mPkg2SignKey; - mContentArchiveHeader0SignKey = other.mContentArchiveHeader0SignKey; - mXciHeaderSignKey = other.mXciHeaderSignKey; - - mContentArchiveHeaderKey = other.mContentArchiveHeaderKey; - mXciHeaderKey = other.mXciHeaderKey; - - for (size_t i = 0; i < kMasterKeyNum; i++) - { - mPkg2Key[i] = other.mPkg2Key[i]; - mPkg1Key[i] = other.mPkg1Key[i]; - mNcaKeyAreaEncryptionKey[0][i] = other.mNcaKeyAreaEncryptionKey[0][i]; - mNcaKeyAreaEncryptionKey[1][i] = other.mNcaKeyAreaEncryptionKey[1][i]; - mNcaKeyAreaEncryptionKey[2][i] = other.mNcaKeyAreaEncryptionKey[2][i]; - mNcaKeyAreaEncryptionKeyHw[0][i] = other.mNcaKeyAreaEncryptionKeyHw[0][i]; - mNcaKeyAreaEncryptionKeyHw[1][i] = other.mNcaKeyAreaEncryptionKeyHw[1][i]; - mNcaKeyAreaEncryptionKeyHw[2][i] = other.mNcaKeyAreaEncryptionKeyHw[2][i]; - mETicketCommonKey[i] = other.mETicketCommonKey[i]; - } - - mPkiRootKeyList = other.mPkiRootKeyList; - - mNcaExternalContentKeyList = other.mNcaExternalContentKeyList; -} - -void KeyConfiguration::importHactoolGenericKeyfile(const std::string& path) -{ - clearGeneralKeyConfiguration(); - - fnd::ResourceFileReader res; - try - { - res.processFile(path); - } - catch (const fnd::Exception&) - { - throw fnd::Exception(kModuleName, "Failed to open key file: " + path); - } - - // internally used sources - fnd::aes::sAes128Key master_key[kMasterKeyNum] = { kNullAesKey }; - fnd::aes::sAes128Key package2_key_source = kNullAesKey; - fnd::aes::sAes128Key ticket_titlekek_source = kNullAesKey; - fnd::aes::sAes128Key key_area_key_source[kNcaKeakNum] = { kNullAesKey, kNullAesKey, kNullAesKey }; - fnd::aes::sAes128Key aes_kek_generation_source = kNullAesKey; - fnd::aes::sAes128Key aes_key_generation_source = kNullAesKey; - fnd::aes::sAes128Key nca_header_kek_source = kNullAesKey; - fnd::aes::sAesXts128Key nca_header_key_source = kNullAesXtsKey; - fnd::rsa::sRsa4096Key pki_root_sign_key = kNullRsa4096Key; - -#define _CONCAT_2_STRINGS(str1, str2) ((str1) + "_" + (str2)) -#define _CONCAT_3_STRINGS(str1, str2, str3) _CONCAT_2_STRINGS(_CONCAT_2_STRINGS(str1, str2), str3) - - std::string key,val; - fnd::Vec dec_array; - -#define _SAVE_KEYDATA(key_name, array, len) \ - key = (key_name); \ - val = res[key]; \ - if (val.empty() == false) { \ - fnd::SimpleTextOutput::stringToArray(val, dec_array); \ - if (dec_array.size() != len) \ - throw fnd::Exception(kModuleName, "Key: \"" + key_name + "\" has incorrect length"); \ - memcpy(array, dec_array.data(), len); \ - } - - for (size_t nameidx = 0; nameidx < kNameVariantNum; nameidx++) - { - // import sources - _SAVE_KEYDATA(_CONCAT_3_STRINGS(kPkg2Base[nameidx], kKeyStr, kSourceStr), package2_key_source.key, 0x10); - _SAVE_KEYDATA(_CONCAT_2_STRINGS(kTicketCommonKeyBase[nameidx], kSourceStr), ticket_titlekek_source.key, 0x10); - _SAVE_KEYDATA(_CONCAT_3_STRINGS(kNcaKeyAreaEncKeyBase[nameidx], kNcaKeyAreaKeyIndexStr[0], kSourceStr), key_area_key_source[0].key, 0x10); - _SAVE_KEYDATA(_CONCAT_3_STRINGS(kNcaKeyAreaEncKeyBase[nameidx], kNcaKeyAreaKeyIndexStr[1], kSourceStr), key_area_key_source[1].key, 0x10); - _SAVE_KEYDATA(_CONCAT_3_STRINGS(kNcaKeyAreaEncKeyBase[nameidx], kNcaKeyAreaKeyIndexStr[2], kSourceStr), key_area_key_source[2].key, 0x10); - _SAVE_KEYDATA(_CONCAT_2_STRINGS(kKekGenBase[nameidx], kSourceStr), aes_kek_generation_source.key, 0x10); - _SAVE_KEYDATA(_CONCAT_2_STRINGS(kKeyGenBase[nameidx], kSourceStr), aes_key_generation_source.key, 0x10); - _SAVE_KEYDATA(_CONCAT_3_STRINGS(kXciHeaderBase[nameidx], kKekStr, kSourceStr), nca_header_kek_source.key, 0x10); - _SAVE_KEYDATA(_CONCAT_3_STRINGS(kXciHeaderBase[nameidx], kKeyStr, kSourceStr), nca_header_key_source.key, 0x20); - - // Store Key Variants/Derivatives - for (size_t mkeyidx = 0; mkeyidx < kMasterKeyNum; mkeyidx++) - { - - _SAVE_KEYDATA(_CONCAT_3_STRINGS(kMasterBase[nameidx], kKeyStr, kKeyIndex[mkeyidx]), master_key[mkeyidx].key, 0x10); - _SAVE_KEYDATA(_CONCAT_3_STRINGS(kPkg1Base[nameidx], kKeyStr, kKeyIndex[mkeyidx]), mPkg1Key[mkeyidx].key, 0x10); - _SAVE_KEYDATA(_CONCAT_3_STRINGS(kPkg2Base[nameidx], kKeyStr, kKeyIndex[mkeyidx]), mPkg2Key[mkeyidx].key, 0x10); - _SAVE_KEYDATA(_CONCAT_2_STRINGS(kTicketCommonKeyBase[nameidx], kKeyIndex[mkeyidx]), mETicketCommonKey[mkeyidx].key, 0x10); - _SAVE_KEYDATA(_CONCAT_3_STRINGS(kNcaKeyAreaEncKeyBase[nameidx], kNcaKeyAreaKeyIndexStr[0], kKeyIndex[mkeyidx]), mNcaKeyAreaEncryptionKey[0][mkeyidx].key, 0x10); - _SAVE_KEYDATA(_CONCAT_3_STRINGS(kNcaKeyAreaEncKeyBase[nameidx], kNcaKeyAreaKeyIndexStr[1], kKeyIndex[mkeyidx]), mNcaKeyAreaEncryptionKey[1][mkeyidx].key, 0x10); - _SAVE_KEYDATA(_CONCAT_3_STRINGS(kNcaKeyAreaEncKeyBase[nameidx], kNcaKeyAreaKeyIndexStr[2], kKeyIndex[mkeyidx]), mNcaKeyAreaEncryptionKey[2][mkeyidx].key, 0x10); - _SAVE_KEYDATA(_CONCAT_3_STRINGS(kNcaKeyAreaEncKeyHwBase[nameidx], kNcaKeyAreaKeyIndexStr[0], kKeyIndex[mkeyidx]), mNcaKeyAreaEncryptionKeyHw[0][mkeyidx].key, 0x10); - _SAVE_KEYDATA(_CONCAT_3_STRINGS(kNcaKeyAreaEncKeyHwBase[nameidx], kNcaKeyAreaKeyIndexStr[1], kKeyIndex[mkeyidx]), mNcaKeyAreaEncryptionKeyHw[1][mkeyidx].key, 0x10); - _SAVE_KEYDATA(_CONCAT_3_STRINGS(kNcaKeyAreaEncKeyHwBase[nameidx], kNcaKeyAreaKeyIndexStr[2], kKeyIndex[mkeyidx]), mNcaKeyAreaEncryptionKeyHw[2][mkeyidx].key, 0x10); - } - - // store nca header key - _SAVE_KEYDATA(_CONCAT_2_STRINGS(kContentArchiveHeaderBase[nameidx], kKeyStr), mContentArchiveHeaderKey.key[0], 0x20); - - // store xci header key - _SAVE_KEYDATA(_CONCAT_2_STRINGS(kXciHeaderBase[nameidx], kKeyStr), mXciHeaderKey.key, 0x10); - - // store rsa keys - _SAVE_KEYDATA(_CONCAT_2_STRINGS(kContentArchiveHeaderBase[nameidx], kRsaKeyPrivate), mContentArchiveHeader0SignKey.priv_exponent, fnd::rsa::kRsa2048Size); - _SAVE_KEYDATA(_CONCAT_2_STRINGS(kContentArchiveHeaderBase[nameidx], kRsaKeyModulus), mContentArchiveHeader0SignKey.modulus, fnd::rsa::kRsa2048Size); - - _SAVE_KEYDATA(_CONCAT_2_STRINGS(kXciHeaderBase[nameidx], kRsaKeyPrivate), mXciHeaderSignKey.priv_exponent, fnd::rsa::kRsa2048Size); - _SAVE_KEYDATA(_CONCAT_2_STRINGS(kXciHeaderBase[nameidx], kRsaKeyModulus), mXciHeaderSignKey.modulus, fnd::rsa::kRsa2048Size); - - _SAVE_KEYDATA(_CONCAT_2_STRINGS(kAcidBase[nameidx], kRsaKeyPrivate), mAcidSignKey.priv_exponent, fnd::rsa::kRsa2048Size); - _SAVE_KEYDATA(_CONCAT_2_STRINGS(kAcidBase[nameidx], kRsaKeyModulus), mAcidSignKey.modulus, fnd::rsa::kRsa2048Size); - - _SAVE_KEYDATA(_CONCAT_2_STRINGS(kPkg2Base[nameidx], kRsaKeyPrivate), mPkg2SignKey.priv_exponent, fnd::rsa::kRsa2048Size); - _SAVE_KEYDATA(_CONCAT_2_STRINGS(kPkg2Base[nameidx], kRsaKeyModulus), mPkg2SignKey.modulus, fnd::rsa::kRsa2048Size); - - _SAVE_KEYDATA(_CONCAT_2_STRINGS(kPkiRootBase[nameidx], kRsaKeyPrivate), pki_root_sign_key.priv_exponent, fnd::rsa::kRsa4096Size); - _SAVE_KEYDATA(_CONCAT_2_STRINGS(kPkiRootBase[nameidx], kRsaKeyModulus), pki_root_sign_key.modulus, fnd::rsa::kRsa4096Size); - } - -#undef _SAVE_KEYDATA -#undef _CONCAT_3_STRINGS -#undef _CONCAT_2_STRINGS - - // Derive keys - for (size_t i = 0; i < kMasterKeyNum; i++) - { - if (master_key[i] != kNullAesKey) - { - if (aes_kek_generation_source != kNullAesKey && aes_key_generation_source != kNullAesKey) - { - if (i == 0 && nca_header_kek_source != kNullAesKey && nca_header_key_source != kNullAesXtsKey) - { - if (mContentArchiveHeaderKey == kNullAesXtsKey) - { - fnd::aes::sAes128Key nca_header_kek; - nn::hac::AesKeygen::generateKey(nca_header_kek.key, aes_kek_generation_source.key, nca_header_kek_source.key, aes_key_generation_source.key, master_key[i].key); - nn::hac::AesKeygen::generateKey(mContentArchiveHeaderKey.key[0], nca_header_key_source.key[0], nca_header_kek.key); - nn::hac::AesKeygen::generateKey(mContentArchiveHeaderKey.key[1], nca_header_key_source.key[1], nca_header_kek.key); - } - } - - for (size_t j = 0; j < nn::hac::nca::kKeyAreaEncryptionKeyNum; j++) - { - if (key_area_key_source[j] != kNullAesKey && mNcaKeyAreaEncryptionKey[j][i] == kNullAesKey) - { - nn::hac::AesKeygen::generateKey(mNcaKeyAreaEncryptionKey[j][i].key, aes_kek_generation_source.key, key_area_key_source[j].key, aes_key_generation_source.key, master_key[i].key); - } - } - } - - if (ticket_titlekek_source != kNullAesKey && mETicketCommonKey[i] == kNullAesKey) - { - nn::hac::AesKeygen::generateKey(mETicketCommonKey[i].key, ticket_titlekek_source.key, master_key[i].key); - } - if (package2_key_source != kNullAesKey && mPkg2Key[i] == kNullAesKey) - { - nn::hac::AesKeygen::generateKey(mPkg2Key[i].key, package2_key_source.key, master_key[i].key); - } - } - } - - // populate pki root keys - if (pki_root_sign_key != kNullRsa4096Key) - { - sPkiRootKey tmp; - - tmp.name = nn::pki::sign::kRootIssuerStr; - tmp.key_type = nn::pki::sign::SIGN_ALGO_RSA4096; - tmp.rsa4096_key = pki_root_sign_key; - - mPkiRootKeyList.addElement(tmp); - } -} - - -void KeyConfiguration::clearGeneralKeyConfiguration() -{ - mAcidSignKey = kNullRsa2048Key; - mPkg2SignKey = kNullRsa2048Key; - mContentArchiveHeader0SignKey = kNullRsa2048Key; - mXciHeaderSignKey = kNullRsa2048Key; - mPkiRootKeyList.clear(); - - mContentArchiveHeaderKey = kNullAesXtsKey; - mXciHeaderKey = kNullAesKey; - - for (size_t i = 0; i < kMasterKeyNum; i++) - { - mPkg1Key[i] = kNullAesKey; - mPkg2Key[i] = kNullAesKey; - mETicketCommonKey[i] = kNullAesKey; - for (size_t j = 0; j < kNcaKeakNum; j++) - { - mNcaKeyAreaEncryptionKey[j][i] = kNullAesKey; - mNcaKeyAreaEncryptionKey[j][i] = kNullAesKey; - } - } -} - -void KeyConfiguration::clearNcaExternalKeys() -{ - mNcaExternalContentKeyList.clear(); -} - -bool KeyConfiguration::getContentArchiveHeaderKey(fnd::aes::sAesXts128Key& key) const -{ - return copyOutKeyResourceIfExists(mContentArchiveHeaderKey, key, kNullAesXtsKey); -} - -bool KeyConfiguration::getContentArchiveHeader0SignKey(fnd::rsa::sRsa2048Key& key) const -{ - return copyOutKeyResourceIfExists(mContentArchiveHeader0SignKey, key, kNullRsa2048Key); -} - -bool KeyConfiguration::getAcidSignKey(fnd::rsa::sRsa2048Key& key) const -{ - return copyOutKeyResourceIfExists(mAcidSignKey, key, kNullRsa2048Key); -} - -bool KeyConfiguration::getNcaKeyAreaEncryptionKey(byte_t masterkey_index, byte_t keak_type, fnd::aes::sAes128Key& key) const -{ - if (keak_type >= kNcaKeakNum || masterkey_index >= kMasterKeyNum) - { - return false; - } - return copyOutKeyResourceIfExists(mNcaKeyAreaEncryptionKey[keak_type][masterkey_index], key, kNullAesKey); -} - -bool KeyConfiguration::getNcaKeyAreaEncryptionKeyHw(byte_t masterkey_index, byte_t keak_type, fnd::aes::sAes128Key& key) const -{ - if (keak_type >= kNcaKeakNum || masterkey_index >= kMasterKeyNum) - { - return false; - } - return copyOutKeyResourceIfExists(mNcaKeyAreaEncryptionKeyHw[keak_type][masterkey_index], key, kNullAesKey); -} - -void KeyConfiguration::addNcaExternalContentKey(const byte_t rights_id[nn::hac::nca::kRightsIdLen], const fnd::aes::sAes128Key& key) -{ - sNcaExternalContentKey tmp; - memcpy(tmp.rights_id.data, rights_id, nn::hac::nca::kRightsIdLen); - tmp.key = key; - - if (mNcaExternalContentKeyList.hasElement(tmp)) - return; - - mNcaExternalContentKeyList.addElement(tmp); -} - -bool KeyConfiguration::getNcaExternalContentKey(const byte_t rights_id[nn::hac::nca::kRightsIdLen], fnd::aes::sAes128Key& key) const -{ - sRightsId id; - bool res_exists = false; - - memcpy(id.data, rights_id, nn::hac::nca::kRightsIdLen); - for (size_t i = 0; i < mNcaExternalContentKeyList.size(); i++) - { - if (mNcaExternalContentKeyList[i].rights_id == id) - { - res_exists = true; - key = mNcaExternalContentKeyList[i].key; - break; - } - } - - return res_exists; -} - -bool KeyConfiguration::getPkg1Key(byte_t masterkey_index, fnd::aes::sAes128Key& key) const -{ - if (masterkey_index >= kMasterKeyNum) - { - return false; - } - return copyOutKeyResourceIfExists(mPkg1Key[masterkey_index], key, kNullAesKey); -} - -bool KeyConfiguration::getPkg2Key(byte_t masterkey_index, fnd::aes::sAes128Key& key) const -{ - if (masterkey_index >= kMasterKeyNum) - { - return false; - } - return copyOutKeyResourceIfExists(mPkg2Key[masterkey_index], key, kNullAesKey); -} - -bool KeyConfiguration::getPkg2SignKey(fnd::rsa::sRsa2048Key& key) const -{ - return copyOutKeyResourceIfExists(mPkg2SignKey, key, kNullRsa2048Key); -} - -bool KeyConfiguration::getXciHeaderSignKey(fnd::rsa::sRsa2048Key& key) const -{ - return copyOutKeyResourceIfExists(mXciHeaderSignKey, key, kNullRsa2048Key); -} - -bool KeyConfiguration::getXciHeaderKey(fnd::aes::sAes128Key& key) const -{ - return copyOutKeyResourceIfExists(mXciHeaderKey, key, kNullAesKey); -} - -bool KeyConfiguration::getETicketCommonKey(byte_t masterkey_index, fnd::aes::sAes128Key& key) const -{ - if (masterkey_index >= kMasterKeyNum) - { - return false; - } - return copyOutKeyResourceIfExists(mETicketCommonKey[masterkey_index], key, kNullAesKey); -} - -bool KeyConfiguration::getPkiRootSignKey(const std::string& root_name, fnd::rsa::sRsa4096Key& key) const -{ - bool res_exists = false; - for (size_t i = 0; i < mPkiRootKeyList.size(); i++) - { - if (root_name == mPkiRootKeyList[i].name && mPkiRootKeyList[i].key_type == nn::pki::sign::SIGN_ALGO_RSA4096) - { - res_exists = true; - key = mPkiRootKeyList[i].rsa4096_key; - break; - } - } - - return res_exists; -} - -bool KeyConfiguration::getPkiRootSignKey(const std::string& root_name, fnd::rsa::sRsa2048Key& key) const -{ - bool res_exists = false; - for (size_t i = 0; i < mPkiRootKeyList.size(); i++) - { - if (root_name == mPkiRootKeyList[i].name && mPkiRootKeyList[i].key_type == nn::pki::sign::SIGN_ALGO_RSA2048) - { - res_exists = true; - key = mPkiRootKeyList[i].rsa2048_key; - break; - } - } - - return res_exists; -} - -bool KeyConfiguration::getPkiRootSignKey(const std::string& root_name, fnd::ecdsa::sEcdsa240Key& key) const -{ - bool res_exists = false; - for (size_t i = 0; i < mPkiRootKeyList.size(); i++) - { - if (root_name == mPkiRootKeyList[i].name && mPkiRootKeyList[i].key_type == nn::pki::sign::SIGN_ALGO_ECDSA240) - { - res_exists = true; - key = mPkiRootKeyList[i].ecdsa240_key; - break; - } - } - - return res_exists; +#include "KeyConfiguration.h" +#include +#include +#include +#include + +KeyConfiguration::KeyConfiguration() +{ + clearGeneralKeyConfiguration(); + clearNcaExternalKeys(); +} + +KeyConfiguration::KeyConfiguration(const KeyConfiguration& other) +{ + *this = other; +} + +void KeyConfiguration::operator=(const KeyConfiguration& other) +{ + mAcidSignKey = other.mAcidSignKey; + mPkg2SignKey = other.mPkg2SignKey; + mContentArchiveHeader0SignKey = other.mContentArchiveHeader0SignKey; + mXciHeaderSignKey = other.mXciHeaderSignKey; + + mContentArchiveHeaderKey = other.mContentArchiveHeaderKey; + mXciHeaderKey = other.mXciHeaderKey; + + for (size_t i = 0; i < kMasterKeyNum; i++) + { + mPkg2Key[i] = other.mPkg2Key[i]; + mPkg1Key[i] = other.mPkg1Key[i]; + mNcaKeyAreaEncryptionKey[0][i] = other.mNcaKeyAreaEncryptionKey[0][i]; + mNcaKeyAreaEncryptionKey[1][i] = other.mNcaKeyAreaEncryptionKey[1][i]; + mNcaKeyAreaEncryptionKey[2][i] = other.mNcaKeyAreaEncryptionKey[2][i]; + mNcaKeyAreaEncryptionKeyHw[0][i] = other.mNcaKeyAreaEncryptionKeyHw[0][i]; + mNcaKeyAreaEncryptionKeyHw[1][i] = other.mNcaKeyAreaEncryptionKeyHw[1][i]; + mNcaKeyAreaEncryptionKeyHw[2][i] = other.mNcaKeyAreaEncryptionKeyHw[2][i]; + mETicketCommonKey[i] = other.mETicketCommonKey[i]; + } + + mPkiRootKeyList = other.mPkiRootKeyList; + + mNcaExternalContentKeyList = other.mNcaExternalContentKeyList; +} + +void KeyConfiguration::importHactoolGenericKeyfile(const std::string& path) +{ + clearGeneralKeyConfiguration(); + + fnd::ResourceFileReader res; + try + { + res.processFile(path); + } + catch (const fnd::Exception&) + { + throw fnd::Exception(kModuleName, "Failed to open key file: " + path); + } + + // internally used sources + fnd::aes::sAes128Key master_key[kMasterKeyNum] = { kNullAesKey }; + fnd::aes::sAes128Key package2_key_source = kNullAesKey; + fnd::aes::sAes128Key ticket_titlekek_source = kNullAesKey; + fnd::aes::sAes128Key key_area_key_source[kNcaKeakNum] = { kNullAesKey, kNullAesKey, kNullAesKey }; + fnd::aes::sAes128Key aes_kek_generation_source = kNullAesKey; + fnd::aes::sAes128Key aes_key_generation_source = kNullAesKey; + fnd::aes::sAes128Key nca_header_kek_source = kNullAesKey; + fnd::aes::sAesXts128Key nca_header_key_source = kNullAesXtsKey; + fnd::rsa::sRsa4096Key pki_root_sign_key = kNullRsa4096Key; + +#define _CONCAT_2_STRINGS(str1, str2) ((str1) + "_" + (str2)) +#define _CONCAT_3_STRINGS(str1, str2, str3) _CONCAT_2_STRINGS(_CONCAT_2_STRINGS(str1, str2), str3) + + std::string key,val; + fnd::Vec dec_array; + +#define _SAVE_KEYDATA(key_name, array, len) \ + key = (key_name); \ + val = res[key]; \ + if (val.empty() == false) { \ + fnd::SimpleTextOutput::stringToArray(val, dec_array); \ + if (dec_array.size() != len) \ + throw fnd::Exception(kModuleName, "Key: \"" + key_name + "\" has incorrect length"); \ + memcpy(array, dec_array.data(), len); \ + } + + for (size_t nameidx = 0; nameidx < kNameVariantNum; nameidx++) + { + // import sources + _SAVE_KEYDATA(_CONCAT_3_STRINGS(kPkg2Base[nameidx], kKeyStr, kSourceStr), package2_key_source.key, 0x10); + _SAVE_KEYDATA(_CONCAT_2_STRINGS(kTicketCommonKeyBase[nameidx], kSourceStr), ticket_titlekek_source.key, 0x10); + _SAVE_KEYDATA(_CONCAT_3_STRINGS(kNcaKeyAreaEncKeyBase[nameidx], kNcaKeyAreaKeyIndexStr[0], kSourceStr), key_area_key_source[0].key, 0x10); + _SAVE_KEYDATA(_CONCAT_3_STRINGS(kNcaKeyAreaEncKeyBase[nameidx], kNcaKeyAreaKeyIndexStr[1], kSourceStr), key_area_key_source[1].key, 0x10); + _SAVE_KEYDATA(_CONCAT_3_STRINGS(kNcaKeyAreaEncKeyBase[nameidx], kNcaKeyAreaKeyIndexStr[2], kSourceStr), key_area_key_source[2].key, 0x10); + _SAVE_KEYDATA(_CONCAT_2_STRINGS(kKekGenBase[nameidx], kSourceStr), aes_kek_generation_source.key, 0x10); + _SAVE_KEYDATA(_CONCAT_2_STRINGS(kKeyGenBase[nameidx], kSourceStr), aes_key_generation_source.key, 0x10); + _SAVE_KEYDATA(_CONCAT_3_STRINGS(kXciHeaderBase[nameidx], kKekStr, kSourceStr), nca_header_kek_source.key, 0x10); + _SAVE_KEYDATA(_CONCAT_3_STRINGS(kXciHeaderBase[nameidx], kKeyStr, kSourceStr), nca_header_key_source.key, 0x20); + + // Store Key Variants/Derivatives + for (size_t mkeyidx = 0; mkeyidx < kMasterKeyNum; mkeyidx++) + { + + _SAVE_KEYDATA(_CONCAT_3_STRINGS(kMasterBase[nameidx], kKeyStr, kKeyIndex[mkeyidx]), master_key[mkeyidx].key, 0x10); + _SAVE_KEYDATA(_CONCAT_3_STRINGS(kPkg1Base[nameidx], kKeyStr, kKeyIndex[mkeyidx]), mPkg1Key[mkeyidx].key, 0x10); + _SAVE_KEYDATA(_CONCAT_3_STRINGS(kPkg2Base[nameidx], kKeyStr, kKeyIndex[mkeyidx]), mPkg2Key[mkeyidx].key, 0x10); + _SAVE_KEYDATA(_CONCAT_2_STRINGS(kTicketCommonKeyBase[nameidx], kKeyIndex[mkeyidx]), mETicketCommonKey[mkeyidx].key, 0x10); + _SAVE_KEYDATA(_CONCAT_3_STRINGS(kNcaKeyAreaEncKeyBase[nameidx], kNcaKeyAreaKeyIndexStr[0], kKeyIndex[mkeyidx]), mNcaKeyAreaEncryptionKey[0][mkeyidx].key, 0x10); + _SAVE_KEYDATA(_CONCAT_3_STRINGS(kNcaKeyAreaEncKeyBase[nameidx], kNcaKeyAreaKeyIndexStr[1], kKeyIndex[mkeyidx]), mNcaKeyAreaEncryptionKey[1][mkeyidx].key, 0x10); + _SAVE_KEYDATA(_CONCAT_3_STRINGS(kNcaKeyAreaEncKeyBase[nameidx], kNcaKeyAreaKeyIndexStr[2], kKeyIndex[mkeyidx]), mNcaKeyAreaEncryptionKey[2][mkeyidx].key, 0x10); + _SAVE_KEYDATA(_CONCAT_3_STRINGS(kNcaKeyAreaEncKeyHwBase[nameidx], kNcaKeyAreaKeyIndexStr[0], kKeyIndex[mkeyidx]), mNcaKeyAreaEncryptionKeyHw[0][mkeyidx].key, 0x10); + _SAVE_KEYDATA(_CONCAT_3_STRINGS(kNcaKeyAreaEncKeyHwBase[nameidx], kNcaKeyAreaKeyIndexStr[1], kKeyIndex[mkeyidx]), mNcaKeyAreaEncryptionKeyHw[1][mkeyidx].key, 0x10); + _SAVE_KEYDATA(_CONCAT_3_STRINGS(kNcaKeyAreaEncKeyHwBase[nameidx], kNcaKeyAreaKeyIndexStr[2], kKeyIndex[mkeyidx]), mNcaKeyAreaEncryptionKeyHw[2][mkeyidx].key, 0x10); + } + + // store nca header key + _SAVE_KEYDATA(_CONCAT_2_STRINGS(kContentArchiveHeaderBase[nameidx], kKeyStr), mContentArchiveHeaderKey.key[0], 0x20); + + // store xci header key + _SAVE_KEYDATA(_CONCAT_2_STRINGS(kXciHeaderBase[nameidx], kKeyStr), mXciHeaderKey.key, 0x10); + + // store rsa keys + _SAVE_KEYDATA(_CONCAT_2_STRINGS(kContentArchiveHeaderBase[nameidx], kRsaKeyPrivate), mContentArchiveHeader0SignKey.priv_exponent, fnd::rsa::kRsa2048Size); + _SAVE_KEYDATA(_CONCAT_2_STRINGS(kContentArchiveHeaderBase[nameidx], kRsaKeyModulus), mContentArchiveHeader0SignKey.modulus, fnd::rsa::kRsa2048Size); + + _SAVE_KEYDATA(_CONCAT_2_STRINGS(kXciHeaderBase[nameidx], kRsaKeyPrivate), mXciHeaderSignKey.priv_exponent, fnd::rsa::kRsa2048Size); + _SAVE_KEYDATA(_CONCAT_2_STRINGS(kXciHeaderBase[nameidx], kRsaKeyModulus), mXciHeaderSignKey.modulus, fnd::rsa::kRsa2048Size); + + _SAVE_KEYDATA(_CONCAT_2_STRINGS(kAcidBase[nameidx], kRsaKeyPrivate), mAcidSignKey.priv_exponent, fnd::rsa::kRsa2048Size); + _SAVE_KEYDATA(_CONCAT_2_STRINGS(kAcidBase[nameidx], kRsaKeyModulus), mAcidSignKey.modulus, fnd::rsa::kRsa2048Size); + + _SAVE_KEYDATA(_CONCAT_2_STRINGS(kPkg2Base[nameidx], kRsaKeyPrivate), mPkg2SignKey.priv_exponent, fnd::rsa::kRsa2048Size); + _SAVE_KEYDATA(_CONCAT_2_STRINGS(kPkg2Base[nameidx], kRsaKeyModulus), mPkg2SignKey.modulus, fnd::rsa::kRsa2048Size); + + _SAVE_KEYDATA(_CONCAT_2_STRINGS(kPkiRootBase[nameidx], kRsaKeyPrivate), pki_root_sign_key.priv_exponent, fnd::rsa::kRsa4096Size); + _SAVE_KEYDATA(_CONCAT_2_STRINGS(kPkiRootBase[nameidx], kRsaKeyModulus), pki_root_sign_key.modulus, fnd::rsa::kRsa4096Size); + } + +#undef _SAVE_KEYDATA +#undef _CONCAT_3_STRINGS +#undef _CONCAT_2_STRINGS + + // Derive keys + for (size_t i = 0; i < kMasterKeyNum; i++) + { + if (master_key[i] != kNullAesKey) + { + if (aes_kek_generation_source != kNullAesKey && aes_key_generation_source != kNullAesKey) + { + if (i == 0 && nca_header_kek_source != kNullAesKey && nca_header_key_source != kNullAesXtsKey) + { + if (mContentArchiveHeaderKey == kNullAesXtsKey) + { + fnd::aes::sAes128Key nca_header_kek; + nn::hac::AesKeygen::generateKey(nca_header_kek.key, aes_kek_generation_source.key, nca_header_kek_source.key, aes_key_generation_source.key, master_key[i].key); + nn::hac::AesKeygen::generateKey(mContentArchiveHeaderKey.key[0], nca_header_key_source.key[0], nca_header_kek.key); + nn::hac::AesKeygen::generateKey(mContentArchiveHeaderKey.key[1], nca_header_key_source.key[1], nca_header_kek.key); + } + } + + for (size_t j = 0; j < nn::hac::nca::kKeyAreaEncryptionKeyNum; j++) + { + if (key_area_key_source[j] != kNullAesKey && mNcaKeyAreaEncryptionKey[j][i] == kNullAesKey) + { + nn::hac::AesKeygen::generateKey(mNcaKeyAreaEncryptionKey[j][i].key, aes_kek_generation_source.key, key_area_key_source[j].key, aes_key_generation_source.key, master_key[i].key); + } + } + } + + if (ticket_titlekek_source != kNullAesKey && mETicketCommonKey[i] == kNullAesKey) + { + nn::hac::AesKeygen::generateKey(mETicketCommonKey[i].key, ticket_titlekek_source.key, master_key[i].key); + } + if (package2_key_source != kNullAesKey && mPkg2Key[i] == kNullAesKey) + { + nn::hac::AesKeygen::generateKey(mPkg2Key[i].key, package2_key_source.key, master_key[i].key); + } + } + } + + // populate pki root keys + if (pki_root_sign_key != kNullRsa4096Key) + { + sPkiRootKey tmp; + + tmp.name = nn::pki::sign::kRootIssuerStr; + tmp.key_type = nn::pki::sign::SIGN_ALGO_RSA4096; + tmp.rsa4096_key = pki_root_sign_key; + + mPkiRootKeyList.addElement(tmp); + } +} + + +void KeyConfiguration::clearGeneralKeyConfiguration() +{ + mAcidSignKey = kNullRsa2048Key; + mPkg2SignKey = kNullRsa2048Key; + mContentArchiveHeader0SignKey = kNullRsa2048Key; + mXciHeaderSignKey = kNullRsa2048Key; + mPkiRootKeyList.clear(); + + mContentArchiveHeaderKey = kNullAesXtsKey; + mXciHeaderKey = kNullAesKey; + + for (size_t i = 0; i < kMasterKeyNum; i++) + { + mPkg1Key[i] = kNullAesKey; + mPkg2Key[i] = kNullAesKey; + mETicketCommonKey[i] = kNullAesKey; + for (size_t j = 0; j < kNcaKeakNum; j++) + { + mNcaKeyAreaEncryptionKey[j][i] = kNullAesKey; + mNcaKeyAreaEncryptionKey[j][i] = kNullAesKey; + } + } +} + +void KeyConfiguration::clearNcaExternalKeys() +{ + mNcaExternalContentKeyList.clear(); +} + +bool KeyConfiguration::getContentArchiveHeaderKey(fnd::aes::sAesXts128Key& key) const +{ + return copyOutKeyResourceIfExists(mContentArchiveHeaderKey, key, kNullAesXtsKey); +} + +bool KeyConfiguration::getContentArchiveHeader0SignKey(fnd::rsa::sRsa2048Key& key) const +{ + return copyOutKeyResourceIfExists(mContentArchiveHeader0SignKey, key, kNullRsa2048Key); +} + +bool KeyConfiguration::getAcidSignKey(fnd::rsa::sRsa2048Key& key) const +{ + return copyOutKeyResourceIfExists(mAcidSignKey, key, kNullRsa2048Key); +} + +bool KeyConfiguration::getNcaKeyAreaEncryptionKey(byte_t masterkey_index, byte_t keak_type, fnd::aes::sAes128Key& key) const +{ + if (keak_type >= kNcaKeakNum || masterkey_index >= kMasterKeyNum) + { + return false; + } + return copyOutKeyResourceIfExists(mNcaKeyAreaEncryptionKey[keak_type][masterkey_index], key, kNullAesKey); +} + +bool KeyConfiguration::getNcaKeyAreaEncryptionKeyHw(byte_t masterkey_index, byte_t keak_type, fnd::aes::sAes128Key& key) const +{ + if (keak_type >= kNcaKeakNum || masterkey_index >= kMasterKeyNum) + { + return false; + } + return copyOutKeyResourceIfExists(mNcaKeyAreaEncryptionKeyHw[keak_type][masterkey_index], key, kNullAesKey); +} + +void KeyConfiguration::addNcaExternalContentKey(const byte_t rights_id[nn::hac::nca::kRightsIdLen], const fnd::aes::sAes128Key& key) +{ + sNcaExternalContentKey tmp; + memcpy(tmp.rights_id.data, rights_id, nn::hac::nca::kRightsIdLen); + tmp.key = key; + + if (mNcaExternalContentKeyList.hasElement(tmp)) + return; + + mNcaExternalContentKeyList.addElement(tmp); +} + +bool KeyConfiguration::getNcaExternalContentKey(const byte_t rights_id[nn::hac::nca::kRightsIdLen], fnd::aes::sAes128Key& key) const +{ + sRightsId id; + bool res_exists = false; + + memcpy(id.data, rights_id, nn::hac::nca::kRightsIdLen); + for (size_t i = 0; i < mNcaExternalContentKeyList.size(); i++) + { + if (mNcaExternalContentKeyList[i].rights_id == id) + { + res_exists = true; + key = mNcaExternalContentKeyList[i].key; + break; + } + } + + return res_exists; +} + +bool KeyConfiguration::getPkg1Key(byte_t masterkey_index, fnd::aes::sAes128Key& key) const +{ + if (masterkey_index >= kMasterKeyNum) + { + return false; + } + return copyOutKeyResourceIfExists(mPkg1Key[masterkey_index], key, kNullAesKey); +} + +bool KeyConfiguration::getPkg2Key(byte_t masterkey_index, fnd::aes::sAes128Key& key) const +{ + if (masterkey_index >= kMasterKeyNum) + { + return false; + } + return copyOutKeyResourceIfExists(mPkg2Key[masterkey_index], key, kNullAesKey); +} + +bool KeyConfiguration::getPkg2SignKey(fnd::rsa::sRsa2048Key& key) const +{ + return copyOutKeyResourceIfExists(mPkg2SignKey, key, kNullRsa2048Key); +} + +bool KeyConfiguration::getXciHeaderSignKey(fnd::rsa::sRsa2048Key& key) const +{ + return copyOutKeyResourceIfExists(mXciHeaderSignKey, key, kNullRsa2048Key); +} + +bool KeyConfiguration::getXciHeaderKey(fnd::aes::sAes128Key& key) const +{ + return copyOutKeyResourceIfExists(mXciHeaderKey, key, kNullAesKey); +} + +bool KeyConfiguration::getETicketCommonKey(byte_t masterkey_index, fnd::aes::sAes128Key& key) const +{ + if (masterkey_index >= kMasterKeyNum) + { + return false; + } + return copyOutKeyResourceIfExists(mETicketCommonKey[masterkey_index], key, kNullAesKey); +} + +bool KeyConfiguration::getPkiRootSignKey(const std::string& root_name, fnd::rsa::sRsa4096Key& key) const +{ + bool res_exists = false; + for (size_t i = 0; i < mPkiRootKeyList.size(); i++) + { + if (root_name == mPkiRootKeyList[i].name && mPkiRootKeyList[i].key_type == nn::pki::sign::SIGN_ALGO_RSA4096) + { + res_exists = true; + key = mPkiRootKeyList[i].rsa4096_key; + break; + } + } + + return res_exists; +} + +bool KeyConfiguration::getPkiRootSignKey(const std::string& root_name, fnd::rsa::sRsa2048Key& key) const +{ + bool res_exists = false; + for (size_t i = 0; i < mPkiRootKeyList.size(); i++) + { + if (root_name == mPkiRootKeyList[i].name && mPkiRootKeyList[i].key_type == nn::pki::sign::SIGN_ALGO_RSA2048) + { + res_exists = true; + key = mPkiRootKeyList[i].rsa2048_key; + break; + } + } + + return res_exists; +} + +bool KeyConfiguration::getPkiRootSignKey(const std::string& root_name, fnd::ecdsa::sEcdsa240Key& key) const +{ + bool res_exists = false; + for (size_t i = 0; i < mPkiRootKeyList.size(); i++) + { + if (root_name == mPkiRootKeyList[i].name && mPkiRootKeyList[i].key_type == nn::pki::sign::SIGN_ALGO_ECDSA240) + { + res_exists = true; + key = mPkiRootKeyList[i].ecdsa240_key; + break; + } + } + + return res_exists; } \ No newline at end of file diff --git a/programs/nstool/source/KeyConfiguration.h b/src/KeyConfiguration.h similarity index 97% rename from programs/nstool/source/KeyConfiguration.h rename to src/KeyConfiguration.h index 5716379..cbf2060 100644 --- a/programs/nstool/source/KeyConfiguration.h +++ b/src/KeyConfiguration.h @@ -1,209 +1,209 @@ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include - -class KeyConfiguration -{ -public: - KeyConfiguration(); - KeyConfiguration(const KeyConfiguration& other); - - void operator=(const KeyConfiguration& other); - - void importHactoolGenericKeyfile(const std::string& path); - //void importHactoolTitleKeyfile(const std::string& path); - - void clearGeneralKeyConfiguration(); - void clearNcaExternalKeys(); - - // nca keys - bool getContentArchiveHeaderKey(fnd::aes::sAesXts128Key& key) const; - bool getContentArchiveHeader0SignKey(fnd::rsa::sRsa2048Key& key) const; - bool getAcidSignKey(fnd::rsa::sRsa2048Key& key) const; - bool getNcaKeyAreaEncryptionKey(byte_t masterkey_index, byte_t keak_type, fnd::aes::sAes128Key& key) const; - bool getNcaKeyAreaEncryptionKeyHw(byte_t masterkey_index, byte_t keak_type, fnd::aes::sAes128Key& key) const; - - // external content keys - void addNcaExternalContentKey(const byte_t rights_id[nn::hac::nca::kRightsIdLen], const fnd::aes::sAes128Key& key); - bool getNcaExternalContentKey(const byte_t rights_id[nn::hac::nca::kRightsIdLen], fnd::aes::sAes128Key& key) const; - - // pkg1/pkg2 - bool getPkg1Key(byte_t masterkey_index, fnd::aes::sAes128Key& key) const; - bool getPkg2Key(byte_t masterkey_index, fnd::aes::sAes128Key& key) const; - bool getPkg2SignKey(fnd::rsa::sRsa2048Key& key) const; - - // xci keys - bool getXciHeaderSignKey(fnd::rsa::sRsa2048Key& key) const; - bool getXciHeaderKey(fnd::aes::sAes128Key& key) const; - - // ticket - bool getETicketCommonKey(byte_t masterkey_index, fnd::aes::sAes128Key& key) const; - - // pki - bool getPkiRootSignKey(const std::string& root_name, fnd::rsa::sRsa4096Key& key) const; - bool getPkiRootSignKey(const std::string& root_name, fnd::rsa::sRsa2048Key& key) const; - bool getPkiRootSignKey(const std::string& root_name, fnd::ecdsa::sEcdsa240Key& key) const; -private: - const std::string kModuleName = "KeyConfiguration"; - const fnd::aes::sAes128Key kNullAesKey = {{0}}; - const fnd::aes::sAesXts128Key kNullAesXtsKey = {{{0}}}; - const fnd::rsa::sRsa4096Key kNullRsa4096Key = {{0}, {0}, {0}}; - const fnd::rsa::sRsa2048Key kNullRsa2048Key = {{0}, {0}, {0}}; - static const size_t kMasterKeyNum = 0x20; - static const size_t kNcaKeakNum = nn::hac::nca::kKeyAreaEncryptionKeyNum; - - // keynames - enum NameVariantIndex - { - NNTOOLS, - LEGACY_HACTOOL, - LEGACY_0 - }; - static const size_t kNameVariantNum = 3; - const std::string kMasterBase[kNameVariantNum] = { "master", "master", "master" }; - const std::string kPkg1Base[kNameVariantNum] = { "package1", "package1", "package1" }; - const std::string kPkg2Base[kNameVariantNum] = { "package2", "package2", "package2" }; - const std::string kXciHeaderBase[kNameVariantNum] = { "xci_header", "xci_header", "xci_header" }; - const std::string kContentArchiveHeaderBase[kNameVariantNum] = { "nca_header", "header", "nca_header" }; - const std::string kAcidBase[kNameVariantNum] = { "acid", "acid", "acid" }; - const std::string kPkiRootBase[kNameVariantNum] = { "pki_root", "pki_root", "pki_root" }; - const std::string kTicketCommonKeyBase[kNameVariantNum] = { "ticket_commonkey", "titlekek", "ticket_commonkey" }; - const std::string kNcaKeyAreaEncKeyBase[kNameVariantNum] = { "nca_key_area_key", "key_area_key", "nca_body_keak" }; - const std::string kNcaKeyAreaEncKeyHwBase[kNameVariantNum] = { "nca_key_area_key_hw", "key_area_hw_key", "nca_key_area_key_hw" }; - const std::string kKekGenBase[kNameVariantNum] = { "aes_kek_generation", "aes_kek_generation", "aes_kek_generation" }; - const std::string kKeyGenBase[kNameVariantNum] = { "aes_key_generation", "aes_key_generation", "aes_key_generation" }; - - // misc str - const std::string kKeyStr = "key"; - const std::string kKekStr = "kek"; - const std::string kSourceStr = "source"; - const std::string kRsaKeyModulus = "sign_key_modulus"; - const std::string kRsaKeyPrivate = "sign_key_private"; - const std::string kNcaKeyAreaKeyIndexStr[kNcaKeakNum] = { "application", "ocean", "system" }; - const std::string kKeyIndex[kMasterKeyNum] = {"00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f"}; - - struct sRightsId - { - byte_t data[nn::hac::nca::kRightsIdLen]; - - void operator=(const sRightsId& other) - { - memcpy(this->data, other.data, nn::hac::nca::kRightsIdLen); - } - - bool operator==(const sRightsId& other) const - { - return memcmp(this->data, other.data, nn::hac::nca::kRightsIdLen) == 0; - } - - bool operator!=(const sRightsId& other) const - { - return !(operator==(other)); - } - }; - - struct sNcaExternalContentKey - { - sRightsId rights_id; - fnd::aes::sAes128Key key; - - void operator=(const sNcaExternalContentKey& other) - { - rights_id = other.rights_id; - key = other.key; - } - - bool operator==(const sNcaExternalContentKey& other) const - { - return (rights_id == other.rights_id) \ - && (key == other.key); - } - - bool operator!=(const sNcaExternalContentKey& other) const - { - return !(operator==(other)); - } - }; - - struct sPkiRootKey - { - std::string name; - nn::pki::sign::SignatureAlgo key_type; - fnd::rsa::sRsa4096Key rsa4096_key; - fnd::rsa::sRsa2048Key rsa2048_key; - fnd::ecdsa::sEcdsa240Key ecdsa240_key; - - void operator=(const sPkiRootKey& other) - { - name = other.name; - key_type = other.key_type; - rsa4096_key = other.rsa4096_key; - rsa2048_key = other.rsa2048_key; - ecdsa240_key = other.ecdsa240_key; - } - - bool operator==(const sPkiRootKey& other) const - { - return (name == other.name) \ - && (key_type == other.key_type) \ - && (rsa4096_key == other.rsa4096_key) \ - && (rsa2048_key == other.rsa2048_key) \ - && (ecdsa240_key == other.ecdsa240_key); - } - - bool operator!=(const sPkiRootKey& other) const - { - return !(operator==(other)); - } - }; - - - /* general key config */ - // acid - fnd::rsa::sRsa2048Key mAcidSignKey; - - // pkg1 and pkg2 - fnd::aes::sAes128Key mPkg1Key[kMasterKeyNum]; - fnd::rsa::sRsa2048Key mPkg2SignKey; - fnd::aes::sAes128Key mPkg2Key[kMasterKeyNum]; - - // nca - fnd::rsa::sRsa2048Key mContentArchiveHeader0SignKey; - fnd::aes::sAesXts128Key mContentArchiveHeaderKey; - fnd::aes::sAes128Key mNcaKeyAreaEncryptionKey[kNcaKeakNum][kMasterKeyNum]; - fnd::aes::sAes128Key mNcaKeyAreaEncryptionKeyHw[kNcaKeakNum][kMasterKeyNum]; - - // xci - fnd::rsa::sRsa2048Key mXciHeaderSignKey; - fnd::aes::sAes128Key mXciHeaderKey; - - // ticket - fnd::aes::sAes128Key mETicketCommonKey[kMasterKeyNum]; - - // pki - fnd::List mPkiRootKeyList; - - /* Nca External Keys */ - fnd::List mNcaExternalContentKeyList; - - template - bool copyOutKeyResourceIfExists(const T& src, T& dst, const T& null_sample) const - { - bool resource_exists = false; - - if (src != null_sample) - { - resource_exists = true; - dst = src; - } - - return resource_exists; - } +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class KeyConfiguration +{ +public: + KeyConfiguration(); + KeyConfiguration(const KeyConfiguration& other); + + void operator=(const KeyConfiguration& other); + + void importHactoolGenericKeyfile(const std::string& path); + //void importHactoolTitleKeyfile(const std::string& path); + + void clearGeneralKeyConfiguration(); + void clearNcaExternalKeys(); + + // nca keys + bool getContentArchiveHeaderKey(fnd::aes::sAesXts128Key& key) const; + bool getContentArchiveHeader0SignKey(fnd::rsa::sRsa2048Key& key) const; + bool getAcidSignKey(fnd::rsa::sRsa2048Key& key) const; + bool getNcaKeyAreaEncryptionKey(byte_t masterkey_index, byte_t keak_type, fnd::aes::sAes128Key& key) const; + bool getNcaKeyAreaEncryptionKeyHw(byte_t masterkey_index, byte_t keak_type, fnd::aes::sAes128Key& key) const; + + // external content keys + void addNcaExternalContentKey(const byte_t rights_id[nn::hac::nca::kRightsIdLen], const fnd::aes::sAes128Key& key); + bool getNcaExternalContentKey(const byte_t rights_id[nn::hac::nca::kRightsIdLen], fnd::aes::sAes128Key& key) const; + + // pkg1/pkg2 + bool getPkg1Key(byte_t masterkey_index, fnd::aes::sAes128Key& key) const; + bool getPkg2Key(byte_t masterkey_index, fnd::aes::sAes128Key& key) const; + bool getPkg2SignKey(fnd::rsa::sRsa2048Key& key) const; + + // xci keys + bool getXciHeaderSignKey(fnd::rsa::sRsa2048Key& key) const; + bool getXciHeaderKey(fnd::aes::sAes128Key& key) const; + + // ticket + bool getETicketCommonKey(byte_t masterkey_index, fnd::aes::sAes128Key& key) const; + + // pki + bool getPkiRootSignKey(const std::string& root_name, fnd::rsa::sRsa4096Key& key) const; + bool getPkiRootSignKey(const std::string& root_name, fnd::rsa::sRsa2048Key& key) const; + bool getPkiRootSignKey(const std::string& root_name, fnd::ecdsa::sEcdsa240Key& key) const; +private: + const std::string kModuleName = "KeyConfiguration"; + const fnd::aes::sAes128Key kNullAesKey = {{0}}; + const fnd::aes::sAesXts128Key kNullAesXtsKey = {{{0}}}; + const fnd::rsa::sRsa4096Key kNullRsa4096Key = {{0}, {0}, {0}}; + const fnd::rsa::sRsa2048Key kNullRsa2048Key = {{0}, {0}, {0}}; + static const size_t kMasterKeyNum = 0x20; + static const size_t kNcaKeakNum = nn::hac::nca::kKeyAreaEncryptionKeyNum; + + // keynames + enum NameVariantIndex + { + NNTOOLS, + LEGACY_HACTOOL, + LEGACY_0 + }; + static const size_t kNameVariantNum = 3; + const std::string kMasterBase[kNameVariantNum] = { "master", "master", "master" }; + const std::string kPkg1Base[kNameVariantNum] = { "package1", "package1", "package1" }; + const std::string kPkg2Base[kNameVariantNum] = { "package2", "package2", "package2" }; + const std::string kXciHeaderBase[kNameVariantNum] = { "xci_header", "xci_header", "xci_header" }; + const std::string kContentArchiveHeaderBase[kNameVariantNum] = { "nca_header", "header", "nca_header" }; + const std::string kAcidBase[kNameVariantNum] = { "acid", "acid", "acid" }; + const std::string kPkiRootBase[kNameVariantNum] = { "pki_root", "pki_root", "pki_root" }; + const std::string kTicketCommonKeyBase[kNameVariantNum] = { "ticket_commonkey", "titlekek", "ticket_commonkey" }; + const std::string kNcaKeyAreaEncKeyBase[kNameVariantNum] = { "nca_key_area_key", "key_area_key", "nca_body_keak" }; + const std::string kNcaKeyAreaEncKeyHwBase[kNameVariantNum] = { "nca_key_area_key_hw", "key_area_hw_key", "nca_key_area_key_hw" }; + const std::string kKekGenBase[kNameVariantNum] = { "aes_kek_generation", "aes_kek_generation", "aes_kek_generation" }; + const std::string kKeyGenBase[kNameVariantNum] = { "aes_key_generation", "aes_key_generation", "aes_key_generation" }; + + // misc str + const std::string kKeyStr = "key"; + const std::string kKekStr = "kek"; + const std::string kSourceStr = "source"; + const std::string kRsaKeyModulus = "sign_key_modulus"; + const std::string kRsaKeyPrivate = "sign_key_private"; + const std::string kNcaKeyAreaKeyIndexStr[kNcaKeakNum] = { "application", "ocean", "system" }; + const std::string kKeyIndex[kMasterKeyNum] = {"00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f"}; + + struct sRightsId + { + byte_t data[nn::hac::nca::kRightsIdLen]; + + void operator=(const sRightsId& other) + { + memcpy(this->data, other.data, nn::hac::nca::kRightsIdLen); + } + + bool operator==(const sRightsId& other) const + { + return memcmp(this->data, other.data, nn::hac::nca::kRightsIdLen) == 0; + } + + bool operator!=(const sRightsId& other) const + { + return !(operator==(other)); + } + }; + + struct sNcaExternalContentKey + { + sRightsId rights_id; + fnd::aes::sAes128Key key; + + void operator=(const sNcaExternalContentKey& other) + { + rights_id = other.rights_id; + key = other.key; + } + + bool operator==(const sNcaExternalContentKey& other) const + { + return (rights_id == other.rights_id) \ + && (key == other.key); + } + + bool operator!=(const sNcaExternalContentKey& other) const + { + return !(operator==(other)); + } + }; + + struct sPkiRootKey + { + std::string name; + nn::pki::sign::SignatureAlgo key_type; + fnd::rsa::sRsa4096Key rsa4096_key; + fnd::rsa::sRsa2048Key rsa2048_key; + fnd::ecdsa::sEcdsa240Key ecdsa240_key; + + void operator=(const sPkiRootKey& other) + { + name = other.name; + key_type = other.key_type; + rsa4096_key = other.rsa4096_key; + rsa2048_key = other.rsa2048_key; + ecdsa240_key = other.ecdsa240_key; + } + + bool operator==(const sPkiRootKey& other) const + { + return (name == other.name) \ + && (key_type == other.key_type) \ + && (rsa4096_key == other.rsa4096_key) \ + && (rsa2048_key == other.rsa2048_key) \ + && (ecdsa240_key == other.ecdsa240_key); + } + + bool operator!=(const sPkiRootKey& other) const + { + return !(operator==(other)); + } + }; + + + /* general key config */ + // acid + fnd::rsa::sRsa2048Key mAcidSignKey; + + // pkg1 and pkg2 + fnd::aes::sAes128Key mPkg1Key[kMasterKeyNum]; + fnd::rsa::sRsa2048Key mPkg2SignKey; + fnd::aes::sAes128Key mPkg2Key[kMasterKeyNum]; + + // nca + fnd::rsa::sRsa2048Key mContentArchiveHeader0SignKey; + fnd::aes::sAesXts128Key mContentArchiveHeaderKey; + fnd::aes::sAes128Key mNcaKeyAreaEncryptionKey[kNcaKeakNum][kMasterKeyNum]; + fnd::aes::sAes128Key mNcaKeyAreaEncryptionKeyHw[kNcaKeakNum][kMasterKeyNum]; + + // xci + fnd::rsa::sRsa2048Key mXciHeaderSignKey; + fnd::aes::sAes128Key mXciHeaderKey; + + // ticket + fnd::aes::sAes128Key mETicketCommonKey[kMasterKeyNum]; + + // pki + fnd::List mPkiRootKeyList; + + /* Nca External Keys */ + fnd::List mNcaExternalContentKeyList; + + template + bool copyOutKeyResourceIfExists(const T& src, T& dst, const T& null_sample) const + { + bool resource_exists = false; + + if (src != null_sample) + { + resource_exists = true; + dst = src; + } + + return resource_exists; + } }; \ No newline at end of file diff --git a/programs/nstool/source/KipProcess.cpp b/src/KipProcess.cpp similarity index 100% rename from programs/nstool/source/KipProcess.cpp rename to src/KipProcess.cpp diff --git a/programs/nstool/source/KipProcess.h b/src/KipProcess.h similarity index 100% rename from programs/nstool/source/KipProcess.h rename to src/KipProcess.h diff --git a/programs/nstool/source/MetaProcess.cpp b/src/MetaProcess.cpp similarity index 96% rename from programs/nstool/source/MetaProcess.cpp rename to src/MetaProcess.cpp index 7297504..c65316d 100644 --- a/programs/nstool/source/MetaProcess.cpp +++ b/src/MetaProcess.cpp @@ -1,1118 +1,1118 @@ -#include -#include -#include "MetaProcess.h" - -MetaProcess::MetaProcess() : - mFile(), - mCliOutputMode(_BIT(OUTPUT_BASIC)), - mVerify(false) -{ -} - -void MetaProcess::process() -{ - importMeta(); - - if (mVerify) - { - validateAcidSignature(mMeta.getAcid()); - validateAciFromAcid(mMeta.getAci(), mMeta.getAcid()); - } - - if (_HAS_BIT(mCliOutputMode, OUTPUT_BASIC)) - { - // npdm binary - displayMetaHeader(mMeta); - - // aci binary - displayAciHdr(mMeta.getAci()); - displayFac(mMeta.getAci().getFileSystemAccessControl()); - displaySac(mMeta.getAci().getServiceAccessControl()); - displayKernelCap(mMeta.getAci().getKernelCapabilities()); - - // acid binary - if (_HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) - { - displayAciDescHdr(mMeta.getAcid()); - displayFac(mMeta.getAcid().getFileSystemAccessControl()); - displaySac(mMeta.getAcid().getServiceAccessControl()); - displayKernelCap(mMeta.getAcid().getKernelCapabilities()); - } - } -} - -void MetaProcess::setInputFile(const fnd::SharedPtr& file) -{ - mFile = file; -} - -void MetaProcess::setKeyCfg(const KeyConfiguration& keycfg) -{ - mKeyCfg = keycfg; -} - -void MetaProcess::setCliOutputMode(CliOutputMode type) -{ - mCliOutputMode = type; -} - -void MetaProcess::setVerifyMode(bool verify) -{ - mVerify = verify; -} - -const nn::hac::Meta& MetaProcess::getMeta() const -{ - return mMeta; -} - -void MetaProcess::importMeta() -{ - fnd::Vec scratch; - - if (*mFile == nullptr) - { - throw fnd::Exception(kModuleName, "No file reader set."); - } - - scratch.alloc((*mFile)->size()); - (*mFile)->read(scratch.data(), 0, scratch.size()); - - mMeta.fromBytes(scratch.data(), scratch.size()); -} - -void MetaProcess::validateAcidSignature(const nn::hac::AccessControlInfoDesc& acid) -{ - try { - fnd::rsa::sRsa2048Key acid_sign_key; - if (mKeyCfg.getAcidSignKey(acid_sign_key) != true) - throw fnd::Exception(); - - acid.validateSignature(acid_sign_key); - } - catch (...) { - std::cout << "[WARNING] ACID Signature: FAIL" << std::endl; - } - -} - -void MetaProcess::validateAciFromAcid(const nn::hac::AccessControlInfo& aci, const nn::hac::AccessControlInfoDesc& acid) -{ - // check Program ID - if (acid.getProgramIdRestrict().min > 0 && aci.getProgramId() < acid.getProgramIdRestrict().min) - { - std::cout << "[WARNING] ACI ProgramId: FAIL (Outside Legal Range)" << std::endl; - } - else if (acid.getProgramIdRestrict().max > 0 && aci.getProgramId() > acid.getProgramIdRestrict().max) - { - std::cout << "[WARNING] ACI ProgramId: FAIL (Outside Legal Range)" << std::endl; - } - - for (size_t i = 0; i < aci.getFileSystemAccessControl().getFsaRightsList().size(); i++) - { - bool fsaRightFound = false; - for (size_t j = 0; j < acid.getFileSystemAccessControl().getFsaRightsList().size() && fsaRightFound == false; j++) - { - if (aci.getFileSystemAccessControl().getFsaRightsList()[i] == acid.getFileSystemAccessControl().getFsaRightsList()[j]) - fsaRightFound = true; - } - - if (fsaRightFound == false) - { - - std::cout << "[WARNING] ACI/FAC FsaRights: FAIL (" << getFsaRightStr(aci.getFileSystemAccessControl().getFsaRightsList()[i]) << " not permitted)" << std::endl; - } - } - - for (size_t i = 0; i < aci.getFileSystemAccessControl().getContentOwnerIdList().size(); i++) - { - bool rightFound = false; - for (size_t j = 0; j < acid.getFileSystemAccessControl().getContentOwnerIdList().size() && rightFound == false; j++) - { - if (aci.getFileSystemAccessControl().getContentOwnerIdList()[i] == acid.getFileSystemAccessControl().getContentOwnerIdList()[j]) - rightFound = true; - } - - if (rightFound == false) - { - - std::cout << "[WARNING] ACI/FAC ContentOwnerId: FAIL (" << std::hex << std::setw(16) << std::setfill('0') << aci.getFileSystemAccessControl().getContentOwnerIdList()[i] << " not permitted)" << std::endl; - } - } - - for (size_t i = 0; i < aci.getFileSystemAccessControl().getSaveDataOwnerIdList().size(); i++) - { - bool rightFound = false; - for (size_t j = 0; j < acid.getFileSystemAccessControl().getSaveDataOwnerIdList().size() && rightFound == false; j++) - { - if (aci.getFileSystemAccessControl().getSaveDataOwnerIdList()[i] == acid.getFileSystemAccessControl().getSaveDataOwnerIdList()[j]) - rightFound = true; - } - - if (rightFound == false) - { - - std::cout << "[WARNING] ACI/FAC SaveDataOwnerId: FAIL (" << std::hex << std::setw(16) << std::setfill('0') << aci.getFileSystemAccessControl().getSaveDataOwnerIdList()[i].id << "(" << std::dec << (uint32_t)aci.getFileSystemAccessControl().getSaveDataOwnerIdList()[i].access_type << ") not permitted)" << std::endl; - } - } - - // check SAC - for (size_t i = 0; i < aci.getServiceAccessControl().getServiceList().size(); i++) - { - bool rightFound = false; - for (size_t j = 0; j < acid.getServiceAccessControl().getServiceList().size() && rightFound == false; j++) - { - if (aci.getServiceAccessControl().getServiceList()[i] == acid.getServiceAccessControl().getServiceList()[j]) - rightFound = true; - } - - if (rightFound == false) - { - std::cout << "[WARNING] ACI/SAC ServiceList: FAIL (" << aci.getServiceAccessControl().getServiceList()[i].getName() << (aci.getServiceAccessControl().getServiceList()[i].isServer()? " (Server)" : "") << " not permitted)" << std::endl; - } - } - - // check KC - // check thread info - if (aci.getKernelCapabilities().getThreadInfo().getMaxCpuId() != acid.getKernelCapabilities().getThreadInfo().getMaxCpuId()) - { - std::cout << "[WARNING] ACI/KC ThreadInfo/MaxCpuId: FAIL (" << std::dec << (uint32_t)aci.getKernelCapabilities().getThreadInfo().getMaxCpuId() << " not permitted)" << std::endl; - } - if (aci.getKernelCapabilities().getThreadInfo().getMinCpuId() != acid.getKernelCapabilities().getThreadInfo().getMinCpuId()) - { - std::cout << "[WARNING] ACI/KC ThreadInfo/MinCpuId: FAIL (" << std::dec << (uint32_t)aci.getKernelCapabilities().getThreadInfo().getMinCpuId() << " not permitted)" << std::endl; - } - if (aci.getKernelCapabilities().getThreadInfo().getMaxPriority() != acid.getKernelCapabilities().getThreadInfo().getMaxPriority()) - { - std::cout << "[WARNING] ACI/KC ThreadInfo/MaxPriority: FAIL (" << std::dec << (uint32_t)aci.getKernelCapabilities().getThreadInfo().getMaxPriority() << " not permitted)" << std::endl; - } - if (aci.getKernelCapabilities().getThreadInfo().getMinPriority() != acid.getKernelCapabilities().getThreadInfo().getMinPriority()) - { - std::cout << "[WARNING] ACI/KC ThreadInfo/MinPriority: FAIL (" << std::dec << (uint32_t)aci.getKernelCapabilities().getThreadInfo().getMinPriority() << " not permitted)" << std::endl; - } - // check system calls - for (size_t i = 0; i < aci.getKernelCapabilities().getSystemCalls().getSystemCalls().size(); i++) - { - bool rightFound = false; - for (size_t j = 0; j < acid.getKernelCapabilities().getSystemCalls().getSystemCalls().size() && rightFound == false; j++) - { - if (aci.getKernelCapabilities().getSystemCalls().getSystemCalls()[i] == acid.getKernelCapabilities().getSystemCalls().getSystemCalls()[j]) - rightFound = true; - } - - if (rightFound == false) - { - std::cout << "[WARNING] ACI/KC SystemCallList: FAIL (" << getSystemCallStr(aci.getKernelCapabilities().getSystemCalls().getSystemCalls()[i]) << " not permitted)" << std::endl; - } - } - // check memory maps - for (size_t i = 0; i < aci.getKernelCapabilities().getMemoryMaps().getMemoryMaps().size(); i++) - { - bool rightFound = false; - for (size_t j = 0; j < acid.getKernelCapabilities().getMemoryMaps().getMemoryMaps().size() && rightFound == false; j++) - { - if (aci.getKernelCapabilities().getMemoryMaps().getMemoryMaps()[i] == acid.getKernelCapabilities().getMemoryMaps().getMemoryMaps()[j]) - rightFound = true; - } - - if (rightFound == false) - { - const nn::hac::MemoryMappingHandler::sMemoryMapping& map = aci.getKernelCapabilities().getMemoryMaps().getMemoryMaps()[i]; - - std::cout << "[WARNING] ACI/KC MemoryMap: FAIL (0x" << std::hex << std::setw(16) << std::setfill('0') << ((uint64_t)map.addr << 12) << " - 0x" << std::hex << std::setw(16) << std::setfill('0') << (((uint64_t)(map.addr + map.size) << 12) - 1) << " (perm=" << getMemMapPermStr(map.perm) << ") (type=" << getMemMapTypeStr(map.type) << ") not permitted)" << std::endl; - } - } - for (size_t i = 0; i < aci.getKernelCapabilities().getMemoryMaps().getIoMemoryMaps().size(); i++) - { - bool rightFound = false; - for (size_t j = 0; j < acid.getKernelCapabilities().getMemoryMaps().getIoMemoryMaps().size() && rightFound == false; j++) - { - if (aci.getKernelCapabilities().getMemoryMaps().getIoMemoryMaps()[i] == acid.getKernelCapabilities().getMemoryMaps().getIoMemoryMaps()[j]) - rightFound = true; - } - - if (rightFound == false) - { - const nn::hac::MemoryMappingHandler::sMemoryMapping& map = aci.getKernelCapabilities().getMemoryMaps().getIoMemoryMaps()[i]; - - std::cout << "[WARNING] ACI/KC IoMemoryMap: FAIL (0x" << std::hex << std::setw(16) << std::setfill('0') << ((uint64_t)map.addr << 12) << " - 0x" << std::hex << std::setw(16) << std::setfill('0') << (((uint64_t)(map.addr + map.size) << 12) - 1) << " (perm=" << getMemMapPermStr(map.perm) << ") (type=" << getMemMapTypeStr(map.type) << ") not permitted)" << std::endl; - } - } - // check interupts - for (size_t i = 0; i < aci.getKernelCapabilities().getInterupts().getInteruptList().size(); i++) - { - bool rightFound = false; - for (size_t j = 0; j < acid.getKernelCapabilities().getInterupts().getInteruptList().size() && rightFound == false; j++) - { - if (aci.getKernelCapabilities().getInterupts().getInteruptList()[i] == acid.getKernelCapabilities().getInterupts().getInteruptList()[j]) - rightFound = true; - } - - if (rightFound == false) - { - std::cout << "[WARNING] ACI/KC InteruptsList: FAIL (0x" << std::hex << (uint32_t)aci.getKernelCapabilities().getInterupts().getInteruptList()[i] << " not permitted)" << std::endl; - } - } - // check misc params - if (aci.getKernelCapabilities().getMiscParams().getProgramType() != acid.getKernelCapabilities().getMiscParams().getProgramType()) - { - std::cout << "[WARNING] ACI/KC ProgramType: FAIL (" << std::dec << (uint32_t)aci.getKernelCapabilities().getMiscParams().getProgramType() << " not permitted)" << std::endl; - } - // check kernel version - uint32_t aciKernelVersion = (uint32_t)aci.getKernelCapabilities().getKernelVersion().getVerMajor() << 16 | (uint32_t)aci.getKernelCapabilities().getKernelVersion().getVerMinor(); - uint32_t acidKernelVersion = (uint32_t)acid.getKernelCapabilities().getKernelVersion().getVerMajor() << 16 | (uint32_t)acid.getKernelCapabilities().getKernelVersion().getVerMinor(); - if (aciKernelVersion < acidKernelVersion) - { - std::cout << "[WARNING] ACI/KC RequiredKernelVersion: FAIL (" << std::dec << aci.getKernelCapabilities().getKernelVersion().getVerMajor() << "." << aci.getKernelCapabilities().getKernelVersion().getVerMinor() << " not permitted)" << std::endl; - } - // check handle table size - if (aci.getKernelCapabilities().getHandleTableSize().getHandleTableSize() > acid.getKernelCapabilities().getHandleTableSize().getHandleTableSize()) - { - std::cout << "[WARNING] ACI/KC HandleTableSize: FAIL (0x" << std::hex << (uint32_t)aci.getKernelCapabilities().getHandleTableSize().getHandleTableSize() << " too large)" << std::endl; - } - // check misc flags - for (size_t i = 0; i < aci.getKernelCapabilities().getMiscFlags().getFlagList().size(); i++) - { - bool rightFound = false; - for (size_t j = 0; j < acid.getKernelCapabilities().getMiscFlags().getFlagList().size() && rightFound == false; j++) - { - if (aci.getKernelCapabilities().getMiscFlags().getFlagList()[i] == acid.getKernelCapabilities().getMiscFlags().getFlagList()[j]) - rightFound = true; - } - - if (rightFound == false) - { - std::cout << "[WARNING] ACI/KC MiscFlag: FAIL (" << getMiscFlagStr(aci.getKernelCapabilities().getMiscFlags().getFlagList()[i]) << " not permitted)" << std::endl; - } - } -} - -void MetaProcess::displayMetaHeader(const nn::hac::Meta& hdr) -{ - std::cout << "[Meta Header]" << std::endl; - std::cout << " Process Architecture Params:" << std::endl; - std::cout << " Ins. Type: " << getInstructionTypeStr(hdr.getInstructionType()) << std::endl; - std::cout << " Addr Space: " << getProcAddressSpaceTypeStr(hdr.getProcAddressSpaceType()) << std::endl; - std::cout << " Main Thread Params:" << std::endl; - std::cout << " Priority: " << std::dec << (uint32_t)hdr.getMainThreadPriority() << std::endl; - std::cout << " CpuId: " << std::dec << (uint32_t)hdr.getMainThreadCpuId() << std::endl; - std::cout << " StackSize: 0x" << std::hex << hdr.getMainThreadStackSize() << std::endl; - std::cout << " TitleInfo:" << std::endl; - std::cout << " Version: v" << std::dec << hdr.getVersion() << std::endl; - std::cout << " Name: " << hdr.getName() << std::endl; - if (hdr.getProductCode().length()) - { - std::cout << " ProductCode: " << hdr.getProductCode() << std::endl; - } -} - -void MetaProcess::displayAciHdr(const nn::hac::AccessControlInfo& aci) -{ - std::cout << "[Access Control Info]" << std::endl; - std::cout << " ProgramID: 0x" << std::hex << std::setw(16) << std::setfill('0') << aci.getProgramId() << std::endl; -} - -void MetaProcess::displayAciDescHdr(const nn::hac::AccessControlInfoDesc& acid) -{ - std::cout << "[Access Control Info Desc]" << std::endl; - if (acid.getFlagList().size() > 0 || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) - { - std::cout << " Flags: " << std::endl; - for (size_t i = 0; i < acid.getFlagList().size(); i++) - { - std::cout << " " << getAcidFlagStr(acid.getFlagList()[i]) << " (" << std::dec << (uint32_t)acid.getFlagList()[i] << ")" << std::endl; - } - } - std::cout << " ProgramID Restriction" << std::endl; - std::cout << " Min: 0x" << std::hex << std::setw(16) << std::setfill('0') << acid.getProgramIdRestrict().min << std::endl; - std::cout << " Max: 0x" << std::hex << std::setw(16) << std::setfill('0') << acid.getProgramIdRestrict().max << std::endl; -} - -void MetaProcess::displayFac(const nn::hac::FileSystemAccessControl& fac) -{ - std::cout << "[FS Access Control]" << std::endl; - std::cout << " Format Version: " << std::dec << (uint32_t)fac.getFormatVersion() << std::endl; - - if (fac.getFsaRightsList().size()) - { - std::cout << " FS Rights:" << std::endl; - for (size_t i = 0; i < fac.getFsaRightsList().size(); i++) - { - if (i % 10 == 0) - { - if (i != 0) - std::cout << std::endl; - std::cout << " "; - } - std::cout << getFsaRightStr(fac.getFsaRightsList()[i]); - if (_HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) - std::cout << " (bit " << std::dec << (uint32_t)fac.getFsaRightsList()[i] << ")"; - if (fac.getFsaRightsList()[i] != fac.getFsaRightsList().atBack()) - std::cout << ", "; - } - std::cout << std::endl; - } - - if (fac.getContentOwnerIdList().size()) - { - std::cout << " Content Owner IDs:" << std::endl; - for (size_t i = 0; i < fac.getContentOwnerIdList().size(); i++) - { - std::cout << " 0x" << std::hex << std::setw(16) << std::setfill('0') << fac.getContentOwnerIdList()[i] << std::endl; - } - } - - if (fac.getSaveDataOwnerIdList().size()) - { - std::cout << " Save Data Owner IDs:" << std::endl; - for (size_t i = 0; i < fac.getSaveDataOwnerIdList().size(); i++) - { - std::cout << " 0x" << std::hex << std::setw(16) << std::setfill('0') << fac.getSaveDataOwnerIdList()[i].id << " (" << getSaveDataOwnerAccessModeStr(fac.getSaveDataOwnerIdList()[i].access_type) << ")" << std::endl; - } - } - -} - -void MetaProcess::displaySac(const nn::hac::ServiceAccessControl& sac) -{ - std::cout << "[Service Access Control]" << std::endl; - std::cout << " Service List:" << std::endl; - for (size_t i = 0; i < sac.getServiceList().size(); i++) - { - if (i % 10 == 0) - { - if (i != 0) - std::cout << std::endl; - std::cout << " "; - } - std::cout << sac.getServiceList()[i].getName(); - if (sac.getServiceList()[i].isServer()) - std::cout << "(isSrv)"; - if (sac.getServiceList()[i] != sac.getServiceList().atBack()) - std::cout << ", "; - } - std::cout << std::endl; -} - -void MetaProcess::displayKernelCap(const nn::hac::KernelCapabilityControl& kern) -{ - std::cout << "[Kernel Capabilities]" << std::endl; - if (kern.getThreadInfo().isSet()) - { - nn::hac::ThreadInfoHandler threadInfo = kern.getThreadInfo(); - std::cout << " Thread Priority:" << std::endl; - std::cout << " Min: " << std::dec << (uint32_t)threadInfo.getMinPriority() << std::endl; - std::cout << " Max: " << std::dec << (uint32_t)threadInfo.getMaxPriority() << std::endl; - std::cout << " CpuId:" << std::endl; - std::cout << " Min: " << std::dec << (uint32_t)threadInfo.getMinCpuId() << std::endl; - std::cout << " Max: " << std::dec << (uint32_t)threadInfo.getMaxCpuId() << std::endl; - } - - if (kern.getSystemCalls().isSet()) - { - fnd::List syscalls = kern.getSystemCalls().getSystemCalls(); - std::cout << " SystemCalls:" << std::endl; - std::cout << " "; - size_t lineLen = 0; - for (size_t i = 0; i < syscalls.size(); i++) - { - if (lineLen > 60) - { - lineLen = 0; - std::cout << std::endl; - std::cout << " "; - } - std::cout << getSystemCallStr(syscalls[i]); - if (syscalls[i] != syscalls.atBack()) - std::cout << ", "; - lineLen += strlen(getSystemCallStr(syscalls[i])); - } - std::cout << std::endl; - } - if (kern.getMemoryMaps().isSet()) - { - fnd::List maps = kern.getMemoryMaps().getMemoryMaps(); - fnd::List ioMaps = kern.getMemoryMaps().getIoMemoryMaps(); - - std::cout << " MemoryMaps:" << std::endl; - for (size_t i = 0; i < maps.size(); i++) - { - std::cout << " 0x" << std::hex << std::setw(16) << std::setfill('0') << ((uint64_t)maps[i].addr << 12) << " - 0x" << std::hex << std::setw(16) << std::setfill('0') << (((uint64_t)(maps[i].addr + maps[i].size) << 12) - 1) << " (perm=" << getMemMapPermStr(maps[i].perm) << ") (type=" << getMemMapTypeStr(maps[i].type) << ")" << std::endl; - } - //std::cout << " IoMaps:" << std::endl; - for (size_t i = 0; i < ioMaps.size(); i++) - { - std::cout << " 0x" << std::hex << std::setw(16) << std::setfill('0') << ((uint64_t)ioMaps[i].addr << 12) << " - 0x" << std::hex << std::setw(16) << std::setfill('0') << (((uint64_t)(ioMaps[i].addr + ioMaps[i].size) << 12) - 1) << " (perm=" << getMemMapPermStr(ioMaps[i].perm) << ") (type=" << getMemMapTypeStr(ioMaps[i].type) << ")" << std::endl; - } - } - if (kern.getInterupts().isSet()) - { - fnd::List interupts = kern.getInterupts().getInteruptList(); - std::cout << " Interupts Flags:" << std::endl; - for (uint32_t i = 0; i < interupts.size(); i++) - { - if (i % 10 == 0) - { - if (i != 0) - std::cout << std::endl; - std::cout << " "; - } - std::cout << "0x" << std::hex << (uint32_t)interupts[i]; - if (interupts[i] != interupts.atBack()) - std::cout << ", "; - std::cout << std::endl; - } - } - if (kern.getMiscParams().isSet()) - { - std::cout << " ProgramType: " << std::dec << (uint32_t)kern.getMiscParams().getProgramType() << std::endl; - } - if (kern.getKernelVersion().isSet()) - { - std::cout << " Kernel Version: " << std::dec << (uint32_t)kern.getKernelVersion().getVerMajor() << "." << (uint32_t)kern.getKernelVersion().getVerMinor() << std::endl; - } - if (kern.getHandleTableSize().isSet()) - { - std::cout << " Handle Table Size: 0x" << std::hex << kern.getHandleTableSize().getHandleTableSize() << std::endl; - } - if (kern.getMiscFlags().isSet()) - { - fnd::List flagList = kern.getMiscFlags().getFlagList(); - - std::cout << " Misc Flags:" << std::endl; - for (uint32_t i = 0; i < flagList.size(); i++) - { - if (i % 10 == 0) - { - if (i != 0) - std::cout << std::endl; - std::cout << " "; - } - std::cout << getMiscFlagStr(flagList[i]); - if (flagList[i] != flagList.atBack()) - std::cout << ", "; - std::cout << std::endl; - } - } -} - -const char* MetaProcess::getInstructionTypeStr(nn::hac::meta::InstructionType type) const -{ - const char* str = nullptr; - - switch(type) - { - case (nn::hac::meta::INSTR_32BIT): - str = "32Bit"; - break; - case (nn::hac::meta::INSTR_64BIT): - str = "64Bit"; - break; - default: - str = "Unknown"; - break; - } - - return str; -} - -const char* MetaProcess::getProcAddressSpaceTypeStr(nn::hac::meta::ProcAddrSpaceType type) const -{ - const char* str = nullptr; - - switch(type) - { - case (nn::hac::meta::ADDR_SPACE_64BIT): - str = "64Bit"; - break; - case (nn::hac::meta::ADDR_SPACE_32BIT): - str = "32Bit"; - break; - case (nn::hac::meta::ADDR_SPACE_32BIT_NO_RESERVED): - str = "32Bit no reserved"; - break; - default: - str = "Unknown"; - break; - } - - return str; -} - -const char* MetaProcess::getAcidFlagStr(nn::hac::aci::Flag flag) const -{ - const char* str = nullptr; - - switch(flag) - { - case (nn::hac::aci::FLAG_PRODUCTION): - str = "Production"; - break; - case (nn::hac::aci::FLAG_UNQUALIFIED_APPROVAL): - str = "UnqualifiedApproval"; - break; - default: - str = "Unknown"; - break; - } - - return str; -} - -const char* MetaProcess::getMiscFlagStr(nn::hac::MiscFlagsHandler::Flags flag) const -{ - const char* str = nullptr; - - switch(flag) - { - case (nn::hac::MiscFlagsHandler::FLAG_ENABLE_DEBUG): - str = "EnableDebug"; - break; - case (nn::hac::MiscFlagsHandler::FLAG_FORCE_DEBUG): - str = "ForceDebug"; - break; - default: - str = "Unknown"; - break; - } - - return str; -} - -const char* MetaProcess::getFsaRightStr(nn::hac::fac::FsAccessFlag flag) const -{ - const char* str = nullptr; - - switch(flag) - { - case (nn::hac::fac::FSA_APPLICATION_INFO): - str = "ApplicationInfo"; - break; - case (nn::hac::fac::FSA_BOOT_MODE_CONTROL): - str = "BootModeControl"; - break; - case (nn::hac::fac::FSA_CALIBRATION): - str = "Calibration"; - break; - case (nn::hac::fac::FSA_SYSTEM_SAVE_DATA): - str = "SystemSaveData"; - break; - case (nn::hac::fac::FSA_GAME_CARD): - str = "GameCard"; - break; - case (nn::hac::fac::FSA_SAVE_DATA_BACKUP): - str = "SaveDataBackUp"; - break; - case (nn::hac::fac::FSA_SAVE_DATA_MANAGEMENT): - str = "SaveDataManagement"; - break; - case (nn::hac::fac::FSA_BIS_ALL_RAW): - str = "BisAllRaw"; - break; - case (nn::hac::fac::FSA_GAME_CARD_RAW): - str = "GameCardRaw"; - break; - case (nn::hac::fac::FSA_GAME_CARD_PRIVATE): - str = "GameCardPrivate"; - break; - case (nn::hac::fac::FSA_SET_TIME): - str = "SetTime"; - break; - case (nn::hac::fac::FSA_CONTENT_MANAGER): - str = "ContentManager"; - break; - case (nn::hac::fac::FSA_IMAGE_MANAGER): - str = "ImageManager"; - break; - case (nn::hac::fac::FSA_CREATE_SAVE_DATA): - str = "CreateSaveData"; - break; - case (nn::hac::fac::FSA_SYSTEM_SAVE_DATA_MANAGEMENT): - str = "SystemSaveDataManagement"; - break; - case (nn::hac::fac::FSA_BIS_FILE_SYSTEM): - str = "BisFileSystem"; - break; - case (nn::hac::fac::FSA_SYSTEM_UPDATE): - str = "SystemUpdate"; - break; - case (nn::hac::fac::FSA_SAVE_DATA_META): - str = "SaveDataMeta"; - break; - case (nn::hac::fac::FSA_DEVICE_SAVE_CONTROL): - str = "DeviceSaveData"; - break; - case (nn::hac::fac::FSA_SETTINGS_CONTROL): - str = "SettingsControl"; - break; - case (nn::hac::fac::FSA_DEBUG): - str = "Debug"; - break; - case (nn::hac::fac::FSA_FULL_PERMISSION): - str = "FullPermission"; - break; - default: - str = "Unknown"; - break; - } - - return str; -} - -const char* MetaProcess::getSaveDataOwnerAccessModeStr(nn::hac::fac::SaveDataOwnerIdAccessType type) const -{ - const char* str = nullptr; - - switch(type) - { - case (nn::hac::fac::SDO_READ): - str = "Read"; - break; - case (nn::hac::fac::SDO_WRITE): - str = "Write"; - break; - case (nn::hac::fac::SDO_READWRITE): - str = "ReadWrite"; - break; - default: - str = "Unknown"; - break; - } - - return str; -} - -const char* MetaProcess::getSystemCallStr(byte_t syscall_id) const -{ - const char* str = nullptr; - - switch(syscall_id) - { - case (0x01): - str = "SetHeapSize"; - break; - case (0x02): - str = "SetMemoryPermission"; - break; - case (0x03): - str = "SetMemoryAttribute"; - break; - case (0x04): - str = "MapMemory"; - break; - case (0x05): - str = "UnmapMemory"; - break; - case (0x06): - str = "QueryMemory"; - break; - case (0x07): - str = "ExitProcess"; - break; - case (0x08): - str = "CreateThread"; - break; - case (0x09): - str = "StartThread"; - break; - case (0x0a): - str = "ExitThread"; - break; - case (0x0b): - str = "SleepThread"; - break; - case (0x0c): - str = "GetThreadPriority"; - break; - case (0x0d): - str = "SetThreadPriority"; - break; - case (0x0e): - str = "GetThreadCoreMask"; - break; - case (0x0f): - str = "SetThreadCoreMask"; - break; - case (0x10): - str = "GetCurrentProcessorNumber"; - break; - case (0x11): - str = "SignalEvent"; - break; - case (0x12): - str = "ClearEvent"; - break; - case (0x13): - str = "MapSharedMemory"; - break; - case (0x14): - str = "UnmapSharedMemory"; - break; - case (0x15): - str = "CreateTransferMemory"; - break; - case (0x16): - str = "CloseHandle"; - break; - case (0x17): - str = "ResetSignal"; - break; - case (0x18): - str = "WaitSynchronization"; - break; - case (0x19): - str = "CancelSynchronization"; - break; - case (0x1a): - str = "ArbitrateLock"; - break; - case (0x1b): - str = "ArbitrateUnlock"; - break; - case (0x1c): - str = "WaitProcessWideKeyAtomic"; - break; - case (0x1d): - str = "SignalProcessWideKey"; - break; - case (0x1e): - str = "GetSystemTick"; - break; - case (0x1f): - str = "ConnectToNamedPort"; - break; - case (0x20): - str = "SendSyncRequestLight"; - break; - case (0x21): - str = "SendSyncRequest"; - break; - case (0x22): - str = "SendSyncRequestWithUserBuffer"; - break; - case (0x23): - str = "SendAsyncRequestWithUserBuffer"; - break; - case (0x24): - str = "GetProcessId"; - break; - case (0x25): - str = "GetThreadId"; - break; - case (0x26): - str = "Break"; - break; - case (0x27): - str = "OutputDebugString"; - break; - case (0x28): - str = "ReturnFromException"; - break; - case (0x29): - str = "GetInfo"; - break; - case (0x2a): - str = "FlushEntireDataCache"; - break; - case (0x2b): - str = "FlushDataCache"; - break; - case (0x2c): - str = "MapPhysicalMemory"; - break; - case (0x2d): - str = "UnmapPhysicalMemory"; - break; - case (0x2e): - str = "GetFutureThreadInfo"; - break; - case (0x2f): - str = "GetLastThreadInfo"; - break; - case (0x30): - str = "GetResourceLimitLimitValue"; - break; - case (0x31): - str = "GetResourceLimitCurrentValue"; - break; - case (0x32): - str = "SetThreadActivity"; - break; - case (0x33): - str = "GetThreadContext3"; - break; - case (0x34): - str = "WaitForAddress"; - break; - case (0x35): - str = "SignalToAddress"; - break; - case (0x36): - str = "svc36"; - break; - case (0x37): - str = "svc37"; - break; - case (0x38): - str = "svc38"; - break; - case (0x39): - str = "svc39"; - break; - case (0x3a): - str = "svc3A"; - break; - case (0x3b): - str = "svc3B"; - break; - case (0x3c): - str = "DumpInfo"; - break; - case (0x3d): - str = "DumpInfoNew"; - break; - case (0x3e): - str = "svc3E"; - break; - case (0x3f): - str = "svc3F"; - break; - case (0x40): - str = "CreateSession"; - break; - case (0x41): - str = "AcceptSession"; - break; - case (0x42): - str = "ReplyAndReceiveLight"; - break; - case (0x43): - str = "ReplyAndReceive"; - break; - case (0x44): - str = "ReplyAndReceiveWithUserBuffer"; - break; - case (0x45): - str = "CreateEvent"; - break; - case (0x46): - str = "svc46"; - break; - case (0x47): - str = "svc47"; - break; - case (0x48): - str = "MapPhysicalMemoryUnsafe"; - break; - case (0x49): - str = "UnmapPhysicalMemoryUnsafe"; - break; - case (0x4a): - str = "SetUnsafeLimit"; - break; - case (0x4b): - str = "CreateCodeMemory"; - break; - case (0x4c): - str = "ControlCodeMemory"; - break; - case (0x4d): - str = "SleepSystem"; - break; - case (0x4e): - str = "ReadWriteRegister"; - break; - case (0x4f): - str = "SetProcessActivity"; - break; - case (0x50): - str = "CreateSharedMemory"; - break; - case (0x51): - str = "MapTransferMemory"; - break; - case (0x52): - str = "UnmapTransferMemory"; - break; - case (0x53): - str = "CreateInterruptEvent"; - break; - case (0x54): - str = "QueryPhysicalAddress"; - break; - case (0x55): - str = "QueryIoMapping"; - break; - case (0x56): - str = "CreateDeviceAddressSpace"; - break; - case (0x57): - str = "AttachDeviceAddressSpace"; - break; - case (0x58): - str = "DetachDeviceAddressSpace"; - break; - case (0x59): - str = "MapDeviceAddressSpaceByForce"; - break; - case (0x5a): - str = "MapDeviceAddressSpaceAligned"; - break; - case (0x5b): - str = "MapDeviceAddressSpace"; - break; - case (0x5c): - str = "UnmapDeviceAddressSpace"; - break; - case (0x5d): - str = "InvalidateProcessDataCache"; - break; - case (0x5e): - str = "StoreProcessDataCache"; - break; - case (0x5f): - str = "FlushProcessDataCache"; - break; - case (0x60): - str = "DebugActiveProcess"; - break; - case (0x61): - str = "BreakDebugProcess"; - break; - case (0x62): - str = "TerminateDebugProcess"; - break; - case (0x63): - str = "GetDebugEvent"; - break; - case (0x64): - str = "ContinueDebugEvent"; - break; - case (0x65): - str = "GetProcessList"; - break; - case (0x66): - str = "GetThreadList"; - break; - case (0x67): - str = "GetDebugThreadContext"; - break; - case (0x68): - str = "SetDebugThreadContext"; - break; - case (0x69): - str = "QueryDebugProcessMemory"; - break; - case (0x6a): - str = "ReadDebugProcessMemory"; - break; - case (0x6b): - str = "WriteDebugProcessMemory"; - break; - case (0x6c): - str = "SetHardwareBreakPoint"; - break; - case (0x6d): - str = "GetDebugThreadParam"; - break; - case (0x6e): - str = "svc6E"; - break; - case (0x6f): - str = "GetSystemInfo"; - break; - case (0x70): - str = "CreatePort"; - break; - case (0x71): - str = "ManageNamedPort"; - break; - case (0x72): - str = "ConnectToPort"; - break; - case (0x73): - str = "SetProcessMemoryPermission"; - break; - case (0x74): - str = "MapProcessMemory"; - break; - case (0x75): - str = "UnmapProcessMemory"; - break; - case (0x76): - str = "QueryProcessMemory"; - break; - case (0x77): - str = "MapProcessCodeMemory"; - break; - case (0x78): - str = "UnmapProcessCodeMemory"; - break; - case (0x79): - str = "CreateProcess"; - break; - case (0x7a): - str = "StartProcess"; - break; - case (0x7b): - str = "TerminateProcess"; - break; - case (0x7c): - str = "GetProcessInfo"; - break; - case (0x7d): - str = "CreateResourceLimit"; - break; - case (0x7e): - str = "SetResourceLimitLimitValue"; - break; - case (0x7f): - str = "CallSecureMonitor"; - break; - default: - str = "Unknown"; - break; - } - - return str; -} - -const char* MetaProcess::getMemMapPermStr(nn::hac::MemoryMappingHandler::MemoryPerm type) const -{ - const char* str = nullptr; - - switch(type) - { - case (nn::hac::MemoryMappingHandler::MEM_RW): - str = "RW"; - break; - case (nn::hac::MemoryMappingHandler::MEM_RO): - str = "RO"; - break; - default: - str = "Unknown"; - break; - } - - return str; -} - -const char* MetaProcess::getMemMapTypeStr(nn::hac::MemoryMappingHandler::MappingType type) const -{ - const char* str = nullptr; - - switch(type) - { - case (nn::hac::MemoryMappingHandler::MAP_IO): - str = "Io"; - break; - case (nn::hac::MemoryMappingHandler::MAP_STATIC): - str = "Static"; - break; - default: - str = "Unknown"; - break; - } - - return str; +#include +#include +#include "MetaProcess.h" + +MetaProcess::MetaProcess() : + mFile(), + mCliOutputMode(_BIT(OUTPUT_BASIC)), + mVerify(false) +{ +} + +void MetaProcess::process() +{ + importMeta(); + + if (mVerify) + { + validateAcidSignature(mMeta.getAcid()); + validateAciFromAcid(mMeta.getAci(), mMeta.getAcid()); + } + + if (_HAS_BIT(mCliOutputMode, OUTPUT_BASIC)) + { + // npdm binary + displayMetaHeader(mMeta); + + // aci binary + displayAciHdr(mMeta.getAci()); + displayFac(mMeta.getAci().getFileSystemAccessControl()); + displaySac(mMeta.getAci().getServiceAccessControl()); + displayKernelCap(mMeta.getAci().getKernelCapabilities()); + + // acid binary + if (_HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) + { + displayAciDescHdr(mMeta.getAcid()); + displayFac(mMeta.getAcid().getFileSystemAccessControl()); + displaySac(mMeta.getAcid().getServiceAccessControl()); + displayKernelCap(mMeta.getAcid().getKernelCapabilities()); + } + } +} + +void MetaProcess::setInputFile(const fnd::SharedPtr& file) +{ + mFile = file; +} + +void MetaProcess::setKeyCfg(const KeyConfiguration& keycfg) +{ + mKeyCfg = keycfg; +} + +void MetaProcess::setCliOutputMode(CliOutputMode type) +{ + mCliOutputMode = type; +} + +void MetaProcess::setVerifyMode(bool verify) +{ + mVerify = verify; +} + +const nn::hac::Meta& MetaProcess::getMeta() const +{ + return mMeta; +} + +void MetaProcess::importMeta() +{ + fnd::Vec scratch; + + if (*mFile == nullptr) + { + throw fnd::Exception(kModuleName, "No file reader set."); + } + + scratch.alloc((*mFile)->size()); + (*mFile)->read(scratch.data(), 0, scratch.size()); + + mMeta.fromBytes(scratch.data(), scratch.size()); +} + +void MetaProcess::validateAcidSignature(const nn::hac::AccessControlInfoDesc& acid) +{ + try { + fnd::rsa::sRsa2048Key acid_sign_key; + if (mKeyCfg.getAcidSignKey(acid_sign_key) != true) + throw fnd::Exception(); + + acid.validateSignature(acid_sign_key); + } + catch (...) { + std::cout << "[WARNING] ACID Signature: FAIL" << std::endl; + } + +} + +void MetaProcess::validateAciFromAcid(const nn::hac::AccessControlInfo& aci, const nn::hac::AccessControlInfoDesc& acid) +{ + // check Program ID + if (acid.getProgramIdRestrict().min > 0 && aci.getProgramId() < acid.getProgramIdRestrict().min) + { + std::cout << "[WARNING] ACI ProgramId: FAIL (Outside Legal Range)" << std::endl; + } + else if (acid.getProgramIdRestrict().max > 0 && aci.getProgramId() > acid.getProgramIdRestrict().max) + { + std::cout << "[WARNING] ACI ProgramId: FAIL (Outside Legal Range)" << std::endl; + } + + for (size_t i = 0; i < aci.getFileSystemAccessControl().getFsaRightsList().size(); i++) + { + bool fsaRightFound = false; + for (size_t j = 0; j < acid.getFileSystemAccessControl().getFsaRightsList().size() && fsaRightFound == false; j++) + { + if (aci.getFileSystemAccessControl().getFsaRightsList()[i] == acid.getFileSystemAccessControl().getFsaRightsList()[j]) + fsaRightFound = true; + } + + if (fsaRightFound == false) + { + + std::cout << "[WARNING] ACI/FAC FsaRights: FAIL (" << getFsaRightStr(aci.getFileSystemAccessControl().getFsaRightsList()[i]) << " not permitted)" << std::endl; + } + } + + for (size_t i = 0; i < aci.getFileSystemAccessControl().getContentOwnerIdList().size(); i++) + { + bool rightFound = false; + for (size_t j = 0; j < acid.getFileSystemAccessControl().getContentOwnerIdList().size() && rightFound == false; j++) + { + if (aci.getFileSystemAccessControl().getContentOwnerIdList()[i] == acid.getFileSystemAccessControl().getContentOwnerIdList()[j]) + rightFound = true; + } + + if (rightFound == false) + { + + std::cout << "[WARNING] ACI/FAC ContentOwnerId: FAIL (" << std::hex << std::setw(16) << std::setfill('0') << aci.getFileSystemAccessControl().getContentOwnerIdList()[i] << " not permitted)" << std::endl; + } + } + + for (size_t i = 0; i < aci.getFileSystemAccessControl().getSaveDataOwnerIdList().size(); i++) + { + bool rightFound = false; + for (size_t j = 0; j < acid.getFileSystemAccessControl().getSaveDataOwnerIdList().size() && rightFound == false; j++) + { + if (aci.getFileSystemAccessControl().getSaveDataOwnerIdList()[i] == acid.getFileSystemAccessControl().getSaveDataOwnerIdList()[j]) + rightFound = true; + } + + if (rightFound == false) + { + + std::cout << "[WARNING] ACI/FAC SaveDataOwnerId: FAIL (" << std::hex << std::setw(16) << std::setfill('0') << aci.getFileSystemAccessControl().getSaveDataOwnerIdList()[i].id << "(" << std::dec << (uint32_t)aci.getFileSystemAccessControl().getSaveDataOwnerIdList()[i].access_type << ") not permitted)" << std::endl; + } + } + + // check SAC + for (size_t i = 0; i < aci.getServiceAccessControl().getServiceList().size(); i++) + { + bool rightFound = false; + for (size_t j = 0; j < acid.getServiceAccessControl().getServiceList().size() && rightFound == false; j++) + { + if (aci.getServiceAccessControl().getServiceList()[i] == acid.getServiceAccessControl().getServiceList()[j]) + rightFound = true; + } + + if (rightFound == false) + { + std::cout << "[WARNING] ACI/SAC ServiceList: FAIL (" << aci.getServiceAccessControl().getServiceList()[i].getName() << (aci.getServiceAccessControl().getServiceList()[i].isServer()? " (Server)" : "") << " not permitted)" << std::endl; + } + } + + // check KC + // check thread info + if (aci.getKernelCapabilities().getThreadInfo().getMaxCpuId() != acid.getKernelCapabilities().getThreadInfo().getMaxCpuId()) + { + std::cout << "[WARNING] ACI/KC ThreadInfo/MaxCpuId: FAIL (" << std::dec << (uint32_t)aci.getKernelCapabilities().getThreadInfo().getMaxCpuId() << " not permitted)" << std::endl; + } + if (aci.getKernelCapabilities().getThreadInfo().getMinCpuId() != acid.getKernelCapabilities().getThreadInfo().getMinCpuId()) + { + std::cout << "[WARNING] ACI/KC ThreadInfo/MinCpuId: FAIL (" << std::dec << (uint32_t)aci.getKernelCapabilities().getThreadInfo().getMinCpuId() << " not permitted)" << std::endl; + } + if (aci.getKernelCapabilities().getThreadInfo().getMaxPriority() != acid.getKernelCapabilities().getThreadInfo().getMaxPriority()) + { + std::cout << "[WARNING] ACI/KC ThreadInfo/MaxPriority: FAIL (" << std::dec << (uint32_t)aci.getKernelCapabilities().getThreadInfo().getMaxPriority() << " not permitted)" << std::endl; + } + if (aci.getKernelCapabilities().getThreadInfo().getMinPriority() != acid.getKernelCapabilities().getThreadInfo().getMinPriority()) + { + std::cout << "[WARNING] ACI/KC ThreadInfo/MinPriority: FAIL (" << std::dec << (uint32_t)aci.getKernelCapabilities().getThreadInfo().getMinPriority() << " not permitted)" << std::endl; + } + // check system calls + for (size_t i = 0; i < aci.getKernelCapabilities().getSystemCalls().getSystemCalls().size(); i++) + { + bool rightFound = false; + for (size_t j = 0; j < acid.getKernelCapabilities().getSystemCalls().getSystemCalls().size() && rightFound == false; j++) + { + if (aci.getKernelCapabilities().getSystemCalls().getSystemCalls()[i] == acid.getKernelCapabilities().getSystemCalls().getSystemCalls()[j]) + rightFound = true; + } + + if (rightFound == false) + { + std::cout << "[WARNING] ACI/KC SystemCallList: FAIL (" << getSystemCallStr(aci.getKernelCapabilities().getSystemCalls().getSystemCalls()[i]) << " not permitted)" << std::endl; + } + } + // check memory maps + for (size_t i = 0; i < aci.getKernelCapabilities().getMemoryMaps().getMemoryMaps().size(); i++) + { + bool rightFound = false; + for (size_t j = 0; j < acid.getKernelCapabilities().getMemoryMaps().getMemoryMaps().size() && rightFound == false; j++) + { + if (aci.getKernelCapabilities().getMemoryMaps().getMemoryMaps()[i] == acid.getKernelCapabilities().getMemoryMaps().getMemoryMaps()[j]) + rightFound = true; + } + + if (rightFound == false) + { + const nn::hac::MemoryMappingHandler::sMemoryMapping& map = aci.getKernelCapabilities().getMemoryMaps().getMemoryMaps()[i]; + + std::cout << "[WARNING] ACI/KC MemoryMap: FAIL (0x" << std::hex << std::setw(16) << std::setfill('0') << ((uint64_t)map.addr << 12) << " - 0x" << std::hex << std::setw(16) << std::setfill('0') << (((uint64_t)(map.addr + map.size) << 12) - 1) << " (perm=" << getMemMapPermStr(map.perm) << ") (type=" << getMemMapTypeStr(map.type) << ") not permitted)" << std::endl; + } + } + for (size_t i = 0; i < aci.getKernelCapabilities().getMemoryMaps().getIoMemoryMaps().size(); i++) + { + bool rightFound = false; + for (size_t j = 0; j < acid.getKernelCapabilities().getMemoryMaps().getIoMemoryMaps().size() && rightFound == false; j++) + { + if (aci.getKernelCapabilities().getMemoryMaps().getIoMemoryMaps()[i] == acid.getKernelCapabilities().getMemoryMaps().getIoMemoryMaps()[j]) + rightFound = true; + } + + if (rightFound == false) + { + const nn::hac::MemoryMappingHandler::sMemoryMapping& map = aci.getKernelCapabilities().getMemoryMaps().getIoMemoryMaps()[i]; + + std::cout << "[WARNING] ACI/KC IoMemoryMap: FAIL (0x" << std::hex << std::setw(16) << std::setfill('0') << ((uint64_t)map.addr << 12) << " - 0x" << std::hex << std::setw(16) << std::setfill('0') << (((uint64_t)(map.addr + map.size) << 12) - 1) << " (perm=" << getMemMapPermStr(map.perm) << ") (type=" << getMemMapTypeStr(map.type) << ") not permitted)" << std::endl; + } + } + // check interupts + for (size_t i = 0; i < aci.getKernelCapabilities().getInterupts().getInteruptList().size(); i++) + { + bool rightFound = false; + for (size_t j = 0; j < acid.getKernelCapabilities().getInterupts().getInteruptList().size() && rightFound == false; j++) + { + if (aci.getKernelCapabilities().getInterupts().getInteruptList()[i] == acid.getKernelCapabilities().getInterupts().getInteruptList()[j]) + rightFound = true; + } + + if (rightFound == false) + { + std::cout << "[WARNING] ACI/KC InteruptsList: FAIL (0x" << std::hex << (uint32_t)aci.getKernelCapabilities().getInterupts().getInteruptList()[i] << " not permitted)" << std::endl; + } + } + // check misc params + if (aci.getKernelCapabilities().getMiscParams().getProgramType() != acid.getKernelCapabilities().getMiscParams().getProgramType()) + { + std::cout << "[WARNING] ACI/KC ProgramType: FAIL (" << std::dec << (uint32_t)aci.getKernelCapabilities().getMiscParams().getProgramType() << " not permitted)" << std::endl; + } + // check kernel version + uint32_t aciKernelVersion = (uint32_t)aci.getKernelCapabilities().getKernelVersion().getVerMajor() << 16 | (uint32_t)aci.getKernelCapabilities().getKernelVersion().getVerMinor(); + uint32_t acidKernelVersion = (uint32_t)acid.getKernelCapabilities().getKernelVersion().getVerMajor() << 16 | (uint32_t)acid.getKernelCapabilities().getKernelVersion().getVerMinor(); + if (aciKernelVersion < acidKernelVersion) + { + std::cout << "[WARNING] ACI/KC RequiredKernelVersion: FAIL (" << std::dec << aci.getKernelCapabilities().getKernelVersion().getVerMajor() << "." << aci.getKernelCapabilities().getKernelVersion().getVerMinor() << " not permitted)" << std::endl; + } + // check handle table size + if (aci.getKernelCapabilities().getHandleTableSize().getHandleTableSize() > acid.getKernelCapabilities().getHandleTableSize().getHandleTableSize()) + { + std::cout << "[WARNING] ACI/KC HandleTableSize: FAIL (0x" << std::hex << (uint32_t)aci.getKernelCapabilities().getHandleTableSize().getHandleTableSize() << " too large)" << std::endl; + } + // check misc flags + for (size_t i = 0; i < aci.getKernelCapabilities().getMiscFlags().getFlagList().size(); i++) + { + bool rightFound = false; + for (size_t j = 0; j < acid.getKernelCapabilities().getMiscFlags().getFlagList().size() && rightFound == false; j++) + { + if (aci.getKernelCapabilities().getMiscFlags().getFlagList()[i] == acid.getKernelCapabilities().getMiscFlags().getFlagList()[j]) + rightFound = true; + } + + if (rightFound == false) + { + std::cout << "[WARNING] ACI/KC MiscFlag: FAIL (" << getMiscFlagStr(aci.getKernelCapabilities().getMiscFlags().getFlagList()[i]) << " not permitted)" << std::endl; + } + } +} + +void MetaProcess::displayMetaHeader(const nn::hac::Meta& hdr) +{ + std::cout << "[Meta Header]" << std::endl; + std::cout << " Process Architecture Params:" << std::endl; + std::cout << " Ins. Type: " << getInstructionTypeStr(hdr.getInstructionType()) << std::endl; + std::cout << " Addr Space: " << getProcAddressSpaceTypeStr(hdr.getProcAddressSpaceType()) << std::endl; + std::cout << " Main Thread Params:" << std::endl; + std::cout << " Priority: " << std::dec << (uint32_t)hdr.getMainThreadPriority() << std::endl; + std::cout << " CpuId: " << std::dec << (uint32_t)hdr.getMainThreadCpuId() << std::endl; + std::cout << " StackSize: 0x" << std::hex << hdr.getMainThreadStackSize() << std::endl; + std::cout << " TitleInfo:" << std::endl; + std::cout << " Version: v" << std::dec << hdr.getVersion() << std::endl; + std::cout << " Name: " << hdr.getName() << std::endl; + if (hdr.getProductCode().length()) + { + std::cout << " ProductCode: " << hdr.getProductCode() << std::endl; + } +} + +void MetaProcess::displayAciHdr(const nn::hac::AccessControlInfo& aci) +{ + std::cout << "[Access Control Info]" << std::endl; + std::cout << " ProgramID: 0x" << std::hex << std::setw(16) << std::setfill('0') << aci.getProgramId() << std::endl; +} + +void MetaProcess::displayAciDescHdr(const nn::hac::AccessControlInfoDesc& acid) +{ + std::cout << "[Access Control Info Desc]" << std::endl; + if (acid.getFlagList().size() > 0 || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) + { + std::cout << " Flags: " << std::endl; + for (size_t i = 0; i < acid.getFlagList().size(); i++) + { + std::cout << " " << getAcidFlagStr(acid.getFlagList()[i]) << " (" << std::dec << (uint32_t)acid.getFlagList()[i] << ")" << std::endl; + } + } + std::cout << " ProgramID Restriction" << std::endl; + std::cout << " Min: 0x" << std::hex << std::setw(16) << std::setfill('0') << acid.getProgramIdRestrict().min << std::endl; + std::cout << " Max: 0x" << std::hex << std::setw(16) << std::setfill('0') << acid.getProgramIdRestrict().max << std::endl; +} + +void MetaProcess::displayFac(const nn::hac::FileSystemAccessControl& fac) +{ + std::cout << "[FS Access Control]" << std::endl; + std::cout << " Format Version: " << std::dec << (uint32_t)fac.getFormatVersion() << std::endl; + + if (fac.getFsaRightsList().size()) + { + std::cout << " FS Rights:" << std::endl; + for (size_t i = 0; i < fac.getFsaRightsList().size(); i++) + { + if (i % 10 == 0) + { + if (i != 0) + std::cout << std::endl; + std::cout << " "; + } + std::cout << getFsaRightStr(fac.getFsaRightsList()[i]); + if (_HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) + std::cout << " (bit " << std::dec << (uint32_t)fac.getFsaRightsList()[i] << ")"; + if (fac.getFsaRightsList()[i] != fac.getFsaRightsList().atBack()) + std::cout << ", "; + } + std::cout << std::endl; + } + + if (fac.getContentOwnerIdList().size()) + { + std::cout << " Content Owner IDs:" << std::endl; + for (size_t i = 0; i < fac.getContentOwnerIdList().size(); i++) + { + std::cout << " 0x" << std::hex << std::setw(16) << std::setfill('0') << fac.getContentOwnerIdList()[i] << std::endl; + } + } + + if (fac.getSaveDataOwnerIdList().size()) + { + std::cout << " Save Data Owner IDs:" << std::endl; + for (size_t i = 0; i < fac.getSaveDataOwnerIdList().size(); i++) + { + std::cout << " 0x" << std::hex << std::setw(16) << std::setfill('0') << fac.getSaveDataOwnerIdList()[i].id << " (" << getSaveDataOwnerAccessModeStr(fac.getSaveDataOwnerIdList()[i].access_type) << ")" << std::endl; + } + } + +} + +void MetaProcess::displaySac(const nn::hac::ServiceAccessControl& sac) +{ + std::cout << "[Service Access Control]" << std::endl; + std::cout << " Service List:" << std::endl; + for (size_t i = 0; i < sac.getServiceList().size(); i++) + { + if (i % 10 == 0) + { + if (i != 0) + std::cout << std::endl; + std::cout << " "; + } + std::cout << sac.getServiceList()[i].getName(); + if (sac.getServiceList()[i].isServer()) + std::cout << "(isSrv)"; + if (sac.getServiceList()[i] != sac.getServiceList().atBack()) + std::cout << ", "; + } + std::cout << std::endl; +} + +void MetaProcess::displayKernelCap(const nn::hac::KernelCapabilityControl& kern) +{ + std::cout << "[Kernel Capabilities]" << std::endl; + if (kern.getThreadInfo().isSet()) + { + nn::hac::ThreadInfoHandler threadInfo = kern.getThreadInfo(); + std::cout << " Thread Priority:" << std::endl; + std::cout << " Min: " << std::dec << (uint32_t)threadInfo.getMinPriority() << std::endl; + std::cout << " Max: " << std::dec << (uint32_t)threadInfo.getMaxPriority() << std::endl; + std::cout << " CpuId:" << std::endl; + std::cout << " Min: " << std::dec << (uint32_t)threadInfo.getMinCpuId() << std::endl; + std::cout << " Max: " << std::dec << (uint32_t)threadInfo.getMaxCpuId() << std::endl; + } + + if (kern.getSystemCalls().isSet()) + { + fnd::List syscalls = kern.getSystemCalls().getSystemCalls(); + std::cout << " SystemCalls:" << std::endl; + std::cout << " "; + size_t lineLen = 0; + for (size_t i = 0; i < syscalls.size(); i++) + { + if (lineLen > 60) + { + lineLen = 0; + std::cout << std::endl; + std::cout << " "; + } + std::cout << getSystemCallStr(syscalls[i]); + if (syscalls[i] != syscalls.atBack()) + std::cout << ", "; + lineLen += strlen(getSystemCallStr(syscalls[i])); + } + std::cout << std::endl; + } + if (kern.getMemoryMaps().isSet()) + { + fnd::List maps = kern.getMemoryMaps().getMemoryMaps(); + fnd::List ioMaps = kern.getMemoryMaps().getIoMemoryMaps(); + + std::cout << " MemoryMaps:" << std::endl; + for (size_t i = 0; i < maps.size(); i++) + { + std::cout << " 0x" << std::hex << std::setw(16) << std::setfill('0') << ((uint64_t)maps[i].addr << 12) << " - 0x" << std::hex << std::setw(16) << std::setfill('0') << (((uint64_t)(maps[i].addr + maps[i].size) << 12) - 1) << " (perm=" << getMemMapPermStr(maps[i].perm) << ") (type=" << getMemMapTypeStr(maps[i].type) << ")" << std::endl; + } + //std::cout << " IoMaps:" << std::endl; + for (size_t i = 0; i < ioMaps.size(); i++) + { + std::cout << " 0x" << std::hex << std::setw(16) << std::setfill('0') << ((uint64_t)ioMaps[i].addr << 12) << " - 0x" << std::hex << std::setw(16) << std::setfill('0') << (((uint64_t)(ioMaps[i].addr + ioMaps[i].size) << 12) - 1) << " (perm=" << getMemMapPermStr(ioMaps[i].perm) << ") (type=" << getMemMapTypeStr(ioMaps[i].type) << ")" << std::endl; + } + } + if (kern.getInterupts().isSet()) + { + fnd::List interupts = kern.getInterupts().getInteruptList(); + std::cout << " Interupts Flags:" << std::endl; + for (uint32_t i = 0; i < interupts.size(); i++) + { + if (i % 10 == 0) + { + if (i != 0) + std::cout << std::endl; + std::cout << " "; + } + std::cout << "0x" << std::hex << (uint32_t)interupts[i]; + if (interupts[i] != interupts.atBack()) + std::cout << ", "; + std::cout << std::endl; + } + } + if (kern.getMiscParams().isSet()) + { + std::cout << " ProgramType: " << std::dec << (uint32_t)kern.getMiscParams().getProgramType() << std::endl; + } + if (kern.getKernelVersion().isSet()) + { + std::cout << " Kernel Version: " << std::dec << (uint32_t)kern.getKernelVersion().getVerMajor() << "." << (uint32_t)kern.getKernelVersion().getVerMinor() << std::endl; + } + if (kern.getHandleTableSize().isSet()) + { + std::cout << " Handle Table Size: 0x" << std::hex << kern.getHandleTableSize().getHandleTableSize() << std::endl; + } + if (kern.getMiscFlags().isSet()) + { + fnd::List flagList = kern.getMiscFlags().getFlagList(); + + std::cout << " Misc Flags:" << std::endl; + for (uint32_t i = 0; i < flagList.size(); i++) + { + if (i % 10 == 0) + { + if (i != 0) + std::cout << std::endl; + std::cout << " "; + } + std::cout << getMiscFlagStr(flagList[i]); + if (flagList[i] != flagList.atBack()) + std::cout << ", "; + std::cout << std::endl; + } + } +} + +const char* MetaProcess::getInstructionTypeStr(nn::hac::meta::InstructionType type) const +{ + const char* str = nullptr; + + switch(type) + { + case (nn::hac::meta::INSTR_32BIT): + str = "32Bit"; + break; + case (nn::hac::meta::INSTR_64BIT): + str = "64Bit"; + break; + default: + str = "Unknown"; + break; + } + + return str; +} + +const char* MetaProcess::getProcAddressSpaceTypeStr(nn::hac::meta::ProcAddrSpaceType type) const +{ + const char* str = nullptr; + + switch(type) + { + case (nn::hac::meta::ADDR_SPACE_64BIT): + str = "64Bit"; + break; + case (nn::hac::meta::ADDR_SPACE_32BIT): + str = "32Bit"; + break; + case (nn::hac::meta::ADDR_SPACE_32BIT_NO_RESERVED): + str = "32Bit no reserved"; + break; + default: + str = "Unknown"; + break; + } + + return str; +} + +const char* MetaProcess::getAcidFlagStr(nn::hac::aci::Flag flag) const +{ + const char* str = nullptr; + + switch(flag) + { + case (nn::hac::aci::FLAG_PRODUCTION): + str = "Production"; + break; + case (nn::hac::aci::FLAG_UNQUALIFIED_APPROVAL): + str = "UnqualifiedApproval"; + break; + default: + str = "Unknown"; + break; + } + + return str; +} + +const char* MetaProcess::getMiscFlagStr(nn::hac::MiscFlagsHandler::Flags flag) const +{ + const char* str = nullptr; + + switch(flag) + { + case (nn::hac::MiscFlagsHandler::FLAG_ENABLE_DEBUG): + str = "EnableDebug"; + break; + case (nn::hac::MiscFlagsHandler::FLAG_FORCE_DEBUG): + str = "ForceDebug"; + break; + default: + str = "Unknown"; + break; + } + + return str; +} + +const char* MetaProcess::getFsaRightStr(nn::hac::fac::FsAccessFlag flag) const +{ + const char* str = nullptr; + + switch(flag) + { + case (nn::hac::fac::FSA_APPLICATION_INFO): + str = "ApplicationInfo"; + break; + case (nn::hac::fac::FSA_BOOT_MODE_CONTROL): + str = "BootModeControl"; + break; + case (nn::hac::fac::FSA_CALIBRATION): + str = "Calibration"; + break; + case (nn::hac::fac::FSA_SYSTEM_SAVE_DATA): + str = "SystemSaveData"; + break; + case (nn::hac::fac::FSA_GAME_CARD): + str = "GameCard"; + break; + case (nn::hac::fac::FSA_SAVE_DATA_BACKUP): + str = "SaveDataBackUp"; + break; + case (nn::hac::fac::FSA_SAVE_DATA_MANAGEMENT): + str = "SaveDataManagement"; + break; + case (nn::hac::fac::FSA_BIS_ALL_RAW): + str = "BisAllRaw"; + break; + case (nn::hac::fac::FSA_GAME_CARD_RAW): + str = "GameCardRaw"; + break; + case (nn::hac::fac::FSA_GAME_CARD_PRIVATE): + str = "GameCardPrivate"; + break; + case (nn::hac::fac::FSA_SET_TIME): + str = "SetTime"; + break; + case (nn::hac::fac::FSA_CONTENT_MANAGER): + str = "ContentManager"; + break; + case (nn::hac::fac::FSA_IMAGE_MANAGER): + str = "ImageManager"; + break; + case (nn::hac::fac::FSA_CREATE_SAVE_DATA): + str = "CreateSaveData"; + break; + case (nn::hac::fac::FSA_SYSTEM_SAVE_DATA_MANAGEMENT): + str = "SystemSaveDataManagement"; + break; + case (nn::hac::fac::FSA_BIS_FILE_SYSTEM): + str = "BisFileSystem"; + break; + case (nn::hac::fac::FSA_SYSTEM_UPDATE): + str = "SystemUpdate"; + break; + case (nn::hac::fac::FSA_SAVE_DATA_META): + str = "SaveDataMeta"; + break; + case (nn::hac::fac::FSA_DEVICE_SAVE_CONTROL): + str = "DeviceSaveData"; + break; + case (nn::hac::fac::FSA_SETTINGS_CONTROL): + str = "SettingsControl"; + break; + case (nn::hac::fac::FSA_DEBUG): + str = "Debug"; + break; + case (nn::hac::fac::FSA_FULL_PERMISSION): + str = "FullPermission"; + break; + default: + str = "Unknown"; + break; + } + + return str; +} + +const char* MetaProcess::getSaveDataOwnerAccessModeStr(nn::hac::fac::SaveDataOwnerIdAccessType type) const +{ + const char* str = nullptr; + + switch(type) + { + case (nn::hac::fac::SDO_READ): + str = "Read"; + break; + case (nn::hac::fac::SDO_WRITE): + str = "Write"; + break; + case (nn::hac::fac::SDO_READWRITE): + str = "ReadWrite"; + break; + default: + str = "Unknown"; + break; + } + + return str; +} + +const char* MetaProcess::getSystemCallStr(byte_t syscall_id) const +{ + const char* str = nullptr; + + switch(syscall_id) + { + case (0x01): + str = "SetHeapSize"; + break; + case (0x02): + str = "SetMemoryPermission"; + break; + case (0x03): + str = "SetMemoryAttribute"; + break; + case (0x04): + str = "MapMemory"; + break; + case (0x05): + str = "UnmapMemory"; + break; + case (0x06): + str = "QueryMemory"; + break; + case (0x07): + str = "ExitProcess"; + break; + case (0x08): + str = "CreateThread"; + break; + case (0x09): + str = "StartThread"; + break; + case (0x0a): + str = "ExitThread"; + break; + case (0x0b): + str = "SleepThread"; + break; + case (0x0c): + str = "GetThreadPriority"; + break; + case (0x0d): + str = "SetThreadPriority"; + break; + case (0x0e): + str = "GetThreadCoreMask"; + break; + case (0x0f): + str = "SetThreadCoreMask"; + break; + case (0x10): + str = "GetCurrentProcessorNumber"; + break; + case (0x11): + str = "SignalEvent"; + break; + case (0x12): + str = "ClearEvent"; + break; + case (0x13): + str = "MapSharedMemory"; + break; + case (0x14): + str = "UnmapSharedMemory"; + break; + case (0x15): + str = "CreateTransferMemory"; + break; + case (0x16): + str = "CloseHandle"; + break; + case (0x17): + str = "ResetSignal"; + break; + case (0x18): + str = "WaitSynchronization"; + break; + case (0x19): + str = "CancelSynchronization"; + break; + case (0x1a): + str = "ArbitrateLock"; + break; + case (0x1b): + str = "ArbitrateUnlock"; + break; + case (0x1c): + str = "WaitProcessWideKeyAtomic"; + break; + case (0x1d): + str = "SignalProcessWideKey"; + break; + case (0x1e): + str = "GetSystemTick"; + break; + case (0x1f): + str = "ConnectToNamedPort"; + break; + case (0x20): + str = "SendSyncRequestLight"; + break; + case (0x21): + str = "SendSyncRequest"; + break; + case (0x22): + str = "SendSyncRequestWithUserBuffer"; + break; + case (0x23): + str = "SendAsyncRequestWithUserBuffer"; + break; + case (0x24): + str = "GetProcessId"; + break; + case (0x25): + str = "GetThreadId"; + break; + case (0x26): + str = "Break"; + break; + case (0x27): + str = "OutputDebugString"; + break; + case (0x28): + str = "ReturnFromException"; + break; + case (0x29): + str = "GetInfo"; + break; + case (0x2a): + str = "FlushEntireDataCache"; + break; + case (0x2b): + str = "FlushDataCache"; + break; + case (0x2c): + str = "MapPhysicalMemory"; + break; + case (0x2d): + str = "UnmapPhysicalMemory"; + break; + case (0x2e): + str = "GetFutureThreadInfo"; + break; + case (0x2f): + str = "GetLastThreadInfo"; + break; + case (0x30): + str = "GetResourceLimitLimitValue"; + break; + case (0x31): + str = "GetResourceLimitCurrentValue"; + break; + case (0x32): + str = "SetThreadActivity"; + break; + case (0x33): + str = "GetThreadContext3"; + break; + case (0x34): + str = "WaitForAddress"; + break; + case (0x35): + str = "SignalToAddress"; + break; + case (0x36): + str = "svc36"; + break; + case (0x37): + str = "svc37"; + break; + case (0x38): + str = "svc38"; + break; + case (0x39): + str = "svc39"; + break; + case (0x3a): + str = "svc3A"; + break; + case (0x3b): + str = "svc3B"; + break; + case (0x3c): + str = "DumpInfo"; + break; + case (0x3d): + str = "DumpInfoNew"; + break; + case (0x3e): + str = "svc3E"; + break; + case (0x3f): + str = "svc3F"; + break; + case (0x40): + str = "CreateSession"; + break; + case (0x41): + str = "AcceptSession"; + break; + case (0x42): + str = "ReplyAndReceiveLight"; + break; + case (0x43): + str = "ReplyAndReceive"; + break; + case (0x44): + str = "ReplyAndReceiveWithUserBuffer"; + break; + case (0x45): + str = "CreateEvent"; + break; + case (0x46): + str = "svc46"; + break; + case (0x47): + str = "svc47"; + break; + case (0x48): + str = "MapPhysicalMemoryUnsafe"; + break; + case (0x49): + str = "UnmapPhysicalMemoryUnsafe"; + break; + case (0x4a): + str = "SetUnsafeLimit"; + break; + case (0x4b): + str = "CreateCodeMemory"; + break; + case (0x4c): + str = "ControlCodeMemory"; + break; + case (0x4d): + str = "SleepSystem"; + break; + case (0x4e): + str = "ReadWriteRegister"; + break; + case (0x4f): + str = "SetProcessActivity"; + break; + case (0x50): + str = "CreateSharedMemory"; + break; + case (0x51): + str = "MapTransferMemory"; + break; + case (0x52): + str = "UnmapTransferMemory"; + break; + case (0x53): + str = "CreateInterruptEvent"; + break; + case (0x54): + str = "QueryPhysicalAddress"; + break; + case (0x55): + str = "QueryIoMapping"; + break; + case (0x56): + str = "CreateDeviceAddressSpace"; + break; + case (0x57): + str = "AttachDeviceAddressSpace"; + break; + case (0x58): + str = "DetachDeviceAddressSpace"; + break; + case (0x59): + str = "MapDeviceAddressSpaceByForce"; + break; + case (0x5a): + str = "MapDeviceAddressSpaceAligned"; + break; + case (0x5b): + str = "MapDeviceAddressSpace"; + break; + case (0x5c): + str = "UnmapDeviceAddressSpace"; + break; + case (0x5d): + str = "InvalidateProcessDataCache"; + break; + case (0x5e): + str = "StoreProcessDataCache"; + break; + case (0x5f): + str = "FlushProcessDataCache"; + break; + case (0x60): + str = "DebugActiveProcess"; + break; + case (0x61): + str = "BreakDebugProcess"; + break; + case (0x62): + str = "TerminateDebugProcess"; + break; + case (0x63): + str = "GetDebugEvent"; + break; + case (0x64): + str = "ContinueDebugEvent"; + break; + case (0x65): + str = "GetProcessList"; + break; + case (0x66): + str = "GetThreadList"; + break; + case (0x67): + str = "GetDebugThreadContext"; + break; + case (0x68): + str = "SetDebugThreadContext"; + break; + case (0x69): + str = "QueryDebugProcessMemory"; + break; + case (0x6a): + str = "ReadDebugProcessMemory"; + break; + case (0x6b): + str = "WriteDebugProcessMemory"; + break; + case (0x6c): + str = "SetHardwareBreakPoint"; + break; + case (0x6d): + str = "GetDebugThreadParam"; + break; + case (0x6e): + str = "svc6E"; + break; + case (0x6f): + str = "GetSystemInfo"; + break; + case (0x70): + str = "CreatePort"; + break; + case (0x71): + str = "ManageNamedPort"; + break; + case (0x72): + str = "ConnectToPort"; + break; + case (0x73): + str = "SetProcessMemoryPermission"; + break; + case (0x74): + str = "MapProcessMemory"; + break; + case (0x75): + str = "UnmapProcessMemory"; + break; + case (0x76): + str = "QueryProcessMemory"; + break; + case (0x77): + str = "MapProcessCodeMemory"; + break; + case (0x78): + str = "UnmapProcessCodeMemory"; + break; + case (0x79): + str = "CreateProcess"; + break; + case (0x7a): + str = "StartProcess"; + break; + case (0x7b): + str = "TerminateProcess"; + break; + case (0x7c): + str = "GetProcessInfo"; + break; + case (0x7d): + str = "CreateResourceLimit"; + break; + case (0x7e): + str = "SetResourceLimitLimitValue"; + break; + case (0x7f): + str = "CallSecureMonitor"; + break; + default: + str = "Unknown"; + break; + } + + return str; +} + +const char* MetaProcess::getMemMapPermStr(nn::hac::MemoryMappingHandler::MemoryPerm type) const +{ + const char* str = nullptr; + + switch(type) + { + case (nn::hac::MemoryMappingHandler::MEM_RW): + str = "RW"; + break; + case (nn::hac::MemoryMappingHandler::MEM_RO): + str = "RO"; + break; + default: + str = "Unknown"; + break; + } + + return str; +} + +const char* MetaProcess::getMemMapTypeStr(nn::hac::MemoryMappingHandler::MappingType type) const +{ + const char* str = nullptr; + + switch(type) + { + case (nn::hac::MemoryMappingHandler::MAP_IO): + str = "Io"; + break; + case (nn::hac::MemoryMappingHandler::MAP_STATIC): + str = "Static"; + break; + default: + str = "Unknown"; + break; + } + + return str; } \ No newline at end of file diff --git a/programs/nstool/source/MetaProcess.h b/src/MetaProcess.h similarity index 97% rename from programs/nstool/source/MetaProcess.h rename to src/MetaProcess.h index 3299b1b..1c734c8 100644 --- a/programs/nstool/source/MetaProcess.h +++ b/src/MetaProcess.h @@ -1,56 +1,56 @@ -#pragma once -#include -#include -#include -#include -#include -#include "KeyConfiguration.h" - -#include "common.h" - -class MetaProcess -{ -public: - MetaProcess(); - - void process(); - - void setInputFile(const fnd::SharedPtr& file); - void setKeyCfg(const KeyConfiguration& keycfg); - void setCliOutputMode(CliOutputMode type); - void setVerifyMode(bool verify); - - const nn::hac::Meta& getMeta() const; - -private: - const std::string kModuleName = "MetaProcess"; - - fnd::SharedPtr mFile; - KeyConfiguration mKeyCfg; - CliOutputMode mCliOutputMode; - bool mVerify; - - nn::hac::Meta mMeta; - - void importMeta(); - - void validateAcidSignature(const nn::hac::AccessControlInfoDesc& acid); - void validateAciFromAcid(const nn::hac::AccessControlInfo& aci, const nn::hac::AccessControlInfoDesc& acid); - - void displayMetaHeader(const nn::hac::Meta& hdr); - void displayAciHdr(const nn::hac::AccessControlInfo& aci); - void displayAciDescHdr(const nn::hac::AccessControlInfoDesc& aci); - void displayFac(const nn::hac::FileSystemAccessControl& fac); - void displaySac(const nn::hac::ServiceAccessControl& sac); - void displayKernelCap(const nn::hac::KernelCapabilityControl& kern); - - const char* getInstructionTypeStr(nn::hac::meta::InstructionType type) const; - const char* getProcAddressSpaceTypeStr(nn::hac::meta::ProcAddrSpaceType type) const; - const char* getAcidFlagStr(nn::hac::aci::Flag flag) const; - const char* getMiscFlagStr(nn::hac::MiscFlagsHandler::Flags flag) const; - const char* getFsaRightStr(nn::hac::fac::FsAccessFlag flag) const; - const char* getSaveDataOwnerAccessModeStr(nn::hac::fac::SaveDataOwnerIdAccessType type) const; - const char* getSystemCallStr(byte_t syscall_id) const; - const char* getMemMapPermStr(nn::hac::MemoryMappingHandler::MemoryPerm type) const; - const char* getMemMapTypeStr(nn::hac::MemoryMappingHandler::MappingType type) const; +#pragma once +#include +#include +#include +#include +#include +#include "KeyConfiguration.h" + +#include "common.h" + +class MetaProcess +{ +public: + MetaProcess(); + + void process(); + + void setInputFile(const fnd::SharedPtr& file); + void setKeyCfg(const KeyConfiguration& keycfg); + void setCliOutputMode(CliOutputMode type); + void setVerifyMode(bool verify); + + const nn::hac::Meta& getMeta() const; + +private: + const std::string kModuleName = "MetaProcess"; + + fnd::SharedPtr mFile; + KeyConfiguration mKeyCfg; + CliOutputMode mCliOutputMode; + bool mVerify; + + nn::hac::Meta mMeta; + + void importMeta(); + + void validateAcidSignature(const nn::hac::AccessControlInfoDesc& acid); + void validateAciFromAcid(const nn::hac::AccessControlInfo& aci, const nn::hac::AccessControlInfoDesc& acid); + + void displayMetaHeader(const nn::hac::Meta& hdr); + void displayAciHdr(const nn::hac::AccessControlInfo& aci); + void displayAciDescHdr(const nn::hac::AccessControlInfoDesc& aci); + void displayFac(const nn::hac::FileSystemAccessControl& fac); + void displaySac(const nn::hac::ServiceAccessControl& sac); + void displayKernelCap(const nn::hac::KernelCapabilityControl& kern); + + const char* getInstructionTypeStr(nn::hac::meta::InstructionType type) const; + const char* getProcAddressSpaceTypeStr(nn::hac::meta::ProcAddrSpaceType type) const; + const char* getAcidFlagStr(nn::hac::aci::Flag flag) const; + const char* getMiscFlagStr(nn::hac::MiscFlagsHandler::Flags flag) const; + const char* getFsaRightStr(nn::hac::fac::FsAccessFlag flag) const; + const char* getSaveDataOwnerAccessModeStr(nn::hac::fac::SaveDataOwnerIdAccessType type) const; + const char* getSystemCallStr(byte_t syscall_id) const; + const char* getMemMapPermStr(nn::hac::MemoryMappingHandler::MemoryPerm type) const; + const char* getMemMapTypeStr(nn::hac::MemoryMappingHandler::MappingType type) const; }; \ No newline at end of file diff --git a/programs/nstool/source/NacpProcess.cpp b/src/NacpProcess.cpp similarity index 96% rename from programs/nstool/source/NacpProcess.cpp rename to src/NacpProcess.cpp index be471e8..83ea3d0 100644 --- a/programs/nstool/source/NacpProcess.cpp +++ b/src/NacpProcess.cpp @@ -1,669 +1,669 @@ -#include -#include -#include -#include -#include -#include "NacpProcess.h" - -NacpProcess::NacpProcess() : - mFile(), - mCliOutputMode(_BIT(OUTPUT_BASIC)), - mVerify(false) -{ -} - -void NacpProcess::process() -{ - importNacp(); - - if (_HAS_BIT(mCliOutputMode, OUTPUT_BASIC)) - displayNacp(); -} - -void NacpProcess::setInputFile(const fnd::SharedPtr& file) -{ - mFile = file; -} - -void NacpProcess::setCliOutputMode(CliOutputMode type) -{ - mCliOutputMode = type; -} - -void NacpProcess::setVerifyMode(bool verify) -{ - mVerify = verify; -} - -const nn::hac::ApplicationControlProperty& NacpProcess::getApplicationControlProperty() const -{ - return mNacp; -} - -void NacpProcess::importNacp() -{ - fnd::Vec scratch; - - if (*mFile == nullptr) - { - throw fnd::Exception(kModuleName, "No file reader set."); - } - - scratch.alloc((*mFile)->size()); - (*mFile)->read(scratch.data(), 0, scratch.size()); - - mNacp.fromBytes(scratch.data(), scratch.size()); -} - -void NacpProcess::displayNacp() -{ - std::cout << "[ApplicationControlProperty]" << std::endl; - std::cout << " Menu Description:" << std::endl; - std::cout << " DisplayVersion: " << mNacp.getDisplayVersion() << std::endl; - if (mNacp.getIsbn().empty() == false || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) - std::cout << " ISBN: " << mNacp.getIsbn() << std::endl; - for (size_t i = 0; i < mNacp.getTitle().size(); i++) - { - std::cout << " " << getLanguageStr(mNacp.getTitle()[i].language) << " Title:" << std::endl; - std::cout << " Name: " << mNacp.getTitle()[i].name << std::endl; - std::cout << " Publisher: " << mNacp.getTitle()[i].publisher << std::endl; - } - std::cout << " Logo:" << std::endl; - std::cout << " Type: " << getLogoTypeStr(mNacp.getLogoType()) << std::endl; - std::cout << " Handling: " << getLogoHandlingStr(mNacp.getLogoHandling()) << std::endl; - std::cout << " AddOnContent:" << std::endl; - std::cout << " BaseId: 0x" << std::hex << std::setw(16) << std::setfill('0') << mNacp.getAocBaseId() << std::endl; - std::cout << " RegistrationType: " << getAocRegistrationTypeStr(mNacp.getAocRegistrationType()) << std::endl; - std::cout << " RuntimeInstallMode: " << getRuntimeAocInstallModeStr(mNacp.getRuntimeAocInstallMode()) << std::endl; - std::cout << " Play Log:" << std::endl; - std::cout << " PlayLogPolicy: " << getPlayLogPolicyStr(mNacp.getPlayLogPolicy()) << std::endl; - std::cout << " PlayLogQueryCapability: " << getPlayLogQueryCapabilityStr(mNacp.getPlayLogQueryCapability()) << std::endl; - if (mNacp.getPlayLogQueryableApplicationId().size() > 0) - { - std::cout << " PlayLogQueryableApplicationId:" << std::endl; - for (size_t i = 0; i < mNacp.getPlayLogQueryableApplicationId().size(); i++) - { - std::cout << " 0x" << std::hex << std::setw(16) << std::setfill('0') << mNacp.getPlayLogQueryableApplicationId()[i] << std::endl; - } - } - std::cout << " Parental Controls:" << std::endl; - std::cout << " ParentalControlFlag: " << getParentalControlFlagStr(mNacp.getParentalControlFlag()) << std::endl; - for (size_t i = 0; i < mNacp.getRatingAge().size(); i++) - { - std::cout << " Age Restriction:" << std::endl; - std::cout << " Agency: " << getOrganisationStr(mNacp.getRatingAge()[i].organisation) << std::endl; - std::cout << " Age: " << std::dec << (uint32_t)mNacp.getRatingAge()[i].age << std::endl; - } - - if (mNacp.getBcatPassphase().empty() == false || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) - { - std::cout << " BCAT:" << std::endl; - std::cout << " BcatPassphase: " << mNacp.getBcatPassphase() << std::endl; - std::cout << " DeliveryCacheStorageSize: 0x" << std::hex << mNacp.getBcatDeliveryCacheStorageSize() << std::endl; - } - if (mNacp.getLocalCommunicationId().size() > 0) - { - std::cout << " Local Area Communication:" << std::endl; - std::cout << " LocalCommunicationId:" << std::endl; - for (size_t i = 0; i < mNacp.getLocalCommunicationId().size(); i++) - { - std::cout << " 0x" << std::hex << std::setw(16) << std::setfill('0') << mNacp.getLocalCommunicationId()[i] << std::endl; - } - } - std::cout << " SaveData:" << std::endl; - std::cout << " SaveDatawOwnerId: 0x" << std::hex << std::setw(16) << std::setfill('0') << mNacp.getSaveDatawOwnerId() << std::endl; - if (mNacp.getUserAccountSaveDataSize().journal_size > 0 || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) - { - std::cout << " UserAccountSaveData:" << std::endl; - std::cout << " Size: " << getSaveDataSizeStr(mNacp.getUserAccountSaveDataSize().size) << std::endl; - std::cout << " JournalSize: " << getSaveDataSizeStr(mNacp.getUserAccountSaveDataSize().journal_size) << std::endl; - } - if (mNacp.getDeviceSaveDataSize().journal_size > 0 || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) - { - std::cout << " DeviceSaveData:" << std::endl; - std::cout << " Size: " << getSaveDataSizeStr(mNacp.getDeviceSaveDataSize().size) << std::endl; - std::cout << " JournalSize: " << getSaveDataSizeStr(mNacp.getDeviceSaveDataSize().journal_size) << std::endl; - } - if (mNacp.getUserAccountSaveDataMax().journal_size > 0 || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) - { - std::cout << " UserAccountSaveDataMax:" << std::endl; - std::cout << " Size: " << getSaveDataSizeStr(mNacp.getUserAccountSaveDataMax().size) << std::endl; - std::cout << " JournalSize: " << getSaveDataSizeStr(mNacp.getUserAccountSaveDataMax().journal_size) << std::endl; - } - if (mNacp.getDeviceSaveDataMax().journal_size > 0 || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) - { - std::cout << " DeviceSaveDataMax:" << std::endl; - std::cout << " Size: " << getSaveDataSizeStr(mNacp.getDeviceSaveDataMax().size) << std::endl; - std::cout << " JournalSize: " << getSaveDataSizeStr(mNacp.getDeviceSaveDataMax().journal_size) << std::endl; - } - if (mNacp.getTemporaryStorageSize() > 0 || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) - { - std::cout << " TemporaryStorageSize: " << getSaveDataSizeStr(mNacp.getTemporaryStorageSize()) << std::endl; - } - if (mNacp.getCacheStorageSize().journal_size > 0 || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) - { - std::cout << " CacheStorage:" << std::endl; - std::cout << " Size: " << getSaveDataSizeStr(mNacp.getCacheStorageSize().size) << std::endl; - std::cout << " JournalSize: " << getSaveDataSizeStr(mNacp.getCacheStorageSize().journal_size) << std::endl; - std::cout << " MaxDataAndJournalSize: " << getSaveDataSizeStr(mNacp.getCacheStorageDataAndJournalSizeMax()) << std::endl; - std::cout << " StorageIndexMax: 0x" << std::hex << mNacp.getCacheStorageIndexMax() << std::endl; - } - std::cout << " Other Flags:" << std::endl; - std::cout << " StartupUserAccount: " << getStartupUserAccountStr(mNacp.getStartupUserAccount()) << std::endl; - std::cout << " UserAccountSwitchLock: " << getUserAccountSwitchLockValueStr(mNacp.getUserAccountSwitchLockValue()) << std::endl; - std::cout << " AttributeFlag: " << getAttributeFlagStr(mNacp.getAttributeFlag()) << std::endl; - std::cout << " CrashReportMode: " << getCrashReportModeStr(mNacp.getCrashReportMode()) << std::endl; - std::cout << " HDCP: " << getHdcpStr(mNacp.getHdcp()) << std::endl; - std::cout << " ScreenshotMode: " << getScreenshotModeStr(mNacp.getScreenshotMode()) << std::endl; - std::cout << " VideoCaptureMode: " << getVideoCaptureModeStr(mNacp.getVideoCaptureMode()) << std::endl; - std::cout << " DataLossConfirmation: " << getDataLossConfirmationStr(mNacp.getDataLossConfirmation()) << std::endl; - std::cout << " RepairFlag: " << getRepairFlagStr(mNacp.getRepairFlag()) << std::endl; - std::cout << " ProgramIndex: 0x" << std::hex << std::setw(2) << std::setfill('0') << (uint32_t)mNacp.getProgramIndex() << std::endl; - std::cout << " Req NetworkLicenseOnLaunch: " << getRequiredNetworkServiceLicenseOnLaunchValueStr(mNacp.getRequiredNetworkServiceLicenseOnLaunchValue()) << std::endl; - if (mNacp.getApplicationErrorCodeCategory().empty() == false || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) - { - std::cout << " ApplicationErrorCodeCategory: " << mNacp.getApplicationErrorCodeCategory() << std::endl; - } - if (mNacp.getSeedForPsuedoDeviceId() > 0 || mNacp.getPresenceGroupId() > 0 || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) - { - std::cout << " Other Ids:" << std::endl; - if (mNacp.getSeedForPsuedoDeviceId() > 0 || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) - std::cout << " SeedForPsuedoDeviceId: 0x" << std::hex << std::setw(16) << std::setfill('0') << mNacp.getSeedForPsuedoDeviceId() << std::endl; - if (mNacp.getPresenceGroupId() > 0 || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) - std::cout << " PresenceGroupId: 0x" << std::hex << std::setw(16) << std::setfill('0') << mNacp.getPresenceGroupId() << std::endl; - } -} - -const char* NacpProcess::getLanguageStr(nn::hac::nacp::Language var) const -{ - const char* str = nullptr; - - switch(var) - { - case (nn::hac::nacp::LANG_AmericanEnglish): - str = "AmericanEnglish"; - break; - case (nn::hac::nacp::LANG_BritishEnglish): - str = "BritishEnglish"; - break; - case (nn::hac::nacp::LANG_Japanese): - str = "Japanese"; - break; - case (nn::hac::nacp::LANG_French): - str = "French"; - break; - case (nn::hac::nacp::LANG_German): - str = "German"; - break; - case (nn::hac::nacp::LANG_LatinAmericanSpanish): - str = "LatinAmericanSpanish"; - break; - case (nn::hac::nacp::LANG_Spanish): - str = "Spanish"; - break; - case (nn::hac::nacp::LANG_Italian): - str = "Italian"; - break; - case (nn::hac::nacp::LANG_Dutch): - str = "Dutch"; - break; - case (nn::hac::nacp::LANG_CanadianFrench): - str = "CanadianFrench"; - break; - case (nn::hac::nacp::LANG_Portuguese): - str = "Portuguese"; - break; - case (nn::hac::nacp::LANG_Russian): - str = "Russian"; - break; - case (nn::hac::nacp::LANG_Korean): - str = "Korean"; - break; - case (nn::hac::nacp::LANG_TraditionalChinese): - str = "TraditionalChinese"; - break; - case (nn::hac::nacp::LANG_SimplifiedChinese): - str = "SimplifiedChinese"; - break; - default: - str = "Unknown"; - } - - return str; -} - -const char* NacpProcess::getStartupUserAccountStr(nn::hac::nacp::StartupUserAccount var) const -{ - const char* str = nullptr; - - switch(var) - { - case (nn::hac::nacp::USER_None): - str = "None"; - break; - case (nn::hac::nacp::USER_Required): - str = "Required"; - break; - case (nn::hac::nacp::USER_RequiredWithNetworkServiceAccountAvailable): - str = "RequiredWithNetworkServiceAccountAvailable"; - break; - default: - str = "Unknown"; - } - - return str; -} - -const char* NacpProcess::getTouchScreenUsageModeStr(nn::hac::nacp::TouchScreenUsageMode var) const -{ - const char* str = nullptr; - - switch(var) - { - case (nn::hac::nacp::TOUCH_None): - str = "None"; - break; - case (nn::hac::nacp::TOUCH_Supported): - str = "Supported"; - break; - case (nn::hac::nacp::TOUCH_Required): - str = "Required"; - break; - default: - str = "Unknown"; - } - - return str; -} - -const char* NacpProcess::getUserAccountSwitchLockValueStr(nn::hac::nacp::UserAccountSwitchLockValue var) const -{ - const char* str = nullptr; - - switch (var) - { - case (nn::hac::nacp::UASL_Disable): - str = "Disable"; - break; - case (nn::hac::nacp::UASL_Enable): - str = "Enable"; - break; - default: - str = "Unknown"; - } - - return str; -} - -const char* NacpProcess::getAocRegistrationTypeStr(nn::hac::nacp::AocRegistrationType var) const -{ - const char* str = nullptr; - - switch(var) - { - case (nn::hac::nacp::AOC_AllOnLaunch): - str = "AllOnLaunch"; - break; - case (nn::hac::nacp::AOC_OnDemand): - str = "OnDemand"; - break; - default: - str = "Unknown"; - } - - return str; -} - -const char* NacpProcess::getAttributeFlagStr(nn::hac::nacp::AttributeFlag var) const -{ - const char* str = nullptr; - - switch(var) - { - case (nn::hac::nacp::ATTR_None): - str = "None"; - break; - case (nn::hac::nacp::ATTR_Demo): - str = "Demo"; - break; - case (nn::hac::nacp::ATTR_RetailInteractiveDisplay): - str = "RetailInteractiveDisplay"; - break; - default: - str = "Unknown"; - } - - return str; -} - -const char* NacpProcess::getParentalControlFlagStr(nn::hac::nacp::ParentalControlFlag var) const -{ - const char* str = nullptr; - - switch(var) - { - case (nn::hac::nacp::PC_None): - str = "None"; - break; - case (nn::hac::nacp::PC_FreeCommunication): - str = "FreeCommunication"; - break; - default: - str = "Unknown"; - } - - return str; -} - -const char* NacpProcess::getScreenshotModeStr(nn::hac::nacp::ScreenshotMode var) const -{ - const char* str = nullptr; - - switch(var) - { - case (nn::hac::nacp::SCRN_Allow): - str = "Allow"; - break; - case (nn::hac::nacp::SCRN_Deny): - str = "Deny"; - break; - default: - str = "Unknown"; - } - - return str; -} - -const char* NacpProcess::getVideoCaptureModeStr(nn::hac::nacp::VideoCaptureMode var) const -{ - const char* str = nullptr; - - switch(var) - { - case (nn::hac::nacp::VCAP_Disable): - str = "Disable"; - break; - case (nn::hac::nacp::VCAP_Manual): - str = "Manual"; - break; - case (nn::hac::nacp::VCAP_Enable): - str = "Enable"; - break; - default: - str = "Unknown"; - } - - return str; -} - -const char* NacpProcess::getDataLossConfirmationStr(nn::hac::nacp::DataLossConfirmation var) const -{ - const char* str = nullptr; - - switch(var) - { - case (nn::hac::nacp::DLOSS_None): - str = "None"; - break; - case (nn::hac::nacp::DLOSS_Required): - str = "Required"; - break; - default: - str = "Unknown"; - } - - return str; -} - -const char* NacpProcess::getPlayLogPolicyStr(nn::hac::nacp::PlayLogPolicy var) const -{ - const char* str = nullptr; - - switch(var) - { - case (nn::hac::nacp::PLP_All): - str = "All"; - break; - case (nn::hac::nacp::PLP_LogOnly): - str = "LogOnly"; - break; - case (nn::hac::nacp::PLP_None): - str = "None"; - break; - default: - str = "Unknown"; - } - - return str; -} - -const char* NacpProcess::getOrganisationStr(nn::hac::nacp::Organisation var) const -{ - const char* str = nullptr; - - switch(var) - { - case (nn::hac::nacp::ORGN_CERO): - str = "CERO"; - break; - case (nn::hac::nacp::ORGN_GRACGCRB): - str = "GRACGCRB"; - break; - case (nn::hac::nacp::ORGN_GSRMR): - str = "GSRMR"; - break; - case (nn::hac::nacp::ORGN_ESRB): - str = "ESRB"; - break; - case (nn::hac::nacp::ORGN_ClassInd): - str = "ClassInd"; - break; - case (nn::hac::nacp::ORGN_USK): - str = "USK"; - break; - case (nn::hac::nacp::ORGN_PEGI): - str = "PEGI"; - break; - case (nn::hac::nacp::ORGN_PEGIPortugal): - str = "PEGIPortugal"; - break; - case (nn::hac::nacp::ORGN_PEGIBBFC): - str = "PEGIBBFC"; - break; - case (nn::hac::nacp::ORGN_Russian): - str = "Russian"; - break; - case (nn::hac::nacp::ORGN_ACB): - str = "ACB"; - break; - case (nn::hac::nacp::ORGN_OFLC): - str = "OFLC"; - break; - default: - str = "Unknown"; - } - - return str; -} - -const char* NacpProcess::getLogoTypeStr(nn::hac::nacp::LogoType var) const -{ - const char* str = nullptr; - - switch(var) - { - case (nn::hac::nacp::LOGO_LicensedByNintendo): - str = "LicensedByNintendo"; - break; - case (nn::hac::nacp::LOGO_DistributedByNintendo): - str = "DistributedByNintendo"; - break; - case (nn::hac::nacp::LOGO_Nintendo): - str = "Nintendo"; - break; - default: - str = "Unknown"; - } - - return str; -} - -const char* NacpProcess::getLogoHandlingStr(nn::hac::nacp::LogoHandling var) const -{ - const char* str = nullptr; - - switch(var) - { - case (nn::hac::nacp::LHND_Auto): - str = "Auto"; - break; - case (nn::hac::nacp::LHND_None): - str = "None"; - break; - default: - str = "Unknown"; - } - - return str; -} - -const char* NacpProcess::getRuntimeAocInstallModeStr(nn::hac::nacp::RuntimeAocInstallMode var) const -{ - const char* str = nullptr; - - switch(var) - { - case (nn::hac::nacp::RTAOC_Deny): - str = "Deny"; - break; - case (nn::hac::nacp::RTAOC_AllowAppend): - str = "AllowAppend"; - break; - default: - str = "Unknown"; - } - - return str; -} - -const char* NacpProcess::getCrashReportModeStr(nn::hac::nacp::CrashReportMode var) const -{ - const char* str = nullptr; - - switch(var) - { - case (nn::hac::nacp::CREP_Deny): - str = "Deny"; - break; - case (nn::hac::nacp::CREP_Allow): - str = "Allow"; - break; - default: - str = "Unknown"; - } - - return str; -} - -const char* NacpProcess::getHdcpStr(nn::hac::nacp::Hdcp var) const -{ - const char* str = nullptr; - - switch(var) - { - case (nn::hac::nacp::HDCP_None): - str = "None"; - break; - case (nn::hac::nacp::HDCP_Required): - str = "Required"; - break; - default: - str = "Unknown"; - } - - return str; -} - -const char* NacpProcess::getPlayLogQueryCapabilityStr(nn::hac::nacp::PlayLogQueryCapability var) const -{ - const char* str = nullptr; - - switch(var) - { - case (nn::hac::nacp::PLQC_None): - str = "None"; - break; - case (nn::hac::nacp::PLQC_Whitelist): - str = "Whitelist"; - break; - case (nn::hac::nacp::PLQC_All): - str = "All"; - break; - default: - str = "Unknown"; - } - - return str; -} - -const char* NacpProcess::getRepairFlagStr(nn::hac::nacp::RepairFlag var) const -{ - const char* str = nullptr; - - switch(var) - { - case (nn::hac::nacp::REPF_None): - str = "None"; - break; - case (nn::hac::nacp::REPF_SuppressGameCardAccess): - str = "SuppressGameCardAccess"; - break; - default: - str = "Unknown"; - } - - return str; -} - -const char* NacpProcess::getRequiredNetworkServiceLicenseOnLaunchValueStr(nn::hac::nacp::RequiredNetworkServiceLicenseOnLaunchValue var) const -{ - const char* str = nullptr; - - switch (var) - { - case (nn::hac::nacp::REQNETLIC_None): - str = "None"; - break; - case (nn::hac::nacp::REQNETLIC_Common): - str = "Common"; - break; - default: - str = "Unknown"; - } - - return str; -} - -std::string NacpProcess::getSaveDataSizeStr(int64_t size) const -{ - static const int64_t kKiloByte = 1024; - static const int64_t kMegaByte = 1024 * 1024; - - std::stringstream sstr; - - - if (size < kKiloByte) - { - sstr << size << " B"; - } - else if (size < kMegaByte) - { - sstr << (size/kKiloByte) << " KB"; - } - else - { - sstr << (size/kMegaByte) << " MB"; - } - - return sstr.str(); +#include +#include +#include +#include +#include +#include "NacpProcess.h" + +NacpProcess::NacpProcess() : + mFile(), + mCliOutputMode(_BIT(OUTPUT_BASIC)), + mVerify(false) +{ +} + +void NacpProcess::process() +{ + importNacp(); + + if (_HAS_BIT(mCliOutputMode, OUTPUT_BASIC)) + displayNacp(); +} + +void NacpProcess::setInputFile(const fnd::SharedPtr& file) +{ + mFile = file; +} + +void NacpProcess::setCliOutputMode(CliOutputMode type) +{ + mCliOutputMode = type; +} + +void NacpProcess::setVerifyMode(bool verify) +{ + mVerify = verify; +} + +const nn::hac::ApplicationControlProperty& NacpProcess::getApplicationControlProperty() const +{ + return mNacp; +} + +void NacpProcess::importNacp() +{ + fnd::Vec scratch; + + if (*mFile == nullptr) + { + throw fnd::Exception(kModuleName, "No file reader set."); + } + + scratch.alloc((*mFile)->size()); + (*mFile)->read(scratch.data(), 0, scratch.size()); + + mNacp.fromBytes(scratch.data(), scratch.size()); +} + +void NacpProcess::displayNacp() +{ + std::cout << "[ApplicationControlProperty]" << std::endl; + std::cout << " Menu Description:" << std::endl; + std::cout << " DisplayVersion: " << mNacp.getDisplayVersion() << std::endl; + if (mNacp.getIsbn().empty() == false || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) + std::cout << " ISBN: " << mNacp.getIsbn() << std::endl; + for (size_t i = 0; i < mNacp.getTitle().size(); i++) + { + std::cout << " " << getLanguageStr(mNacp.getTitle()[i].language) << " Title:" << std::endl; + std::cout << " Name: " << mNacp.getTitle()[i].name << std::endl; + std::cout << " Publisher: " << mNacp.getTitle()[i].publisher << std::endl; + } + std::cout << " Logo:" << std::endl; + std::cout << " Type: " << getLogoTypeStr(mNacp.getLogoType()) << std::endl; + std::cout << " Handling: " << getLogoHandlingStr(mNacp.getLogoHandling()) << std::endl; + std::cout << " AddOnContent:" << std::endl; + std::cout << " BaseId: 0x" << std::hex << std::setw(16) << std::setfill('0') << mNacp.getAocBaseId() << std::endl; + std::cout << " RegistrationType: " << getAocRegistrationTypeStr(mNacp.getAocRegistrationType()) << std::endl; + std::cout << " RuntimeInstallMode: " << getRuntimeAocInstallModeStr(mNacp.getRuntimeAocInstallMode()) << std::endl; + std::cout << " Play Log:" << std::endl; + std::cout << " PlayLogPolicy: " << getPlayLogPolicyStr(mNacp.getPlayLogPolicy()) << std::endl; + std::cout << " PlayLogQueryCapability: " << getPlayLogQueryCapabilityStr(mNacp.getPlayLogQueryCapability()) << std::endl; + if (mNacp.getPlayLogQueryableApplicationId().size() > 0) + { + std::cout << " PlayLogQueryableApplicationId:" << std::endl; + for (size_t i = 0; i < mNacp.getPlayLogQueryableApplicationId().size(); i++) + { + std::cout << " 0x" << std::hex << std::setw(16) << std::setfill('0') << mNacp.getPlayLogQueryableApplicationId()[i] << std::endl; + } + } + std::cout << " Parental Controls:" << std::endl; + std::cout << " ParentalControlFlag: " << getParentalControlFlagStr(mNacp.getParentalControlFlag()) << std::endl; + for (size_t i = 0; i < mNacp.getRatingAge().size(); i++) + { + std::cout << " Age Restriction:" << std::endl; + std::cout << " Agency: " << getOrganisationStr(mNacp.getRatingAge()[i].organisation) << std::endl; + std::cout << " Age: " << std::dec << (uint32_t)mNacp.getRatingAge()[i].age << std::endl; + } + + if (mNacp.getBcatPassphase().empty() == false || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) + { + std::cout << " BCAT:" << std::endl; + std::cout << " BcatPassphase: " << mNacp.getBcatPassphase() << std::endl; + std::cout << " DeliveryCacheStorageSize: 0x" << std::hex << mNacp.getBcatDeliveryCacheStorageSize() << std::endl; + } + if (mNacp.getLocalCommunicationId().size() > 0) + { + std::cout << " Local Area Communication:" << std::endl; + std::cout << " LocalCommunicationId:" << std::endl; + for (size_t i = 0; i < mNacp.getLocalCommunicationId().size(); i++) + { + std::cout << " 0x" << std::hex << std::setw(16) << std::setfill('0') << mNacp.getLocalCommunicationId()[i] << std::endl; + } + } + std::cout << " SaveData:" << std::endl; + std::cout << " SaveDatawOwnerId: 0x" << std::hex << std::setw(16) << std::setfill('0') << mNacp.getSaveDatawOwnerId() << std::endl; + if (mNacp.getUserAccountSaveDataSize().journal_size > 0 || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) + { + std::cout << " UserAccountSaveData:" << std::endl; + std::cout << " Size: " << getSaveDataSizeStr(mNacp.getUserAccountSaveDataSize().size) << std::endl; + std::cout << " JournalSize: " << getSaveDataSizeStr(mNacp.getUserAccountSaveDataSize().journal_size) << std::endl; + } + if (mNacp.getDeviceSaveDataSize().journal_size > 0 || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) + { + std::cout << " DeviceSaveData:" << std::endl; + std::cout << " Size: " << getSaveDataSizeStr(mNacp.getDeviceSaveDataSize().size) << std::endl; + std::cout << " JournalSize: " << getSaveDataSizeStr(mNacp.getDeviceSaveDataSize().journal_size) << std::endl; + } + if (mNacp.getUserAccountSaveDataMax().journal_size > 0 || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) + { + std::cout << " UserAccountSaveDataMax:" << std::endl; + std::cout << " Size: " << getSaveDataSizeStr(mNacp.getUserAccountSaveDataMax().size) << std::endl; + std::cout << " JournalSize: " << getSaveDataSizeStr(mNacp.getUserAccountSaveDataMax().journal_size) << std::endl; + } + if (mNacp.getDeviceSaveDataMax().journal_size > 0 || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) + { + std::cout << " DeviceSaveDataMax:" << std::endl; + std::cout << " Size: " << getSaveDataSizeStr(mNacp.getDeviceSaveDataMax().size) << std::endl; + std::cout << " JournalSize: " << getSaveDataSizeStr(mNacp.getDeviceSaveDataMax().journal_size) << std::endl; + } + if (mNacp.getTemporaryStorageSize() > 0 || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) + { + std::cout << " TemporaryStorageSize: " << getSaveDataSizeStr(mNacp.getTemporaryStorageSize()) << std::endl; + } + if (mNacp.getCacheStorageSize().journal_size > 0 || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) + { + std::cout << " CacheStorage:" << std::endl; + std::cout << " Size: " << getSaveDataSizeStr(mNacp.getCacheStorageSize().size) << std::endl; + std::cout << " JournalSize: " << getSaveDataSizeStr(mNacp.getCacheStorageSize().journal_size) << std::endl; + std::cout << " MaxDataAndJournalSize: " << getSaveDataSizeStr(mNacp.getCacheStorageDataAndJournalSizeMax()) << std::endl; + std::cout << " StorageIndexMax: 0x" << std::hex << mNacp.getCacheStorageIndexMax() << std::endl; + } + std::cout << " Other Flags:" << std::endl; + std::cout << " StartupUserAccount: " << getStartupUserAccountStr(mNacp.getStartupUserAccount()) << std::endl; + std::cout << " UserAccountSwitchLock: " << getUserAccountSwitchLockValueStr(mNacp.getUserAccountSwitchLockValue()) << std::endl; + std::cout << " AttributeFlag: " << getAttributeFlagStr(mNacp.getAttributeFlag()) << std::endl; + std::cout << " CrashReportMode: " << getCrashReportModeStr(mNacp.getCrashReportMode()) << std::endl; + std::cout << " HDCP: " << getHdcpStr(mNacp.getHdcp()) << std::endl; + std::cout << " ScreenshotMode: " << getScreenshotModeStr(mNacp.getScreenshotMode()) << std::endl; + std::cout << " VideoCaptureMode: " << getVideoCaptureModeStr(mNacp.getVideoCaptureMode()) << std::endl; + std::cout << " DataLossConfirmation: " << getDataLossConfirmationStr(mNacp.getDataLossConfirmation()) << std::endl; + std::cout << " RepairFlag: " << getRepairFlagStr(mNacp.getRepairFlag()) << std::endl; + std::cout << " ProgramIndex: 0x" << std::hex << std::setw(2) << std::setfill('0') << (uint32_t)mNacp.getProgramIndex() << std::endl; + std::cout << " Req NetworkLicenseOnLaunch: " << getRequiredNetworkServiceLicenseOnLaunchValueStr(mNacp.getRequiredNetworkServiceLicenseOnLaunchValue()) << std::endl; + if (mNacp.getApplicationErrorCodeCategory().empty() == false || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) + { + std::cout << " ApplicationErrorCodeCategory: " << mNacp.getApplicationErrorCodeCategory() << std::endl; + } + if (mNacp.getSeedForPsuedoDeviceId() > 0 || mNacp.getPresenceGroupId() > 0 || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) + { + std::cout << " Other Ids:" << std::endl; + if (mNacp.getSeedForPsuedoDeviceId() > 0 || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) + std::cout << " SeedForPsuedoDeviceId: 0x" << std::hex << std::setw(16) << std::setfill('0') << mNacp.getSeedForPsuedoDeviceId() << std::endl; + if (mNacp.getPresenceGroupId() > 0 || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) + std::cout << " PresenceGroupId: 0x" << std::hex << std::setw(16) << std::setfill('0') << mNacp.getPresenceGroupId() << std::endl; + } +} + +const char* NacpProcess::getLanguageStr(nn::hac::nacp::Language var) const +{ + const char* str = nullptr; + + switch(var) + { + case (nn::hac::nacp::LANG_AmericanEnglish): + str = "AmericanEnglish"; + break; + case (nn::hac::nacp::LANG_BritishEnglish): + str = "BritishEnglish"; + break; + case (nn::hac::nacp::LANG_Japanese): + str = "Japanese"; + break; + case (nn::hac::nacp::LANG_French): + str = "French"; + break; + case (nn::hac::nacp::LANG_German): + str = "German"; + break; + case (nn::hac::nacp::LANG_LatinAmericanSpanish): + str = "LatinAmericanSpanish"; + break; + case (nn::hac::nacp::LANG_Spanish): + str = "Spanish"; + break; + case (nn::hac::nacp::LANG_Italian): + str = "Italian"; + break; + case (nn::hac::nacp::LANG_Dutch): + str = "Dutch"; + break; + case (nn::hac::nacp::LANG_CanadianFrench): + str = "CanadianFrench"; + break; + case (nn::hac::nacp::LANG_Portuguese): + str = "Portuguese"; + break; + case (nn::hac::nacp::LANG_Russian): + str = "Russian"; + break; + case (nn::hac::nacp::LANG_Korean): + str = "Korean"; + break; + case (nn::hac::nacp::LANG_TraditionalChinese): + str = "TraditionalChinese"; + break; + case (nn::hac::nacp::LANG_SimplifiedChinese): + str = "SimplifiedChinese"; + break; + default: + str = "Unknown"; + } + + return str; +} + +const char* NacpProcess::getStartupUserAccountStr(nn::hac::nacp::StartupUserAccount var) const +{ + const char* str = nullptr; + + switch(var) + { + case (nn::hac::nacp::USER_None): + str = "None"; + break; + case (nn::hac::nacp::USER_Required): + str = "Required"; + break; + case (nn::hac::nacp::USER_RequiredWithNetworkServiceAccountAvailable): + str = "RequiredWithNetworkServiceAccountAvailable"; + break; + default: + str = "Unknown"; + } + + return str; +} + +const char* NacpProcess::getTouchScreenUsageModeStr(nn::hac::nacp::TouchScreenUsageMode var) const +{ + const char* str = nullptr; + + switch(var) + { + case (nn::hac::nacp::TOUCH_None): + str = "None"; + break; + case (nn::hac::nacp::TOUCH_Supported): + str = "Supported"; + break; + case (nn::hac::nacp::TOUCH_Required): + str = "Required"; + break; + default: + str = "Unknown"; + } + + return str; +} + +const char* NacpProcess::getUserAccountSwitchLockValueStr(nn::hac::nacp::UserAccountSwitchLockValue var) const +{ + const char* str = nullptr; + + switch (var) + { + case (nn::hac::nacp::UASL_Disable): + str = "Disable"; + break; + case (nn::hac::nacp::UASL_Enable): + str = "Enable"; + break; + default: + str = "Unknown"; + } + + return str; +} + +const char* NacpProcess::getAocRegistrationTypeStr(nn::hac::nacp::AocRegistrationType var) const +{ + const char* str = nullptr; + + switch(var) + { + case (nn::hac::nacp::AOC_AllOnLaunch): + str = "AllOnLaunch"; + break; + case (nn::hac::nacp::AOC_OnDemand): + str = "OnDemand"; + break; + default: + str = "Unknown"; + } + + return str; +} + +const char* NacpProcess::getAttributeFlagStr(nn::hac::nacp::AttributeFlag var) const +{ + const char* str = nullptr; + + switch(var) + { + case (nn::hac::nacp::ATTR_None): + str = "None"; + break; + case (nn::hac::nacp::ATTR_Demo): + str = "Demo"; + break; + case (nn::hac::nacp::ATTR_RetailInteractiveDisplay): + str = "RetailInteractiveDisplay"; + break; + default: + str = "Unknown"; + } + + return str; +} + +const char* NacpProcess::getParentalControlFlagStr(nn::hac::nacp::ParentalControlFlag var) const +{ + const char* str = nullptr; + + switch(var) + { + case (nn::hac::nacp::PC_None): + str = "None"; + break; + case (nn::hac::nacp::PC_FreeCommunication): + str = "FreeCommunication"; + break; + default: + str = "Unknown"; + } + + return str; +} + +const char* NacpProcess::getScreenshotModeStr(nn::hac::nacp::ScreenshotMode var) const +{ + const char* str = nullptr; + + switch(var) + { + case (nn::hac::nacp::SCRN_Allow): + str = "Allow"; + break; + case (nn::hac::nacp::SCRN_Deny): + str = "Deny"; + break; + default: + str = "Unknown"; + } + + return str; +} + +const char* NacpProcess::getVideoCaptureModeStr(nn::hac::nacp::VideoCaptureMode var) const +{ + const char* str = nullptr; + + switch(var) + { + case (nn::hac::nacp::VCAP_Disable): + str = "Disable"; + break; + case (nn::hac::nacp::VCAP_Manual): + str = "Manual"; + break; + case (nn::hac::nacp::VCAP_Enable): + str = "Enable"; + break; + default: + str = "Unknown"; + } + + return str; +} + +const char* NacpProcess::getDataLossConfirmationStr(nn::hac::nacp::DataLossConfirmation var) const +{ + const char* str = nullptr; + + switch(var) + { + case (nn::hac::nacp::DLOSS_None): + str = "None"; + break; + case (nn::hac::nacp::DLOSS_Required): + str = "Required"; + break; + default: + str = "Unknown"; + } + + return str; +} + +const char* NacpProcess::getPlayLogPolicyStr(nn::hac::nacp::PlayLogPolicy var) const +{ + const char* str = nullptr; + + switch(var) + { + case (nn::hac::nacp::PLP_All): + str = "All"; + break; + case (nn::hac::nacp::PLP_LogOnly): + str = "LogOnly"; + break; + case (nn::hac::nacp::PLP_None): + str = "None"; + break; + default: + str = "Unknown"; + } + + return str; +} + +const char* NacpProcess::getOrganisationStr(nn::hac::nacp::Organisation var) const +{ + const char* str = nullptr; + + switch(var) + { + case (nn::hac::nacp::ORGN_CERO): + str = "CERO"; + break; + case (nn::hac::nacp::ORGN_GRACGCRB): + str = "GRACGCRB"; + break; + case (nn::hac::nacp::ORGN_GSRMR): + str = "GSRMR"; + break; + case (nn::hac::nacp::ORGN_ESRB): + str = "ESRB"; + break; + case (nn::hac::nacp::ORGN_ClassInd): + str = "ClassInd"; + break; + case (nn::hac::nacp::ORGN_USK): + str = "USK"; + break; + case (nn::hac::nacp::ORGN_PEGI): + str = "PEGI"; + break; + case (nn::hac::nacp::ORGN_PEGIPortugal): + str = "PEGIPortugal"; + break; + case (nn::hac::nacp::ORGN_PEGIBBFC): + str = "PEGIBBFC"; + break; + case (nn::hac::nacp::ORGN_Russian): + str = "Russian"; + break; + case (nn::hac::nacp::ORGN_ACB): + str = "ACB"; + break; + case (nn::hac::nacp::ORGN_OFLC): + str = "OFLC"; + break; + default: + str = "Unknown"; + } + + return str; +} + +const char* NacpProcess::getLogoTypeStr(nn::hac::nacp::LogoType var) const +{ + const char* str = nullptr; + + switch(var) + { + case (nn::hac::nacp::LOGO_LicensedByNintendo): + str = "LicensedByNintendo"; + break; + case (nn::hac::nacp::LOGO_DistributedByNintendo): + str = "DistributedByNintendo"; + break; + case (nn::hac::nacp::LOGO_Nintendo): + str = "Nintendo"; + break; + default: + str = "Unknown"; + } + + return str; +} + +const char* NacpProcess::getLogoHandlingStr(nn::hac::nacp::LogoHandling var) const +{ + const char* str = nullptr; + + switch(var) + { + case (nn::hac::nacp::LHND_Auto): + str = "Auto"; + break; + case (nn::hac::nacp::LHND_None): + str = "None"; + break; + default: + str = "Unknown"; + } + + return str; +} + +const char* NacpProcess::getRuntimeAocInstallModeStr(nn::hac::nacp::RuntimeAocInstallMode var) const +{ + const char* str = nullptr; + + switch(var) + { + case (nn::hac::nacp::RTAOC_Deny): + str = "Deny"; + break; + case (nn::hac::nacp::RTAOC_AllowAppend): + str = "AllowAppend"; + break; + default: + str = "Unknown"; + } + + return str; +} + +const char* NacpProcess::getCrashReportModeStr(nn::hac::nacp::CrashReportMode var) const +{ + const char* str = nullptr; + + switch(var) + { + case (nn::hac::nacp::CREP_Deny): + str = "Deny"; + break; + case (nn::hac::nacp::CREP_Allow): + str = "Allow"; + break; + default: + str = "Unknown"; + } + + return str; +} + +const char* NacpProcess::getHdcpStr(nn::hac::nacp::Hdcp var) const +{ + const char* str = nullptr; + + switch(var) + { + case (nn::hac::nacp::HDCP_None): + str = "None"; + break; + case (nn::hac::nacp::HDCP_Required): + str = "Required"; + break; + default: + str = "Unknown"; + } + + return str; +} + +const char* NacpProcess::getPlayLogQueryCapabilityStr(nn::hac::nacp::PlayLogQueryCapability var) const +{ + const char* str = nullptr; + + switch(var) + { + case (nn::hac::nacp::PLQC_None): + str = "None"; + break; + case (nn::hac::nacp::PLQC_Whitelist): + str = "Whitelist"; + break; + case (nn::hac::nacp::PLQC_All): + str = "All"; + break; + default: + str = "Unknown"; + } + + return str; +} + +const char* NacpProcess::getRepairFlagStr(nn::hac::nacp::RepairFlag var) const +{ + const char* str = nullptr; + + switch(var) + { + case (nn::hac::nacp::REPF_None): + str = "None"; + break; + case (nn::hac::nacp::REPF_SuppressGameCardAccess): + str = "SuppressGameCardAccess"; + break; + default: + str = "Unknown"; + } + + return str; +} + +const char* NacpProcess::getRequiredNetworkServiceLicenseOnLaunchValueStr(nn::hac::nacp::RequiredNetworkServiceLicenseOnLaunchValue var) const +{ + const char* str = nullptr; + + switch (var) + { + case (nn::hac::nacp::REQNETLIC_None): + str = "None"; + break; + case (nn::hac::nacp::REQNETLIC_Common): + str = "Common"; + break; + default: + str = "Unknown"; + } + + return str; +} + +std::string NacpProcess::getSaveDataSizeStr(int64_t size) const +{ + static const int64_t kKiloByte = 1024; + static const int64_t kMegaByte = 1024 * 1024; + + std::stringstream sstr; + + + if (size < kKiloByte) + { + sstr << size << " B"; + } + else if (size < kMegaByte) + { + sstr << (size/kKiloByte) << " KB"; + } + else + { + sstr << (size/kMegaByte) << " MB"; + } + + return sstr.str(); } \ No newline at end of file diff --git a/programs/nstool/source/NacpProcess.h b/src/NacpProcess.h similarity index 97% rename from programs/nstool/source/NacpProcess.h rename to src/NacpProcess.h index a39ae2b..aaeba21 100644 --- a/programs/nstool/source/NacpProcess.h +++ b/src/NacpProcess.h @@ -1,55 +1,55 @@ -#pragma once -#include -#include -#include -#include -#include - -#include "common.h" - -class NacpProcess -{ -public: - NacpProcess(); - - void process(); - - void setInputFile(const fnd::SharedPtr& file); - void setCliOutputMode(CliOutputMode type); - void setVerifyMode(bool verify); - - const nn::hac::ApplicationControlProperty& getApplicationControlProperty() const; - -private: - const std::string kModuleName = "NacpProcess"; - - fnd::SharedPtr mFile; - CliOutputMode mCliOutputMode; - bool mVerify; - - nn::hac::ApplicationControlProperty mNacp; - - void importNacp(); - void displayNacp(); - const char* getLanguageStr(nn::hac::nacp::Language var) const; - const char* getStartupUserAccountStr(nn::hac::nacp::StartupUserAccount var) const; - const char* getUserAccountSwitchLockValueStr(nn::hac::nacp::UserAccountSwitchLockValue var) const; - const char* getTouchScreenUsageModeStr(nn::hac::nacp::TouchScreenUsageMode var) const; - const char* getAocRegistrationTypeStr(nn::hac::nacp::AocRegistrationType var) const; - const char* getAttributeFlagStr(nn::hac::nacp::AttributeFlag var) const; - const char* getParentalControlFlagStr(nn::hac::nacp::ParentalControlFlag var) const; - const char* getScreenshotModeStr(nn::hac::nacp::ScreenshotMode var) const; - const char* getVideoCaptureModeStr(nn::hac::nacp::VideoCaptureMode var) const; - const char* getDataLossConfirmationStr(nn::hac::nacp::DataLossConfirmation var) const; - const char* getPlayLogPolicyStr(nn::hac::nacp::PlayLogPolicy var) const; - const char* getOrganisationStr(nn::hac::nacp::Organisation var) const; - const char* getLogoTypeStr(nn::hac::nacp::LogoType var) const; - const char* getLogoHandlingStr(nn::hac::nacp::LogoHandling var) const; - const char* getRuntimeAocInstallModeStr(nn::hac::nacp::RuntimeAocInstallMode var) const; - const char* getCrashReportModeStr(nn::hac::nacp::CrashReportMode var) const; - const char* getHdcpStr(nn::hac::nacp::Hdcp var) const; - const char* getPlayLogQueryCapabilityStr(nn::hac::nacp::PlayLogQueryCapability var) const; - const char* getRepairFlagStr(nn::hac::nacp::RepairFlag var) const; - const char* getRequiredNetworkServiceLicenseOnLaunchValueStr(nn::hac::nacp::RequiredNetworkServiceLicenseOnLaunchValue var) const; - std::string getSaveDataSizeStr(int64_t size) const; +#pragma once +#include +#include +#include +#include +#include + +#include "common.h" + +class NacpProcess +{ +public: + NacpProcess(); + + void process(); + + void setInputFile(const fnd::SharedPtr& file); + void setCliOutputMode(CliOutputMode type); + void setVerifyMode(bool verify); + + const nn::hac::ApplicationControlProperty& getApplicationControlProperty() const; + +private: + const std::string kModuleName = "NacpProcess"; + + fnd::SharedPtr mFile; + CliOutputMode mCliOutputMode; + bool mVerify; + + nn::hac::ApplicationControlProperty mNacp; + + void importNacp(); + void displayNacp(); + const char* getLanguageStr(nn::hac::nacp::Language var) const; + const char* getStartupUserAccountStr(nn::hac::nacp::StartupUserAccount var) const; + const char* getUserAccountSwitchLockValueStr(nn::hac::nacp::UserAccountSwitchLockValue var) const; + const char* getTouchScreenUsageModeStr(nn::hac::nacp::TouchScreenUsageMode var) const; + const char* getAocRegistrationTypeStr(nn::hac::nacp::AocRegistrationType var) const; + const char* getAttributeFlagStr(nn::hac::nacp::AttributeFlag var) const; + const char* getParentalControlFlagStr(nn::hac::nacp::ParentalControlFlag var) const; + const char* getScreenshotModeStr(nn::hac::nacp::ScreenshotMode var) const; + const char* getVideoCaptureModeStr(nn::hac::nacp::VideoCaptureMode var) const; + const char* getDataLossConfirmationStr(nn::hac::nacp::DataLossConfirmation var) const; + const char* getPlayLogPolicyStr(nn::hac::nacp::PlayLogPolicy var) const; + const char* getOrganisationStr(nn::hac::nacp::Organisation var) const; + const char* getLogoTypeStr(nn::hac::nacp::LogoType var) const; + const char* getLogoHandlingStr(nn::hac::nacp::LogoHandling var) const; + const char* getRuntimeAocInstallModeStr(nn::hac::nacp::RuntimeAocInstallMode var) const; + const char* getCrashReportModeStr(nn::hac::nacp::CrashReportMode var) const; + const char* getHdcpStr(nn::hac::nacp::Hdcp var) const; + const char* getPlayLogQueryCapabilityStr(nn::hac::nacp::PlayLogQueryCapability var) const; + const char* getRepairFlagStr(nn::hac::nacp::RepairFlag var) const; + const char* getRequiredNetworkServiceLicenseOnLaunchValueStr(nn::hac::nacp::RequiredNetworkServiceLicenseOnLaunchValue var) const; + std::string getSaveDataSizeStr(int64_t size) const; }; \ No newline at end of file diff --git a/programs/nstool/source/NcaProcess.cpp b/src/NcaProcess.cpp similarity index 96% rename from programs/nstool/source/NcaProcess.cpp rename to src/NcaProcess.cpp index 575b96b..fcfb8db 100644 --- a/programs/nstool/source/NcaProcess.cpp +++ b/src/NcaProcess.cpp @@ -1,834 +1,834 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NcaProcess.h" -#include "PfsProcess.h" -#include "RomfsProcess.h" -#include "MetaProcess.h" - - -NcaProcess::NcaProcess() : - mFile(), - mCliOutputMode(_BIT(OUTPUT_BASIC)), - mVerify(false), - mListFs(false) -{ - for (size_t i = 0; i < nn::hac::nca::kPartitionNum; i++) - { - mPartitionPath[i].doExtract = false; - } -} - -void NcaProcess::process() -{ - // import header - importHeader(); - - // determine keys - generateNcaBodyEncryptionKeys(); - - // import/generate fs header data - generatePartitionConfiguration(); - - // validate signatures - if (mVerify) - validateNcaSignatures(); - - // display header - if (_HAS_BIT(mCliOutputMode, OUTPUT_BASIC)) - displayHeader(); - - // process partition - processPartitions(); -} - -void NcaProcess::setInputFile(const fnd::SharedPtr& file) -{ - mFile = file; -} - -void NcaProcess::setKeyCfg(const KeyConfiguration& keycfg) -{ - mKeyCfg = keycfg; -} - -void NcaProcess::setCliOutputMode(CliOutputMode type) -{ - mCliOutputMode = type; -} - -void NcaProcess::setVerifyMode(bool verify) -{ - mVerify = verify; -} - -void NcaProcess::setPartition0ExtractPath(const std::string& path) -{ - mPartitionPath[0].path = path; - mPartitionPath[0].doExtract = true; -} - -void NcaProcess::setPartition1ExtractPath(const std::string& path) -{ - mPartitionPath[1].path = path; - mPartitionPath[1].doExtract = true; -} - -void NcaProcess::setPartition2ExtractPath(const std::string& path) -{ - mPartitionPath[2].path = path; - mPartitionPath[2].doExtract = true; -} - -void NcaProcess::setPartition3ExtractPath(const std::string& path) -{ - mPartitionPath[3].path = path; - mPartitionPath[3].doExtract = true; -} - -void NcaProcess::setListFs(bool list_fs) -{ - mListFs = list_fs; -} - -void NcaProcess::importHeader() -{ - if (*mFile == nullptr) - { - throw fnd::Exception(kModuleName, "No file reader set."); - } - - // read header block - (*mFile)->read((byte_t*)&mHdrBlock, 0, sizeof(nn::hac::sContentArchiveHeaderBlock)); - - // decrypt header block - fnd::aes::sAesXts128Key header_key; - mKeyCfg.getContentArchiveHeaderKey(header_key); - nn::hac::ContentArchiveUtils::decryptContentArchiveHeader((byte_t*)&mHdrBlock, (byte_t*)&mHdrBlock, header_key); - - // generate header hash - fnd::sha::Sha256((byte_t*)&mHdrBlock.header, sizeof(nn::hac::sContentArchiveHeader), mHdrHash.bytes); - - // proccess main header - mHdr.fromBytes((byte_t*)&mHdrBlock.header, sizeof(nn::hac::sContentArchiveHeader)); -} - -void NcaProcess::generateNcaBodyEncryptionKeys() -{ - // create zeros key - fnd::aes::sAes128Key zero_aesctr_key; - memset(zero_aesctr_key.key, 0, sizeof(zero_aesctr_key)); - - // get key data from header - byte_t masterkey_rev = nn::hac::ContentArchiveUtils::getMasterKeyRevisionFromKeyGeneration(mHdr.getKeyGeneration()); - byte_t keak_index = mHdr.getKeyAreaEncryptionKeyIndex(); - - // process key area - sKeys::sKeyAreaKey kak; - fnd::aes::sAes128Key key_area_enc_key; - const fnd::aes::sAes128Key* key_area = (const fnd::aes::sAes128Key*) mHdr.getKeyArea(); - - for (size_t i = 0; i < nn::hac::nca::kKeyAreaKeyNum; i++) - { - if (key_area[i] != zero_aesctr_key) - { - kak.index = (byte_t)i; - kak.enc = key_area[i]; - // key[0-3] - if (i < 4 && mKeyCfg.getNcaKeyAreaEncryptionKey(masterkey_rev, keak_index, key_area_enc_key) == true) - { - kak.decrypted = true; - nn::hac::AesKeygen::generateKey(kak.dec.key, kak.enc.key, key_area_enc_key.key); - } - // key[KEY_AESCTR_HW] - else if (i == nn::hac::nca::KEY_AESCTR_HW && mKeyCfg.getNcaKeyAreaEncryptionKeyHw(masterkey_rev, keak_index, key_area_enc_key) == true) - { - kak.decrypted = true; - nn::hac::AesKeygen::generateKey(kak.dec.key, kak.enc.key, key_area_enc_key.key); - } - else - { - kak.decrypted = false; - } - mContentKey.kak_list.addElement(kak); - } - } - - // set flag to indicate that the keys are not available - mContentKey.aes_ctr.isSet = false; - - // if this has a rights id, the key needs to be sourced from a ticket - if (mHdr.hasRightsId() == true) - { - fnd::aes::sAes128Key tmp_key; - if (mKeyCfg.getNcaExternalContentKey(mHdr.getRightsId(), tmp_key) == true) - { - mContentKey.aes_ctr = tmp_key; - } - else if (mKeyCfg.getNcaExternalContentKey(kDummyRightsIdForUserTitleKey, tmp_key) == true) - { - fnd::aes::sAes128Key common_key; - if (mKeyCfg.getETicketCommonKey(masterkey_rev, common_key) == true) - { - nn::hac::AesKeygen::generateKey(tmp_key.key, tmp_key.key, common_key.key); - } - mContentKey.aes_ctr = tmp_key; - } - } - // otherwise decrypt key area - else - { - fnd::aes::sAes128Key kak_aes_ctr = zero_aesctr_key; - for (size_t i = 0; i < mContentKey.kak_list.size(); i++) - { - if (mContentKey.kak_list[i].index == nn::hac::nca::KEY_AESCTR && mContentKey.kak_list[i].decrypted) - { - kak_aes_ctr = mContentKey.kak_list[i].dec; - } - } - - if (kak_aes_ctr != zero_aesctr_key) - { - mContentKey.aes_ctr = kak_aes_ctr; - } - } - - // if the keys weren't generated, check if the keys were supplied by the user - if (mContentKey.aes_ctr.isSet == false) - { - if (mKeyCfg.getNcaExternalContentKey(kDummyRightsIdForUserBodyKey, mContentKey.aes_ctr.var) == true) - mContentKey.aes_ctr.isSet = true; - } - - - if (_HAS_BIT(mCliOutputMode, OUTPUT_KEY_DATA)) - { - if (mContentKey.aes_ctr.isSet) - { - std::cout << "[NCA Content Key]" << std::endl; - std::cout << " AES-CTR Key: " << fnd::SimpleTextOutput::arrayToString(mContentKey.aes_ctr.var.key, sizeof(mContentKey.aes_ctr.var), true, ":") << std::endl; - } - } - - -} - -void NcaProcess::generatePartitionConfiguration() -{ - std::stringstream error; - - for (size_t i = 0; i < mHdr.getPartitionEntryList().size(); i++) - { - // get reference to relevant structures - const nn::hac::ContentArchiveHeader::sPartitionEntry& partition = mHdr.getPartitionEntryList()[i]; - nn::hac::sNcaFsHeader& fs_header = mHdrBlock.fs_header[partition.header_index]; - - // output structure - sPartitionInfo& info = mPartitions[partition.header_index]; - - // validate header hash - fnd::sha::sSha256Hash fs_header_hash; - fnd::sha::Sha256((const byte_t*)&mHdrBlock.fs_header[partition.header_index], sizeof(nn::hac::sNcaFsHeader), fs_header_hash.bytes); - if (fs_header_hash.compare(partition.fs_header_hash) == false) - { - error.clear(); - error << "NCA FS Header [" << partition.header_index << "] Hash: FAIL \n"; - throw fnd::Exception(kModuleName, error.str()); - } - - - if (fs_header.version.get() != nn::hac::nca::kDefaultFsHeaderVersion) - { - error.clear(); - error << "NCA FS Header [" << partition.header_index << "] Version(" << fs_header.version.get() << "): UNSUPPORTED"; - throw fnd::Exception(kModuleName, error.str()); - } - - // setup AES-CTR - nn::hac::ContentArchiveUtils::getNcaPartitionAesCtr(&fs_header, info.aes_ctr.iv); - - // save partition config - info.reader = nullptr; - info.offset = partition.offset; - info.size = partition.size; - info.format_type = (nn::hac::nca::FormatType)fs_header.format_type; - info.hash_type = (nn::hac::nca::HashType)fs_header.hash_type; - info.enc_type = (nn::hac::nca::EncryptionType)fs_header.encryption_type; - if (info.hash_type == nn::hac::nca::HASH_HIERARCHICAL_SHA256) - { - // info.hash_tree_meta.importData(fs_header.hash_superblock, nn::hac::nca::kFsHeaderHashSuperblockLen, LayeredIntegrityMetadata::HASH_TYPE_SHA256); - nn::hac::HierarchicalSha256Header hdr; - fnd::List hash_layers; - fnd::LayeredIntegrityMetadata::sLayer data_layer; - fnd::List master_hash_list; - - // import raw data - hdr.fromBytes(fs_header.hash_superblock, nn::hac::nca::kFsHeaderHashSuperblockLen); - for (size_t i = 0; i < hdr.getLayerInfo().size(); i++) - { - fnd::LayeredIntegrityMetadata::sLayer layer; - layer.offset = hdr.getLayerInfo()[i].offset; - layer.size = hdr.getLayerInfo()[i].size; - layer.block_size = hdr.getHashBlockSize(); - if (i + 1 == hdr.getLayerInfo().size()) - { - data_layer = layer; - } - else - { - hash_layers.addElement(layer); - } - } - master_hash_list.addElement(hdr.getMasterHash()); - - // write data into metadata - info.layered_intergrity_metadata.setAlignHashToBlock(false); - info.layered_intergrity_metadata.setHashLayerInfo(hash_layers); - info.layered_intergrity_metadata.setDataLayerInfo(data_layer); - info.layered_intergrity_metadata.setMasterHashList(master_hash_list); - } - else if (info.hash_type == nn::hac::nca::HASH_HIERARCHICAL_INTERGRITY) - { - // info.hash_tree_meta.importData(fs_header.hash_superblock, nn::hac::nca::kFsHeaderHashSuperblockLen, LayeredIntegrityMetadata::HASH_TYPE_INTEGRITY); - nn::hac::HierarchicalIntegrityHeader hdr; - fnd::List hash_layers; - fnd::LayeredIntegrityMetadata::sLayer data_layer; - fnd::List master_hash_list; - - hdr.fromBytes(fs_header.hash_superblock, nn::hac::nca::kFsHeaderHashSuperblockLen); - for (size_t i = 0; i < hdr.getLayerInfo().size(); i++) - { - fnd::LayeredIntegrityMetadata::sLayer layer; - layer.offset = hdr.getLayerInfo()[i].offset; - layer.size = hdr.getLayerInfo()[i].size; - layer.block_size = _BIT(hdr.getLayerInfo()[i].block_size); - if (i + 1 == hdr.getLayerInfo().size()) - { - data_layer = layer; - } - else - { - hash_layers.addElement(layer); - } - } - - // write data into metadata - info.layered_intergrity_metadata.setAlignHashToBlock(true); - info.layered_intergrity_metadata.setHashLayerInfo(hash_layers); - info.layered_intergrity_metadata.setDataLayerInfo(data_layer); - info.layered_intergrity_metadata.setMasterHashList(hdr.getMasterHashList()); - } - - // create reader - try - { - // filter out unrecognised format types - switch (info.format_type) - { - case (nn::hac::nca::FORMAT_PFS0): - case (nn::hac::nca::FORMAT_ROMFS): - break; - default: - error.clear(); - error << "FormatType(" << info.format_type << "): UNKNOWN"; - throw fnd::Exception(kModuleName, error.str()); - } - - // create reader based on encryption type0 - if (info.enc_type == nn::hac::nca::CRYPT_NONE) - { - info.reader = new fnd::OffsetAdjustedIFile(mFile, info.offset, info.size); - } - else if (info.enc_type == nn::hac::nca::CRYPT_AESCTR) - { - if (mContentKey.aes_ctr.isSet == false) - throw fnd::Exception(kModuleName, "AES-CTR Key was not determined"); - info.reader = new fnd::OffsetAdjustedIFile(new fnd::AesCtrWrappedIFile(mFile, mContentKey.aes_ctr.var, info.aes_ctr), info.offset, info.size); - } - else if (info.enc_type == nn::hac::nca::CRYPT_AESXTS || info.enc_type == nn::hac::nca::CRYPT_AESCTREX) - { - error.clear(); - error << "EncryptionType(" << getEncryptionTypeStr(info.enc_type) << "): UNSUPPORTED"; - throw fnd::Exception(kModuleName, error.str()); - } - else - { - error.clear(); - error << "EncryptionType(" << info.enc_type << "): UNKNOWN"; - throw fnd::Exception(kModuleName, error.str()); - } - - // filter out unrecognised hash types, and hash based readers - if (info.hash_type == nn::hac::nca::HASH_HIERARCHICAL_SHA256 || info.hash_type == nn::hac::nca::HASH_HIERARCHICAL_INTERGRITY) - { - info.reader = new fnd::LayeredIntegrityWrappedIFile(info.reader, info.layered_intergrity_metadata); - } - else if (info.hash_type != nn::hac::nca::HASH_NONE) - { - error.clear(); - error << "HashType(" << info.hash_type << "): UNKNOWN"; - throw fnd::Exception(kModuleName, error.str()); - } - } - catch (const fnd::Exception& e) - { - info.fail_reason = std::string(e.error()); - } - } -} - -void NcaProcess::validateNcaSignatures() -{ - // validate signature[0] - fnd::rsa::sRsa2048Key sign0_key; - mKeyCfg.getContentArchiveHeader0SignKey(sign0_key); - if (fnd::rsa::pss::rsaVerify(sign0_key, fnd::sha::HASH_SHA256, mHdrHash.bytes, mHdrBlock.signature_main) != 0) - { - std::cout << "[WARNING] NCA Header Main Signature: FAIL" << std::endl; - } - - // validate signature[1] - if (mHdr.getContentType() == nn::hac::nca::TYPE_PROGRAM) - { - if (mPartitions[nn::hac::nca::PARTITION_CODE].format_type == nn::hac::nca::FORMAT_PFS0) - { - if (*mPartitions[nn::hac::nca::PARTITION_CODE].reader != nullptr) - { - PfsProcess exefs; - exefs.setInputFile(mPartitions[nn::hac::nca::PARTITION_CODE].reader); - exefs.setCliOutputMode(0); - exefs.process(); - - // open main.npdm - if (exefs.getPfsHeader().getFileList().hasElement(kNpdmExefsPath) == true) - { - const nn::hac::PartitionFsHeader::sFile& file = exefs.getPfsHeader().getFileList().getElement(kNpdmExefsPath); - - MetaProcess npdm; - npdm.setInputFile(new fnd::OffsetAdjustedIFile(mPartitions[nn::hac::nca::PARTITION_CODE].reader, file.offset, file.size)); - npdm.setCliOutputMode(0); - npdm.process(); - - if (fnd::rsa::pss::rsaVerify(npdm.getMeta().getAcid().getContentArchiveHeaderSignature2Key(), fnd::sha::HASH_SHA256, mHdrHash.bytes, mHdrBlock.signature_acid) != 0) - { - std::cout << "[WARNING] NCA Header ACID Signature: FAIL" << std::endl; - } - - } - else - { - std::cout << "[WARNING] NCA Header ACID Signature: FAIL (\"" << kNpdmExefsPath << "\" not present in ExeFs)" << std::endl; - } - } - else - { - std::cout << "[WARNING] NCA Header ACID Signature: FAIL (ExeFs unreadable)" << std::endl; - } - } - else - { - std::cout << "[WARNING] NCA Header ACID Signature: FAIL (No ExeFs partition)" << std::endl; - } - } -} - -void NcaProcess::displayHeader() -{ - std::cout << "[NCA Header]" << std::endl; - std::cout << " Format Type: " << getFormatVersionStr(mHdr.getFormatVersion()) << std::endl; - std::cout << " Dist. Type: " << getDistributionTypeStr(mHdr.getDistributionType()) << std::endl; - std::cout << " Content Type: " << getContentTypeStr(mHdr.getContentType()) << std::endl; - std::cout << " Key Generation: " << std::dec << (uint32_t)mHdr.getKeyGeneration() << std::endl; - std::cout << " Kaek Index: " << getKaekIndexStr((nn::hac::nca::KeyAreaEncryptionKeyIndex)mHdr.getKeyAreaEncryptionKeyIndex()) << " (" << std::dec << (uint32_t)mHdr.getKeyAreaEncryptionKeyIndex() << ")" << std::endl; - std::cout << " Size: 0x" << std::hex << mHdr.getContentSize() << std::endl; - std::cout << " ProgID: 0x" << std::hex << std::setw(16) << std::setfill('0') << mHdr.getProgramId() << std::endl; - std::cout << " Content Index: " << std::dec << mHdr.getContentIndex() << std::endl; -#define _SPLIT_VER(ver) std::dec << (uint32_t)((ver>>24) & 0xff) << "." << (uint32_t)((ver>>16) & 0xff) << "." << (uint32_t)((ver>>8) & 0xff) - std::cout << " SdkAddon Ver.: v" << std::dec << mHdr.getSdkAddonVersion() << " (" << _SPLIT_VER(mHdr.getSdkAddonVersion()) << ")" << std::endl; -#undef _SPLIT_VER - if (mHdr.hasRightsId()) - { - std::cout << " RightsId: " << fnd::SimpleTextOutput::arrayToString(mHdr.getRightsId(), nn::hac::nca::kRightsIdLen, true, "") << std::endl; - } - - if (mContentKey.kak_list.size() > 0 && _HAS_BIT(mCliOutputMode, OUTPUT_KEY_DATA)) - { - std::cout << " Key Area:" << std::endl; - std::cout << " <--------------------------------------------------------------------------------------------------------->" << std::endl; - std::cout << " | IDX | ENCRYPTED KEY | DECRYPTED KEY |" << std::endl; - std::cout << " |-----|-------------------------------------------------|-------------------------------------------------|" << std::endl; - for (size_t i = 0; i < mContentKey.kak_list.size(); i++) - { - std::cout << " | " << std::dec << std::setw(3) << std::setfill(' ') << (uint32_t)mContentKey.kak_list[i].index << " | "; - - std::cout << fnd::SimpleTextOutput::arrayToString(mContentKey.kak_list[i].enc.key, 16, true, ":") << " | "; - - - if (mContentKey.kak_list[i].decrypted) - std::cout << fnd::SimpleTextOutput::arrayToString(mContentKey.kak_list[i].dec.key, 16, true, ":"); - else - std::cout << " "; - - std::cout << " |" << std::endl; - } - std::cout << " <--------------------------------------------------------------------------------------------------------->" << std::endl; - } - - if (_HAS_BIT(mCliOutputMode, OUTPUT_LAYOUT)) - { - std::cout << " Partitions:" << std::endl; - for (size_t i = 0; i < mHdr.getPartitionEntryList().size(); i++) - { - uint32_t index = mHdr.getPartitionEntryList()[i].header_index; - sPartitionInfo& info = mPartitions[index]; - if (info.size == 0) continue; - - std::cout << " " << std::dec << index << ":" << std::endl; - std::cout << " Offset: 0x" << std::hex << (uint64_t)info.offset << std::endl; - std::cout << " Size: 0x" << std::hex << (uint64_t)info.size << std::endl; - std::cout << " Format Type: " << getFormatTypeStr(info.format_type) << std::endl; - std::cout << " Hash Type: " << getHashTypeStr(info.hash_type) << std::endl; - std::cout << " Enc. Type: " << getEncryptionTypeStr(info.enc_type) << std::endl; - if (info.enc_type == nn::hac::nca::CRYPT_AESCTR) - { - fnd::aes::sAesIvCtr ctr; - fnd::aes::AesIncrementCounter(info.aes_ctr.iv, info.offset>>4, ctr.iv); - std::cout << " AesCtr Counter:" << std::endl; - std::cout << " " << fnd::SimpleTextOutput::arrayToString(ctr.iv, sizeof(fnd::aes::sAesIvCtr), true, ":") << std::endl; - } - if (info.hash_type == nn::hac::nca::HASH_HIERARCHICAL_INTERGRITY) - { - fnd::LayeredIntegrityMetadata& hash_hdr = info.layered_intergrity_metadata; - std::cout << " HierarchicalIntegrity Header:" << std::endl; - for (size_t j = 0; j < hash_hdr.getHashLayerInfo().size(); j++) - { - std::cout << " Hash Layer " << std::dec << j << ":" << std::endl; - std::cout << " Offset: 0x" << std::hex << (uint64_t)hash_hdr.getHashLayerInfo()[j].offset << std::endl; - std::cout << " Size: 0x" << std::hex << (uint64_t)hash_hdr.getHashLayerInfo()[j].size << std::endl; - std::cout << " BlockSize: 0x" << std::hex << (uint32_t)hash_hdr.getHashLayerInfo()[j].block_size << std::endl; - } - - std::cout << " Data Layer:" << std::endl; - std::cout << " Offset: 0x" << std::hex << (uint64_t)hash_hdr.getDataLayer().offset << std::endl; - std::cout << " Size: 0x" << std::hex << (uint64_t)hash_hdr.getDataLayer().size << std::endl; - std::cout << " BlockSize: 0x" << std::hex << (uint32_t)hash_hdr.getDataLayer().block_size << std::endl; - for (size_t j = 0; j < hash_hdr.getMasterHashList().size(); j++) - { - std::cout << " Master Hash " << std::dec << j << ":" << std::endl; - std::cout << " " << fnd::SimpleTextOutput::arrayToString(hash_hdr.getMasterHashList()[j].bytes, 0x10, true, ":") << std::endl; - std::cout << " " << fnd::SimpleTextOutput::arrayToString(hash_hdr.getMasterHashList()[j].bytes+0x10, 0x10, true, ":") << std::endl; - } - } - else if (info.hash_type == nn::hac::nca::HASH_HIERARCHICAL_SHA256) - { - fnd::LayeredIntegrityMetadata& hash_hdr = info.layered_intergrity_metadata; - std::cout << " HierarchicalSha256 Header:" << std::endl; - std::cout << " Master Hash:" << std::endl; - std::cout << " " << fnd::SimpleTextOutput::arrayToString(hash_hdr.getMasterHashList()[0].bytes, 0x10, true, ":") << std::endl; - std::cout << " " << fnd::SimpleTextOutput::arrayToString(hash_hdr.getMasterHashList()[0].bytes+0x10, 0x10, true, ":") << std::endl; - std::cout << " HashBlockSize: 0x" << std::hex << (uint32_t)hash_hdr.getDataLayer().block_size << std::endl; - std::cout << " Hash Layer:" << std::endl; - std::cout << " Offset: 0x" << std::hex << (uint64_t)hash_hdr.getHashLayerInfo()[0].offset << std::endl; - std::cout << " Size: 0x" << std::hex << (uint64_t)hash_hdr.getHashLayerInfo()[0].size << std::endl; - std::cout << " Data Layer:" << std::endl; - std::cout << " Offset: 0x" << std::hex << (uint64_t)hash_hdr.getDataLayer().offset << std::endl; - std::cout << " Size: 0x" << std::hex << (uint64_t)hash_hdr.getDataLayer().size << std::endl; - } - } - } -} - - -void NcaProcess::processPartitions() -{ - for (size_t i = 0; i < mHdr.getPartitionEntryList().size(); i++) - { - uint32_t index = mHdr.getPartitionEntryList()[i].header_index; - struct sPartitionInfo& partition = mPartitions[index]; - - // if the reader is null, skip - if (*partition.reader == nullptr) - { - std::cout << "[WARNING] NCA Partition " << std::dec << index << " not readable."; - if (partition.fail_reason.empty() == false) - { - std::cout << " (" << partition.fail_reason << ")"; - } - std::cout << std::endl; - continue; - } - - if (partition.format_type == nn::hac::nca::FORMAT_PFS0) - { - PfsProcess pfs; - pfs.setInputFile(partition.reader); - pfs.setCliOutputMode(mCliOutputMode); - pfs.setListFs(mListFs); - if (mHdr.getContentType() == nn::hac::nca::TYPE_PROGRAM) - { - pfs.setMountPointName(std::string(getContentTypeForMountStr(mHdr.getContentType())) + ":/" + std::string(getProgramPartitionNameStr(index))); - } - else - { - pfs.setMountPointName(std::string(getContentTypeForMountStr(mHdr.getContentType())) + ":/"); - } - - if (mPartitionPath[index].doExtract) - pfs.setExtractPath(mPartitionPath[index].path); - pfs.process(); - } - else if (partition.format_type == nn::hac::nca::FORMAT_ROMFS) - { - RomfsProcess romfs; - romfs.setInputFile(partition.reader); - romfs.setCliOutputMode(mCliOutputMode); - romfs.setListFs(mListFs); - if (mHdr.getContentType() == nn::hac::nca::TYPE_PROGRAM) - { - romfs.setMountPointName(std::string(getContentTypeForMountStr(mHdr.getContentType())) + ":/" + std::string(getProgramPartitionNameStr(index))); - } - else - { - romfs.setMountPointName(std::string(getContentTypeForMountStr(mHdr.getContentType())) + ":/"); - } - - if (mPartitionPath[index].doExtract) - romfs.setExtractPath(mPartitionPath[index].path); - romfs.process(); - } - } -} - -const char* NcaProcess::getFormatVersionStr(byte_t format_ver) const -{ - const char* str = nullptr; - - switch (format_ver) - { - case (nn::hac::nca::FORMAT_NCA2): - str = "NCA2"; - break; - case (nn::hac::nca::FORMAT_NCA3): - str = "NCA3"; - break; - default: - str = "Unknown"; - break; - } - - return str; -} - -const char* NcaProcess::getDistributionTypeStr(nn::hac::nca::DistributionType dist_type) const -{ - const char* str = nullptr; - - switch (dist_type) - { - case (nn::hac::nca::DIST_DOWNLOAD): - str = "Download"; - break; - case (nn::hac::nca::DIST_GAME_CARD): - str = "Game Card"; - break; - default: - str = "Unknown"; - break; - } - - return str; -} - - -const char* NcaProcess::getContentTypeStr(nn::hac::nca::ContentType cont_type) const -{ - const char* str = nullptr; - - switch (cont_type) - { - case (nn::hac::nca::TYPE_PROGRAM): - str = "Program"; - break; - case (nn::hac::nca::TYPE_META): - str = "Meta"; - break; - case (nn::hac::nca::TYPE_CONTROL): - str = "Control"; - break; - case (nn::hac::nca::TYPE_MANUAL): - str = "Manual"; - break; - case (nn::hac::nca::TYPE_DATA): - str = "Data"; - break; - case (nn::hac::nca::TYPE_PUBLIC_DATA): - str = "PublicData"; - break; - default: - str = "Unknown"; - break; - } - - return str; -} - -const char* NcaProcess::getEncryptionTypeStr(nn::hac::nca::EncryptionType enc_type) const -{ - const char* str = nullptr; - - switch (enc_type) - { - case (nn::hac::nca::CRYPT_AUTO): - str = "Auto"; - break; - case (nn::hac::nca::CRYPT_NONE): - str = "None"; - break; - case (nn::hac::nca::CRYPT_AESXTS): - str = "AesXts"; - break; - case (nn::hac::nca::CRYPT_AESCTR): - str = "AesCtr"; - break; - case (nn::hac::nca::CRYPT_AESCTREX): - str = "AesCtrEx"; - break; - default: - str = "Unknown"; - break; - } - - return str; -} - -const char* NcaProcess::getHashTypeStr(nn::hac::nca::HashType hash_type) const -{ - const char* str = nullptr; - - switch (hash_type) - { - case (nn::hac::nca::HASH_AUTO): - str = "Auto"; - break; - case (nn::hac::nca::HASH_NONE): - str = "None"; - break; - case (nn::hac::nca::HASH_HIERARCHICAL_SHA256): - str = "HierarchicalSha256"; - break; - case (nn::hac::nca::HASH_HIERARCHICAL_INTERGRITY): - str = "HierarchicalIntegrity"; - break; - default: - str = "Unknown"; - break; - } - - return str; -} - -const char* NcaProcess::getFormatTypeStr(nn::hac::nca::FormatType format_type) const -{ - const char* str = nullptr; - - switch (format_type) - { - case (nn::hac::nca::FORMAT_ROMFS): - str = "RomFs"; - break; - case (nn::hac::nca::FORMAT_PFS0): - str = "PartitionFs"; - break; - default: - str = "Unknown"; - break; - } - - return str; -} - -const char* NcaProcess::getKaekIndexStr(nn::hac::nca::KeyAreaEncryptionKeyIndex keak_index) const -{ - const char* str = nullptr; - - switch (keak_index) - { - case (nn::hac::nca::KAEK_IDX_APPLICATION): - str = "Application"; - break; - case (nn::hac::nca::KAEK_IDX_OCEAN): - str = "Ocean"; - break; - case (nn::hac::nca::KAEK_IDX_SYSTEM): - str = "System"; - break; - default: - str = "Unknown"; - break; - } - - return str; -} - -const char* NcaProcess::getContentTypeForMountStr(nn::hac::nca::ContentType cont_type) const -{ - const char* str = nullptr; - - switch (cont_type) - { - case (nn::hac::nca::TYPE_PROGRAM): - str = "program"; - break; - case (nn::hac::nca::TYPE_META): - str = "meta"; - break; - case (nn::hac::nca::TYPE_CONTROL): - str = "control"; - break; - case (nn::hac::nca::TYPE_MANUAL): - str = "manual"; - break; - case (nn::hac::nca::TYPE_DATA): - str = "data"; - break; - case (nn::hac::nca::TYPE_PUBLIC_DATA): - str = "publicdata"; - break; - default: - str = ""; - break; - } - - return str; -} - -const char* NcaProcess::getProgramPartitionNameStr(size_t i) const -{ - const char* str = nullptr; - - switch (i) - { - case (nn::hac::nca::PARTITION_CODE): - str = "code"; - break; - case (nn::hac::nca::PARTITION_DATA): - str = "data"; - break; - case (nn::hac::nca::PARTITION_LOGO): - str = "logo"; - break; - default: - str = ""; - break; - } - - return str; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "NcaProcess.h" +#include "PfsProcess.h" +#include "RomfsProcess.h" +#include "MetaProcess.h" + + +NcaProcess::NcaProcess() : + mFile(), + mCliOutputMode(_BIT(OUTPUT_BASIC)), + mVerify(false), + mListFs(false) +{ + for (size_t i = 0; i < nn::hac::nca::kPartitionNum; i++) + { + mPartitionPath[i].doExtract = false; + } +} + +void NcaProcess::process() +{ + // import header + importHeader(); + + // determine keys + generateNcaBodyEncryptionKeys(); + + // import/generate fs header data + generatePartitionConfiguration(); + + // validate signatures + if (mVerify) + validateNcaSignatures(); + + // display header + if (_HAS_BIT(mCliOutputMode, OUTPUT_BASIC)) + displayHeader(); + + // process partition + processPartitions(); +} + +void NcaProcess::setInputFile(const fnd::SharedPtr& file) +{ + mFile = file; +} + +void NcaProcess::setKeyCfg(const KeyConfiguration& keycfg) +{ + mKeyCfg = keycfg; +} + +void NcaProcess::setCliOutputMode(CliOutputMode type) +{ + mCliOutputMode = type; +} + +void NcaProcess::setVerifyMode(bool verify) +{ + mVerify = verify; +} + +void NcaProcess::setPartition0ExtractPath(const std::string& path) +{ + mPartitionPath[0].path = path; + mPartitionPath[0].doExtract = true; +} + +void NcaProcess::setPartition1ExtractPath(const std::string& path) +{ + mPartitionPath[1].path = path; + mPartitionPath[1].doExtract = true; +} + +void NcaProcess::setPartition2ExtractPath(const std::string& path) +{ + mPartitionPath[2].path = path; + mPartitionPath[2].doExtract = true; +} + +void NcaProcess::setPartition3ExtractPath(const std::string& path) +{ + mPartitionPath[3].path = path; + mPartitionPath[3].doExtract = true; +} + +void NcaProcess::setListFs(bool list_fs) +{ + mListFs = list_fs; +} + +void NcaProcess::importHeader() +{ + if (*mFile == nullptr) + { + throw fnd::Exception(kModuleName, "No file reader set."); + } + + // read header block + (*mFile)->read((byte_t*)&mHdrBlock, 0, sizeof(nn::hac::sContentArchiveHeaderBlock)); + + // decrypt header block + fnd::aes::sAesXts128Key header_key; + mKeyCfg.getContentArchiveHeaderKey(header_key); + nn::hac::ContentArchiveUtils::decryptContentArchiveHeader((byte_t*)&mHdrBlock, (byte_t*)&mHdrBlock, header_key); + + // generate header hash + fnd::sha::Sha256((byte_t*)&mHdrBlock.header, sizeof(nn::hac::sContentArchiveHeader), mHdrHash.bytes); + + // proccess main header + mHdr.fromBytes((byte_t*)&mHdrBlock.header, sizeof(nn::hac::sContentArchiveHeader)); +} + +void NcaProcess::generateNcaBodyEncryptionKeys() +{ + // create zeros key + fnd::aes::sAes128Key zero_aesctr_key; + memset(zero_aesctr_key.key, 0, sizeof(zero_aesctr_key)); + + // get key data from header + byte_t masterkey_rev = nn::hac::ContentArchiveUtils::getMasterKeyRevisionFromKeyGeneration(mHdr.getKeyGeneration()); + byte_t keak_index = mHdr.getKeyAreaEncryptionKeyIndex(); + + // process key area + sKeys::sKeyAreaKey kak; + fnd::aes::sAes128Key key_area_enc_key; + const fnd::aes::sAes128Key* key_area = (const fnd::aes::sAes128Key*) mHdr.getKeyArea(); + + for (size_t i = 0; i < nn::hac::nca::kKeyAreaKeyNum; i++) + { + if (key_area[i] != zero_aesctr_key) + { + kak.index = (byte_t)i; + kak.enc = key_area[i]; + // key[0-3] + if (i < 4 && mKeyCfg.getNcaKeyAreaEncryptionKey(masterkey_rev, keak_index, key_area_enc_key) == true) + { + kak.decrypted = true; + nn::hac::AesKeygen::generateKey(kak.dec.key, kak.enc.key, key_area_enc_key.key); + } + // key[KEY_AESCTR_HW] + else if (i == nn::hac::nca::KEY_AESCTR_HW && mKeyCfg.getNcaKeyAreaEncryptionKeyHw(masterkey_rev, keak_index, key_area_enc_key) == true) + { + kak.decrypted = true; + nn::hac::AesKeygen::generateKey(kak.dec.key, kak.enc.key, key_area_enc_key.key); + } + else + { + kak.decrypted = false; + } + mContentKey.kak_list.addElement(kak); + } + } + + // set flag to indicate that the keys are not available + mContentKey.aes_ctr.isSet = false; + + // if this has a rights id, the key needs to be sourced from a ticket + if (mHdr.hasRightsId() == true) + { + fnd::aes::sAes128Key tmp_key; + if (mKeyCfg.getNcaExternalContentKey(mHdr.getRightsId(), tmp_key) == true) + { + mContentKey.aes_ctr = tmp_key; + } + else if (mKeyCfg.getNcaExternalContentKey(kDummyRightsIdForUserTitleKey, tmp_key) == true) + { + fnd::aes::sAes128Key common_key; + if (mKeyCfg.getETicketCommonKey(masterkey_rev, common_key) == true) + { + nn::hac::AesKeygen::generateKey(tmp_key.key, tmp_key.key, common_key.key); + } + mContentKey.aes_ctr = tmp_key; + } + } + // otherwise decrypt key area + else + { + fnd::aes::sAes128Key kak_aes_ctr = zero_aesctr_key; + for (size_t i = 0; i < mContentKey.kak_list.size(); i++) + { + if (mContentKey.kak_list[i].index == nn::hac::nca::KEY_AESCTR && mContentKey.kak_list[i].decrypted) + { + kak_aes_ctr = mContentKey.kak_list[i].dec; + } + } + + if (kak_aes_ctr != zero_aesctr_key) + { + mContentKey.aes_ctr = kak_aes_ctr; + } + } + + // if the keys weren't generated, check if the keys were supplied by the user + if (mContentKey.aes_ctr.isSet == false) + { + if (mKeyCfg.getNcaExternalContentKey(kDummyRightsIdForUserBodyKey, mContentKey.aes_ctr.var) == true) + mContentKey.aes_ctr.isSet = true; + } + + + if (_HAS_BIT(mCliOutputMode, OUTPUT_KEY_DATA)) + { + if (mContentKey.aes_ctr.isSet) + { + std::cout << "[NCA Content Key]" << std::endl; + std::cout << " AES-CTR Key: " << fnd::SimpleTextOutput::arrayToString(mContentKey.aes_ctr.var.key, sizeof(mContentKey.aes_ctr.var), true, ":") << std::endl; + } + } + + +} + +void NcaProcess::generatePartitionConfiguration() +{ + std::stringstream error; + + for (size_t i = 0; i < mHdr.getPartitionEntryList().size(); i++) + { + // get reference to relevant structures + const nn::hac::ContentArchiveHeader::sPartitionEntry& partition = mHdr.getPartitionEntryList()[i]; + nn::hac::sNcaFsHeader& fs_header = mHdrBlock.fs_header[partition.header_index]; + + // output structure + sPartitionInfo& info = mPartitions[partition.header_index]; + + // validate header hash + fnd::sha::sSha256Hash fs_header_hash; + fnd::sha::Sha256((const byte_t*)&mHdrBlock.fs_header[partition.header_index], sizeof(nn::hac::sNcaFsHeader), fs_header_hash.bytes); + if (fs_header_hash.compare(partition.fs_header_hash) == false) + { + error.clear(); + error << "NCA FS Header [" << partition.header_index << "] Hash: FAIL \n"; + throw fnd::Exception(kModuleName, error.str()); + } + + + if (fs_header.version.get() != nn::hac::nca::kDefaultFsHeaderVersion) + { + error.clear(); + error << "NCA FS Header [" << partition.header_index << "] Version(" << fs_header.version.get() << "): UNSUPPORTED"; + throw fnd::Exception(kModuleName, error.str()); + } + + // setup AES-CTR + nn::hac::ContentArchiveUtils::getNcaPartitionAesCtr(&fs_header, info.aes_ctr.iv); + + // save partition config + info.reader = nullptr; + info.offset = partition.offset; + info.size = partition.size; + info.format_type = (nn::hac::nca::FormatType)fs_header.format_type; + info.hash_type = (nn::hac::nca::HashType)fs_header.hash_type; + info.enc_type = (nn::hac::nca::EncryptionType)fs_header.encryption_type; + if (info.hash_type == nn::hac::nca::HASH_HIERARCHICAL_SHA256) + { + // info.hash_tree_meta.importData(fs_header.hash_superblock, nn::hac::nca::kFsHeaderHashSuperblockLen, LayeredIntegrityMetadata::HASH_TYPE_SHA256); + nn::hac::HierarchicalSha256Header hdr; + fnd::List hash_layers; + fnd::LayeredIntegrityMetadata::sLayer data_layer; + fnd::List master_hash_list; + + // import raw data + hdr.fromBytes(fs_header.hash_superblock, nn::hac::nca::kFsHeaderHashSuperblockLen); + for (size_t i = 0; i < hdr.getLayerInfo().size(); i++) + { + fnd::LayeredIntegrityMetadata::sLayer layer; + layer.offset = hdr.getLayerInfo()[i].offset; + layer.size = hdr.getLayerInfo()[i].size; + layer.block_size = hdr.getHashBlockSize(); + if (i + 1 == hdr.getLayerInfo().size()) + { + data_layer = layer; + } + else + { + hash_layers.addElement(layer); + } + } + master_hash_list.addElement(hdr.getMasterHash()); + + // write data into metadata + info.layered_intergrity_metadata.setAlignHashToBlock(false); + info.layered_intergrity_metadata.setHashLayerInfo(hash_layers); + info.layered_intergrity_metadata.setDataLayerInfo(data_layer); + info.layered_intergrity_metadata.setMasterHashList(master_hash_list); + } + else if (info.hash_type == nn::hac::nca::HASH_HIERARCHICAL_INTERGRITY) + { + // info.hash_tree_meta.importData(fs_header.hash_superblock, nn::hac::nca::kFsHeaderHashSuperblockLen, LayeredIntegrityMetadata::HASH_TYPE_INTEGRITY); + nn::hac::HierarchicalIntegrityHeader hdr; + fnd::List hash_layers; + fnd::LayeredIntegrityMetadata::sLayer data_layer; + fnd::List master_hash_list; + + hdr.fromBytes(fs_header.hash_superblock, nn::hac::nca::kFsHeaderHashSuperblockLen); + for (size_t i = 0; i < hdr.getLayerInfo().size(); i++) + { + fnd::LayeredIntegrityMetadata::sLayer layer; + layer.offset = hdr.getLayerInfo()[i].offset; + layer.size = hdr.getLayerInfo()[i].size; + layer.block_size = _BIT(hdr.getLayerInfo()[i].block_size); + if (i + 1 == hdr.getLayerInfo().size()) + { + data_layer = layer; + } + else + { + hash_layers.addElement(layer); + } + } + + // write data into metadata + info.layered_intergrity_metadata.setAlignHashToBlock(true); + info.layered_intergrity_metadata.setHashLayerInfo(hash_layers); + info.layered_intergrity_metadata.setDataLayerInfo(data_layer); + info.layered_intergrity_metadata.setMasterHashList(hdr.getMasterHashList()); + } + + // create reader + try + { + // filter out unrecognised format types + switch (info.format_type) + { + case (nn::hac::nca::FORMAT_PFS0): + case (nn::hac::nca::FORMAT_ROMFS): + break; + default: + error.clear(); + error << "FormatType(" << info.format_type << "): UNKNOWN"; + throw fnd::Exception(kModuleName, error.str()); + } + + // create reader based on encryption type0 + if (info.enc_type == nn::hac::nca::CRYPT_NONE) + { + info.reader = new fnd::OffsetAdjustedIFile(mFile, info.offset, info.size); + } + else if (info.enc_type == nn::hac::nca::CRYPT_AESCTR) + { + if (mContentKey.aes_ctr.isSet == false) + throw fnd::Exception(kModuleName, "AES-CTR Key was not determined"); + info.reader = new fnd::OffsetAdjustedIFile(new fnd::AesCtrWrappedIFile(mFile, mContentKey.aes_ctr.var, info.aes_ctr), info.offset, info.size); + } + else if (info.enc_type == nn::hac::nca::CRYPT_AESXTS || info.enc_type == nn::hac::nca::CRYPT_AESCTREX) + { + error.clear(); + error << "EncryptionType(" << getEncryptionTypeStr(info.enc_type) << "): UNSUPPORTED"; + throw fnd::Exception(kModuleName, error.str()); + } + else + { + error.clear(); + error << "EncryptionType(" << info.enc_type << "): UNKNOWN"; + throw fnd::Exception(kModuleName, error.str()); + } + + // filter out unrecognised hash types, and hash based readers + if (info.hash_type == nn::hac::nca::HASH_HIERARCHICAL_SHA256 || info.hash_type == nn::hac::nca::HASH_HIERARCHICAL_INTERGRITY) + { + info.reader = new fnd::LayeredIntegrityWrappedIFile(info.reader, info.layered_intergrity_metadata); + } + else if (info.hash_type != nn::hac::nca::HASH_NONE) + { + error.clear(); + error << "HashType(" << info.hash_type << "): UNKNOWN"; + throw fnd::Exception(kModuleName, error.str()); + } + } + catch (const fnd::Exception& e) + { + info.fail_reason = std::string(e.error()); + } + } +} + +void NcaProcess::validateNcaSignatures() +{ + // validate signature[0] + fnd::rsa::sRsa2048Key sign0_key; + mKeyCfg.getContentArchiveHeader0SignKey(sign0_key); + if (fnd::rsa::pss::rsaVerify(sign0_key, fnd::sha::HASH_SHA256, mHdrHash.bytes, mHdrBlock.signature_main) != 0) + { + std::cout << "[WARNING] NCA Header Main Signature: FAIL" << std::endl; + } + + // validate signature[1] + if (mHdr.getContentType() == nn::hac::nca::TYPE_PROGRAM) + { + if (mPartitions[nn::hac::nca::PARTITION_CODE].format_type == nn::hac::nca::FORMAT_PFS0) + { + if (*mPartitions[nn::hac::nca::PARTITION_CODE].reader != nullptr) + { + PfsProcess exefs; + exefs.setInputFile(mPartitions[nn::hac::nca::PARTITION_CODE].reader); + exefs.setCliOutputMode(0); + exefs.process(); + + // open main.npdm + if (exefs.getPfsHeader().getFileList().hasElement(kNpdmExefsPath) == true) + { + const nn::hac::PartitionFsHeader::sFile& file = exefs.getPfsHeader().getFileList().getElement(kNpdmExefsPath); + + MetaProcess npdm; + npdm.setInputFile(new fnd::OffsetAdjustedIFile(mPartitions[nn::hac::nca::PARTITION_CODE].reader, file.offset, file.size)); + npdm.setCliOutputMode(0); + npdm.process(); + + if (fnd::rsa::pss::rsaVerify(npdm.getMeta().getAcid().getContentArchiveHeaderSignature2Key(), fnd::sha::HASH_SHA256, mHdrHash.bytes, mHdrBlock.signature_acid) != 0) + { + std::cout << "[WARNING] NCA Header ACID Signature: FAIL" << std::endl; + } + + } + else + { + std::cout << "[WARNING] NCA Header ACID Signature: FAIL (\"" << kNpdmExefsPath << "\" not present in ExeFs)" << std::endl; + } + } + else + { + std::cout << "[WARNING] NCA Header ACID Signature: FAIL (ExeFs unreadable)" << std::endl; + } + } + else + { + std::cout << "[WARNING] NCA Header ACID Signature: FAIL (No ExeFs partition)" << std::endl; + } + } +} + +void NcaProcess::displayHeader() +{ + std::cout << "[NCA Header]" << std::endl; + std::cout << " Format Type: " << getFormatVersionStr(mHdr.getFormatVersion()) << std::endl; + std::cout << " Dist. Type: " << getDistributionTypeStr(mHdr.getDistributionType()) << std::endl; + std::cout << " Content Type: " << getContentTypeStr(mHdr.getContentType()) << std::endl; + std::cout << " Key Generation: " << std::dec << (uint32_t)mHdr.getKeyGeneration() << std::endl; + std::cout << " Kaek Index: " << getKaekIndexStr((nn::hac::nca::KeyAreaEncryptionKeyIndex)mHdr.getKeyAreaEncryptionKeyIndex()) << " (" << std::dec << (uint32_t)mHdr.getKeyAreaEncryptionKeyIndex() << ")" << std::endl; + std::cout << " Size: 0x" << std::hex << mHdr.getContentSize() << std::endl; + std::cout << " ProgID: 0x" << std::hex << std::setw(16) << std::setfill('0') << mHdr.getProgramId() << std::endl; + std::cout << " Content Index: " << std::dec << mHdr.getContentIndex() << std::endl; +#define _SPLIT_VER(ver) std::dec << (uint32_t)((ver>>24) & 0xff) << "." << (uint32_t)((ver>>16) & 0xff) << "." << (uint32_t)((ver>>8) & 0xff) + std::cout << " SdkAddon Ver.: v" << std::dec << mHdr.getSdkAddonVersion() << " (" << _SPLIT_VER(mHdr.getSdkAddonVersion()) << ")" << std::endl; +#undef _SPLIT_VER + if (mHdr.hasRightsId()) + { + std::cout << " RightsId: " << fnd::SimpleTextOutput::arrayToString(mHdr.getRightsId(), nn::hac::nca::kRightsIdLen, true, "") << std::endl; + } + + if (mContentKey.kak_list.size() > 0 && _HAS_BIT(mCliOutputMode, OUTPUT_KEY_DATA)) + { + std::cout << " Key Area:" << std::endl; + std::cout << " <--------------------------------------------------------------------------------------------------------->" << std::endl; + std::cout << " | IDX | ENCRYPTED KEY | DECRYPTED KEY |" << std::endl; + std::cout << " |-----|-------------------------------------------------|-------------------------------------------------|" << std::endl; + for (size_t i = 0; i < mContentKey.kak_list.size(); i++) + { + std::cout << " | " << std::dec << std::setw(3) << std::setfill(' ') << (uint32_t)mContentKey.kak_list[i].index << " | "; + + std::cout << fnd::SimpleTextOutput::arrayToString(mContentKey.kak_list[i].enc.key, 16, true, ":") << " | "; + + + if (mContentKey.kak_list[i].decrypted) + std::cout << fnd::SimpleTextOutput::arrayToString(mContentKey.kak_list[i].dec.key, 16, true, ":"); + else + std::cout << " "; + + std::cout << " |" << std::endl; + } + std::cout << " <--------------------------------------------------------------------------------------------------------->" << std::endl; + } + + if (_HAS_BIT(mCliOutputMode, OUTPUT_LAYOUT)) + { + std::cout << " Partitions:" << std::endl; + for (size_t i = 0; i < mHdr.getPartitionEntryList().size(); i++) + { + uint32_t index = mHdr.getPartitionEntryList()[i].header_index; + sPartitionInfo& info = mPartitions[index]; + if (info.size == 0) continue; + + std::cout << " " << std::dec << index << ":" << std::endl; + std::cout << " Offset: 0x" << std::hex << (uint64_t)info.offset << std::endl; + std::cout << " Size: 0x" << std::hex << (uint64_t)info.size << std::endl; + std::cout << " Format Type: " << getFormatTypeStr(info.format_type) << std::endl; + std::cout << " Hash Type: " << getHashTypeStr(info.hash_type) << std::endl; + std::cout << " Enc. Type: " << getEncryptionTypeStr(info.enc_type) << std::endl; + if (info.enc_type == nn::hac::nca::CRYPT_AESCTR) + { + fnd::aes::sAesIvCtr ctr; + fnd::aes::AesIncrementCounter(info.aes_ctr.iv, info.offset>>4, ctr.iv); + std::cout << " AesCtr Counter:" << std::endl; + std::cout << " " << fnd::SimpleTextOutput::arrayToString(ctr.iv, sizeof(fnd::aes::sAesIvCtr), true, ":") << std::endl; + } + if (info.hash_type == nn::hac::nca::HASH_HIERARCHICAL_INTERGRITY) + { + fnd::LayeredIntegrityMetadata& hash_hdr = info.layered_intergrity_metadata; + std::cout << " HierarchicalIntegrity Header:" << std::endl; + for (size_t j = 0; j < hash_hdr.getHashLayerInfo().size(); j++) + { + std::cout << " Hash Layer " << std::dec << j << ":" << std::endl; + std::cout << " Offset: 0x" << std::hex << (uint64_t)hash_hdr.getHashLayerInfo()[j].offset << std::endl; + std::cout << " Size: 0x" << std::hex << (uint64_t)hash_hdr.getHashLayerInfo()[j].size << std::endl; + std::cout << " BlockSize: 0x" << std::hex << (uint32_t)hash_hdr.getHashLayerInfo()[j].block_size << std::endl; + } + + std::cout << " Data Layer:" << std::endl; + std::cout << " Offset: 0x" << std::hex << (uint64_t)hash_hdr.getDataLayer().offset << std::endl; + std::cout << " Size: 0x" << std::hex << (uint64_t)hash_hdr.getDataLayer().size << std::endl; + std::cout << " BlockSize: 0x" << std::hex << (uint32_t)hash_hdr.getDataLayer().block_size << std::endl; + for (size_t j = 0; j < hash_hdr.getMasterHashList().size(); j++) + { + std::cout << " Master Hash " << std::dec << j << ":" << std::endl; + std::cout << " " << fnd::SimpleTextOutput::arrayToString(hash_hdr.getMasterHashList()[j].bytes, 0x10, true, ":") << std::endl; + std::cout << " " << fnd::SimpleTextOutput::arrayToString(hash_hdr.getMasterHashList()[j].bytes+0x10, 0x10, true, ":") << std::endl; + } + } + else if (info.hash_type == nn::hac::nca::HASH_HIERARCHICAL_SHA256) + { + fnd::LayeredIntegrityMetadata& hash_hdr = info.layered_intergrity_metadata; + std::cout << " HierarchicalSha256 Header:" << std::endl; + std::cout << " Master Hash:" << std::endl; + std::cout << " " << fnd::SimpleTextOutput::arrayToString(hash_hdr.getMasterHashList()[0].bytes, 0x10, true, ":") << std::endl; + std::cout << " " << fnd::SimpleTextOutput::arrayToString(hash_hdr.getMasterHashList()[0].bytes+0x10, 0x10, true, ":") << std::endl; + std::cout << " HashBlockSize: 0x" << std::hex << (uint32_t)hash_hdr.getDataLayer().block_size << std::endl; + std::cout << " Hash Layer:" << std::endl; + std::cout << " Offset: 0x" << std::hex << (uint64_t)hash_hdr.getHashLayerInfo()[0].offset << std::endl; + std::cout << " Size: 0x" << std::hex << (uint64_t)hash_hdr.getHashLayerInfo()[0].size << std::endl; + std::cout << " Data Layer:" << std::endl; + std::cout << " Offset: 0x" << std::hex << (uint64_t)hash_hdr.getDataLayer().offset << std::endl; + std::cout << " Size: 0x" << std::hex << (uint64_t)hash_hdr.getDataLayer().size << std::endl; + } + } + } +} + + +void NcaProcess::processPartitions() +{ + for (size_t i = 0; i < mHdr.getPartitionEntryList().size(); i++) + { + uint32_t index = mHdr.getPartitionEntryList()[i].header_index; + struct sPartitionInfo& partition = mPartitions[index]; + + // if the reader is null, skip + if (*partition.reader == nullptr) + { + std::cout << "[WARNING] NCA Partition " << std::dec << index << " not readable."; + if (partition.fail_reason.empty() == false) + { + std::cout << " (" << partition.fail_reason << ")"; + } + std::cout << std::endl; + continue; + } + + if (partition.format_type == nn::hac::nca::FORMAT_PFS0) + { + PfsProcess pfs; + pfs.setInputFile(partition.reader); + pfs.setCliOutputMode(mCliOutputMode); + pfs.setListFs(mListFs); + if (mHdr.getContentType() == nn::hac::nca::TYPE_PROGRAM) + { + pfs.setMountPointName(std::string(getContentTypeForMountStr(mHdr.getContentType())) + ":/" + std::string(getProgramPartitionNameStr(index))); + } + else + { + pfs.setMountPointName(std::string(getContentTypeForMountStr(mHdr.getContentType())) + ":/"); + } + + if (mPartitionPath[index].doExtract) + pfs.setExtractPath(mPartitionPath[index].path); + pfs.process(); + } + else if (partition.format_type == nn::hac::nca::FORMAT_ROMFS) + { + RomfsProcess romfs; + romfs.setInputFile(partition.reader); + romfs.setCliOutputMode(mCliOutputMode); + romfs.setListFs(mListFs); + if (mHdr.getContentType() == nn::hac::nca::TYPE_PROGRAM) + { + romfs.setMountPointName(std::string(getContentTypeForMountStr(mHdr.getContentType())) + ":/" + std::string(getProgramPartitionNameStr(index))); + } + else + { + romfs.setMountPointName(std::string(getContentTypeForMountStr(mHdr.getContentType())) + ":/"); + } + + if (mPartitionPath[index].doExtract) + romfs.setExtractPath(mPartitionPath[index].path); + romfs.process(); + } + } +} + +const char* NcaProcess::getFormatVersionStr(byte_t format_ver) const +{ + const char* str = nullptr; + + switch (format_ver) + { + case (nn::hac::nca::FORMAT_NCA2): + str = "NCA2"; + break; + case (nn::hac::nca::FORMAT_NCA3): + str = "NCA3"; + break; + default: + str = "Unknown"; + break; + } + + return str; +} + +const char* NcaProcess::getDistributionTypeStr(nn::hac::nca::DistributionType dist_type) const +{ + const char* str = nullptr; + + switch (dist_type) + { + case (nn::hac::nca::DIST_DOWNLOAD): + str = "Download"; + break; + case (nn::hac::nca::DIST_GAME_CARD): + str = "Game Card"; + break; + default: + str = "Unknown"; + break; + } + + return str; +} + + +const char* NcaProcess::getContentTypeStr(nn::hac::nca::ContentType cont_type) const +{ + const char* str = nullptr; + + switch (cont_type) + { + case (nn::hac::nca::TYPE_PROGRAM): + str = "Program"; + break; + case (nn::hac::nca::TYPE_META): + str = "Meta"; + break; + case (nn::hac::nca::TYPE_CONTROL): + str = "Control"; + break; + case (nn::hac::nca::TYPE_MANUAL): + str = "Manual"; + break; + case (nn::hac::nca::TYPE_DATA): + str = "Data"; + break; + case (nn::hac::nca::TYPE_PUBLIC_DATA): + str = "PublicData"; + break; + default: + str = "Unknown"; + break; + } + + return str; +} + +const char* NcaProcess::getEncryptionTypeStr(nn::hac::nca::EncryptionType enc_type) const +{ + const char* str = nullptr; + + switch (enc_type) + { + case (nn::hac::nca::CRYPT_AUTO): + str = "Auto"; + break; + case (nn::hac::nca::CRYPT_NONE): + str = "None"; + break; + case (nn::hac::nca::CRYPT_AESXTS): + str = "AesXts"; + break; + case (nn::hac::nca::CRYPT_AESCTR): + str = "AesCtr"; + break; + case (nn::hac::nca::CRYPT_AESCTREX): + str = "AesCtrEx"; + break; + default: + str = "Unknown"; + break; + } + + return str; +} + +const char* NcaProcess::getHashTypeStr(nn::hac::nca::HashType hash_type) const +{ + const char* str = nullptr; + + switch (hash_type) + { + case (nn::hac::nca::HASH_AUTO): + str = "Auto"; + break; + case (nn::hac::nca::HASH_NONE): + str = "None"; + break; + case (nn::hac::nca::HASH_HIERARCHICAL_SHA256): + str = "HierarchicalSha256"; + break; + case (nn::hac::nca::HASH_HIERARCHICAL_INTERGRITY): + str = "HierarchicalIntegrity"; + break; + default: + str = "Unknown"; + break; + } + + return str; +} + +const char* NcaProcess::getFormatTypeStr(nn::hac::nca::FormatType format_type) const +{ + const char* str = nullptr; + + switch (format_type) + { + case (nn::hac::nca::FORMAT_ROMFS): + str = "RomFs"; + break; + case (nn::hac::nca::FORMAT_PFS0): + str = "PartitionFs"; + break; + default: + str = "Unknown"; + break; + } + + return str; +} + +const char* NcaProcess::getKaekIndexStr(nn::hac::nca::KeyAreaEncryptionKeyIndex keak_index) const +{ + const char* str = nullptr; + + switch (keak_index) + { + case (nn::hac::nca::KAEK_IDX_APPLICATION): + str = "Application"; + break; + case (nn::hac::nca::KAEK_IDX_OCEAN): + str = "Ocean"; + break; + case (nn::hac::nca::KAEK_IDX_SYSTEM): + str = "System"; + break; + default: + str = "Unknown"; + break; + } + + return str; +} + +const char* NcaProcess::getContentTypeForMountStr(nn::hac::nca::ContentType cont_type) const +{ + const char* str = nullptr; + + switch (cont_type) + { + case (nn::hac::nca::TYPE_PROGRAM): + str = "program"; + break; + case (nn::hac::nca::TYPE_META): + str = "meta"; + break; + case (nn::hac::nca::TYPE_CONTROL): + str = "control"; + break; + case (nn::hac::nca::TYPE_MANUAL): + str = "manual"; + break; + case (nn::hac::nca::TYPE_DATA): + str = "data"; + break; + case (nn::hac::nca::TYPE_PUBLIC_DATA): + str = "publicdata"; + break; + default: + str = ""; + break; + } + + return str; +} + +const char* NcaProcess::getProgramPartitionNameStr(size_t i) const +{ + const char* str = nullptr; + + switch (i) + { + case (nn::hac::nca::PARTITION_CODE): + str = "code"; + break; + case (nn::hac::nca::PARTITION_DATA): + str = "data"; + break; + case (nn::hac::nca::PARTITION_LOGO): + str = "logo"; + break; + default: + str = ""; + break; + } + + return str; } \ No newline at end of file diff --git a/programs/nstool/source/NcaProcess.h b/src/NcaProcess.h similarity index 96% rename from programs/nstool/source/NcaProcess.h rename to src/NcaProcess.h index 8716c9f..2b9ba2e 100644 --- a/programs/nstool/source/NcaProcess.h +++ b/src/NcaProcess.h @@ -1,123 +1,123 @@ -#pragma once -#include -#include -#include -#include -#include -#include -#include "KeyConfiguration.h" - - -#include "common.h" - -class NcaProcess -{ -public: - NcaProcess(); - - void process(); - - // generic - void setInputFile(const fnd::SharedPtr& file); - void setKeyCfg(const KeyConfiguration& keycfg); - void setCliOutputMode(CliOutputMode type); - void setVerifyMode(bool verify); - - // nca specfic - void setPartition0ExtractPath(const std::string& path); - void setPartition1ExtractPath(const std::string& path); - void setPartition2ExtractPath(const std::string& path); - void setPartition3ExtractPath(const std::string& path); - void setListFs(bool list_fs); - -private: - const std::string kModuleName = "NcaProcess"; - const std::string kNpdmExefsPath = "main.npdm"; - - // user options - fnd::SharedPtr mFile; - KeyConfiguration mKeyCfg; - CliOutputMode mCliOutputMode; - bool mVerify; - - struct sExtract - { - std::string path; - bool doExtract; - } mPartitionPath[nn::hac::nca::kPartitionNum]; - - bool mListFs; - - // data - nn::hac::sContentArchiveHeaderBlock mHdrBlock; - fnd::sha::sSha256Hash mHdrHash; - nn::hac::ContentArchiveHeader mHdr; - - // crypto - struct sKeys - { - struct sKeyAreaKey - { - byte_t index; - bool decrypted; - fnd::aes::sAes128Key enc; - fnd::aes::sAes128Key dec; - - void operator=(const sKeyAreaKey& other) - { - index = other.index; - decrypted = other.decrypted; - enc = other.enc; - dec = other.dec; - } - - bool operator==(const sKeyAreaKey& other) const - { - return (index == other.index) \ - && (decrypted == other.decrypted) \ - && (enc == other.enc) \ - && (dec == other.dec); - } - - bool operator!=(const sKeyAreaKey& other) const - { - return !(*this == other); - } - }; - fnd::List kak_list; - - sOptional aes_ctr; - } mContentKey; - - struct sPartitionInfo - { - fnd::SharedPtr reader; - std::string fail_reason; - size_t offset; - size_t size; - - // meta data - nn::hac::nca::FormatType format_type; - nn::hac::nca::HashType hash_type; - nn::hac::nca::EncryptionType enc_type; - fnd::LayeredIntegrityMetadata layered_intergrity_metadata; - fnd::aes::sAesIvCtr aes_ctr; - } mPartitions[nn::hac::nca::kPartitionNum]; - - void importHeader(); - void generateNcaBodyEncryptionKeys(); - void generatePartitionConfiguration(); - void validateNcaSignatures(); - void displayHeader(); - void processPartitions(); - - const char* getFormatVersionStr(byte_t format_ver) const; - const char* getDistributionTypeStr(nn::hac::nca::DistributionType dist_type) const; - const char* getContentTypeStr(nn::hac::nca::ContentType cont_type) const; - const char* getEncryptionTypeStr(nn::hac::nca::EncryptionType enc_type) const; - const char* getHashTypeStr(nn::hac::nca::HashType hash_type) const; - const char* getFormatTypeStr(nn::hac::nca::FormatType format_type) const; - const char* getKaekIndexStr(nn::hac::nca::KeyAreaEncryptionKeyIndex keak_index) const; - const char* getContentTypeForMountStr(nn::hac::nca::ContentType cont_type) const; - const char* getProgramPartitionNameStr(size_t i) const; +#pragma once +#include +#include +#include +#include +#include +#include +#include "KeyConfiguration.h" + + +#include "common.h" + +class NcaProcess +{ +public: + NcaProcess(); + + void process(); + + // generic + void setInputFile(const fnd::SharedPtr& file); + void setKeyCfg(const KeyConfiguration& keycfg); + void setCliOutputMode(CliOutputMode type); + void setVerifyMode(bool verify); + + // nca specfic + void setPartition0ExtractPath(const std::string& path); + void setPartition1ExtractPath(const std::string& path); + void setPartition2ExtractPath(const std::string& path); + void setPartition3ExtractPath(const std::string& path); + void setListFs(bool list_fs); + +private: + const std::string kModuleName = "NcaProcess"; + const std::string kNpdmExefsPath = "main.npdm"; + + // user options + fnd::SharedPtr mFile; + KeyConfiguration mKeyCfg; + CliOutputMode mCliOutputMode; + bool mVerify; + + struct sExtract + { + std::string path; + bool doExtract; + } mPartitionPath[nn::hac::nca::kPartitionNum]; + + bool mListFs; + + // data + nn::hac::sContentArchiveHeaderBlock mHdrBlock; + fnd::sha::sSha256Hash mHdrHash; + nn::hac::ContentArchiveHeader mHdr; + + // crypto + struct sKeys + { + struct sKeyAreaKey + { + byte_t index; + bool decrypted; + fnd::aes::sAes128Key enc; + fnd::aes::sAes128Key dec; + + void operator=(const sKeyAreaKey& other) + { + index = other.index; + decrypted = other.decrypted; + enc = other.enc; + dec = other.dec; + } + + bool operator==(const sKeyAreaKey& other) const + { + return (index == other.index) \ + && (decrypted == other.decrypted) \ + && (enc == other.enc) \ + && (dec == other.dec); + } + + bool operator!=(const sKeyAreaKey& other) const + { + return !(*this == other); + } + }; + fnd::List kak_list; + + sOptional aes_ctr; + } mContentKey; + + struct sPartitionInfo + { + fnd::SharedPtr reader; + std::string fail_reason; + size_t offset; + size_t size; + + // meta data + nn::hac::nca::FormatType format_type; + nn::hac::nca::HashType hash_type; + nn::hac::nca::EncryptionType enc_type; + fnd::LayeredIntegrityMetadata layered_intergrity_metadata; + fnd::aes::sAesIvCtr aes_ctr; + } mPartitions[nn::hac::nca::kPartitionNum]; + + void importHeader(); + void generateNcaBodyEncryptionKeys(); + void generatePartitionConfiguration(); + void validateNcaSignatures(); + void displayHeader(); + void processPartitions(); + + const char* getFormatVersionStr(byte_t format_ver) const; + const char* getDistributionTypeStr(nn::hac::nca::DistributionType dist_type) const; + const char* getContentTypeStr(nn::hac::nca::ContentType cont_type) const; + const char* getEncryptionTypeStr(nn::hac::nca::EncryptionType enc_type) const; + const char* getHashTypeStr(nn::hac::nca::HashType hash_type) const; + const char* getFormatTypeStr(nn::hac::nca::FormatType format_type) const; + const char* getKaekIndexStr(nn::hac::nca::KeyAreaEncryptionKeyIndex keak_index) const; + const char* getContentTypeForMountStr(nn::hac::nca::ContentType cont_type) const; + const char* getProgramPartitionNameStr(size_t i) const; }; \ No newline at end of file diff --git a/programs/nstool/source/NroProcess.cpp b/src/NroProcess.cpp similarity index 96% rename from programs/nstool/source/NroProcess.cpp rename to src/NroProcess.cpp index e6f43e5..f1da20d 100644 --- a/programs/nstool/source/NroProcess.cpp +++ b/src/NroProcess.cpp @@ -1,172 +1,172 @@ -#include -#include -#include -#include -#include -#include -#include -#include "NroProcess.h" - -NroProcess::NroProcess(): - mFile(), - mCliOutputMode(_BIT(OUTPUT_BASIC)), - mVerify(false) -{ -} - -void NroProcess::process() -{ - importHeader(); - importCodeSegments(); - - if (_HAS_BIT(mCliOutputMode, OUTPUT_BASIC)) - displayHeader(); - - processRoMeta(); - - if (mIsHomebrewNro) - mAssetProc.process(); -} - -void NroProcess::setInputFile(const fnd::SharedPtr& file) -{ - mFile = file; -} - -void NroProcess::setCliOutputMode(CliOutputMode type) -{ - mCliOutputMode = type; -} - -void NroProcess::setVerifyMode(bool verify) -{ - mVerify = verify; -} - -void NroProcess::setInstructionType(nn::hac::meta::InstructionType type) -{ - mRoMeta.setInstructionType(type); -} - -void NroProcess::setListApi(bool listApi) -{ - mRoMeta.setListApi(listApi); -} - -void NroProcess::setListSymbols(bool listSymbols) -{ - mRoMeta.setListSymbols(listSymbols); -} - -void NroProcess::setAssetListFs(bool list) -{ - mAssetProc.setListFs(list); -} - -void NroProcess::setAssetIconExtractPath(const std::string& path) -{ - mAssetProc.setIconExtractPath(path); -} - -void NroProcess::setAssetNacpExtractPath(const std::string& path) -{ - mAssetProc.setNacpExtractPath(path); -} - -void NroProcess::setAssetRomfsExtractPath(const std::string& path) -{ - mAssetProc.setRomfsExtractPath(path); -} - -const RoMetadataProcess& NroProcess::getRoMetadataProcess() const -{ - return mRoMeta; -} - -void NroProcess::importHeader() -{ - fnd::Vec scratch; - - if (*mFile == nullptr) - { - throw fnd::Exception(kModuleName, "No file reader set."); - } - - if ((*mFile)->size() < sizeof(nn::hac::sNroHeader)) - { - throw fnd::Exception(kModuleName, "Corrupt NRO: file too small"); - } - - scratch.alloc(sizeof(nn::hac::sNroHeader)); - (*mFile)->read(scratch.data(), 0, scratch.size()); - - mHdr.fromBytes(scratch.data(), scratch.size()); - - // setup homebrew extension - nn::hac::sNroHeader* raw_hdr = (nn::hac::sNroHeader*)scratch.data(); - if (((le_uint64_t*)raw_hdr->reserved_0)->get() == nn::hac::nro::kNroHomebrewStructMagic && (*mFile)->size() > mHdr.getNroSize()) - { - mIsHomebrewNro = true; - mAssetProc.setInputFile(new fnd::OffsetAdjustedIFile(mFile, mHdr.getNroSize(), (*mFile)->size() - mHdr.getNroSize())); - mAssetProc.setCliOutputMode(mCliOutputMode); - mAssetProc.setVerifyMode(mVerify); - } - else - mIsHomebrewNro = false; -} - -void NroProcess::importCodeSegments() -{ - mTextBlob.alloc(mHdr.getTextInfo().size); - (*mFile)->read(mTextBlob.data(), mHdr.getTextInfo().memory_offset, mTextBlob.size()); - mRoBlob.alloc(mHdr.getRoInfo().size); - (*mFile)->read(mRoBlob.data(), mHdr.getRoInfo().memory_offset, mRoBlob.size()); - mDataBlob.alloc(mHdr.getDataInfo().size); - (*mFile)->read(mDataBlob.data(), mHdr.getDataInfo().memory_offset, mDataBlob.size()); -} - -void NroProcess::displayHeader() -{ - std::cout << "[NRO Header]" << std::endl; - std::cout << " RoCrt: " << fnd::SimpleTextOutput::arrayToString(mHdr.getRoCrt().data, nn::hac::nro::kRoCrtSize, false, "") << std::endl; - std::cout << " ModuleId: " << fnd::SimpleTextOutput::arrayToString(mHdr.getModuleId().data, nn::hac::nro::kModuleIdSize, false, "") << std::endl; - std::cout << " NroSize: 0x" << std::hex << mHdr.getNroSize() << std::endl; - std::cout << " Program Sections:" << std::endl; - std::cout << " .text:" << std::endl; - std::cout << " Offset: 0x" << std::hex << mHdr.getTextInfo().memory_offset << std::endl; - std::cout << " Size: 0x" << std::hex << mHdr.getTextInfo().size << std::endl; - std::cout << " .ro:" << std::endl; - std::cout << " Offset: 0x" << std::hex << mHdr.getRoInfo().memory_offset << std::endl; - std::cout << " Size: 0x" << std::hex << mHdr.getRoInfo().size << std::endl; - if (_HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) - { - std::cout << " .api_info:" << std::endl; - std::cout << " Offset: 0x" << std::hex << mHdr.getRoEmbeddedInfo().memory_offset << std::endl; - std::cout << " Size: 0x" << std::hex << mHdr.getRoEmbeddedInfo().size << std::endl; - std::cout << " .dynstr:" << std::endl; - std::cout << " Offset: 0x" << std::hex << mHdr.getRoDynStrInfo().memory_offset << std::endl; - std::cout << " Size: 0x" << std::hex << mHdr.getRoDynStrInfo().size << std::endl; - std::cout << " .dynsym:" << std::endl; - std::cout << " Offset: 0x" << std::hex << mHdr.getRoDynSymInfo().memory_offset << std::endl; - std::cout << " Size: 0x" << std::hex << mHdr.getRoDynSymInfo().size << std::endl; - } - std::cout << " .data:" << std::endl; - std::cout << " Offset: 0x" << std::hex << mHdr.getDataInfo().memory_offset << std::endl; - std::cout << " Size: 0x" << std::hex << mHdr.getDataInfo().size << std::endl; - std::cout << " .bss:" << std::endl; - std::cout << " Size: 0x" << std::hex << mHdr.getBssSize() << std::endl; -} - -void NroProcess::processRoMeta() -{ - if (mRoBlob.size()) - { - // setup ro metadata - mRoMeta.setApiInfo(mHdr.getRoEmbeddedInfo().memory_offset, mHdr.getRoEmbeddedInfo().size); - mRoMeta.setDynSym(mHdr.getRoDynSymInfo().memory_offset, mHdr.getRoDynSymInfo().size); - mRoMeta.setDynStr(mHdr.getRoDynStrInfo().memory_offset, mHdr.getRoDynStrInfo().size); - mRoMeta.setRoBinary(mRoBlob); - mRoMeta.setCliOutputMode(mCliOutputMode); - mRoMeta.process(); - } +#include +#include +#include +#include +#include +#include +#include +#include "NroProcess.h" + +NroProcess::NroProcess(): + mFile(), + mCliOutputMode(_BIT(OUTPUT_BASIC)), + mVerify(false) +{ +} + +void NroProcess::process() +{ + importHeader(); + importCodeSegments(); + + if (_HAS_BIT(mCliOutputMode, OUTPUT_BASIC)) + displayHeader(); + + processRoMeta(); + + if (mIsHomebrewNro) + mAssetProc.process(); +} + +void NroProcess::setInputFile(const fnd::SharedPtr& file) +{ + mFile = file; +} + +void NroProcess::setCliOutputMode(CliOutputMode type) +{ + mCliOutputMode = type; +} + +void NroProcess::setVerifyMode(bool verify) +{ + mVerify = verify; +} + +void NroProcess::setInstructionType(nn::hac::meta::InstructionType type) +{ + mRoMeta.setInstructionType(type); +} + +void NroProcess::setListApi(bool listApi) +{ + mRoMeta.setListApi(listApi); +} + +void NroProcess::setListSymbols(bool listSymbols) +{ + mRoMeta.setListSymbols(listSymbols); +} + +void NroProcess::setAssetListFs(bool list) +{ + mAssetProc.setListFs(list); +} + +void NroProcess::setAssetIconExtractPath(const std::string& path) +{ + mAssetProc.setIconExtractPath(path); +} + +void NroProcess::setAssetNacpExtractPath(const std::string& path) +{ + mAssetProc.setNacpExtractPath(path); +} + +void NroProcess::setAssetRomfsExtractPath(const std::string& path) +{ + mAssetProc.setRomfsExtractPath(path); +} + +const RoMetadataProcess& NroProcess::getRoMetadataProcess() const +{ + return mRoMeta; +} + +void NroProcess::importHeader() +{ + fnd::Vec scratch; + + if (*mFile == nullptr) + { + throw fnd::Exception(kModuleName, "No file reader set."); + } + + if ((*mFile)->size() < sizeof(nn::hac::sNroHeader)) + { + throw fnd::Exception(kModuleName, "Corrupt NRO: file too small"); + } + + scratch.alloc(sizeof(nn::hac::sNroHeader)); + (*mFile)->read(scratch.data(), 0, scratch.size()); + + mHdr.fromBytes(scratch.data(), scratch.size()); + + // setup homebrew extension + nn::hac::sNroHeader* raw_hdr = (nn::hac::sNroHeader*)scratch.data(); + if (((le_uint64_t*)raw_hdr->reserved_0)->get() == nn::hac::nro::kNroHomebrewStructMagic && (*mFile)->size() > mHdr.getNroSize()) + { + mIsHomebrewNro = true; + mAssetProc.setInputFile(new fnd::OffsetAdjustedIFile(mFile, mHdr.getNroSize(), (*mFile)->size() - mHdr.getNroSize())); + mAssetProc.setCliOutputMode(mCliOutputMode); + mAssetProc.setVerifyMode(mVerify); + } + else + mIsHomebrewNro = false; +} + +void NroProcess::importCodeSegments() +{ + mTextBlob.alloc(mHdr.getTextInfo().size); + (*mFile)->read(mTextBlob.data(), mHdr.getTextInfo().memory_offset, mTextBlob.size()); + mRoBlob.alloc(mHdr.getRoInfo().size); + (*mFile)->read(mRoBlob.data(), mHdr.getRoInfo().memory_offset, mRoBlob.size()); + mDataBlob.alloc(mHdr.getDataInfo().size); + (*mFile)->read(mDataBlob.data(), mHdr.getDataInfo().memory_offset, mDataBlob.size()); +} + +void NroProcess::displayHeader() +{ + std::cout << "[NRO Header]" << std::endl; + std::cout << " RoCrt: " << fnd::SimpleTextOutput::arrayToString(mHdr.getRoCrt().data, nn::hac::nro::kRoCrtSize, false, "") << std::endl; + std::cout << " ModuleId: " << fnd::SimpleTextOutput::arrayToString(mHdr.getModuleId().data, nn::hac::nro::kModuleIdSize, false, "") << std::endl; + std::cout << " NroSize: 0x" << std::hex << mHdr.getNroSize() << std::endl; + std::cout << " Program Sections:" << std::endl; + std::cout << " .text:" << std::endl; + std::cout << " Offset: 0x" << std::hex << mHdr.getTextInfo().memory_offset << std::endl; + std::cout << " Size: 0x" << std::hex << mHdr.getTextInfo().size << std::endl; + std::cout << " .ro:" << std::endl; + std::cout << " Offset: 0x" << std::hex << mHdr.getRoInfo().memory_offset << std::endl; + std::cout << " Size: 0x" << std::hex << mHdr.getRoInfo().size << std::endl; + if (_HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) + { + std::cout << " .api_info:" << std::endl; + std::cout << " Offset: 0x" << std::hex << mHdr.getRoEmbeddedInfo().memory_offset << std::endl; + std::cout << " Size: 0x" << std::hex << mHdr.getRoEmbeddedInfo().size << std::endl; + std::cout << " .dynstr:" << std::endl; + std::cout << " Offset: 0x" << std::hex << mHdr.getRoDynStrInfo().memory_offset << std::endl; + std::cout << " Size: 0x" << std::hex << mHdr.getRoDynStrInfo().size << std::endl; + std::cout << " .dynsym:" << std::endl; + std::cout << " Offset: 0x" << std::hex << mHdr.getRoDynSymInfo().memory_offset << std::endl; + std::cout << " Size: 0x" << std::hex << mHdr.getRoDynSymInfo().size << std::endl; + } + std::cout << " .data:" << std::endl; + std::cout << " Offset: 0x" << std::hex << mHdr.getDataInfo().memory_offset << std::endl; + std::cout << " Size: 0x" << std::hex << mHdr.getDataInfo().size << std::endl; + std::cout << " .bss:" << std::endl; + std::cout << " Size: 0x" << std::hex << mHdr.getBssSize() << std::endl; +} + +void NroProcess::processRoMeta() +{ + if (mRoBlob.size()) + { + // setup ro metadata + mRoMeta.setApiInfo(mHdr.getRoEmbeddedInfo().memory_offset, mHdr.getRoEmbeddedInfo().size); + mRoMeta.setDynSym(mHdr.getRoDynSymInfo().memory_offset, mHdr.getRoDynSymInfo().size); + mRoMeta.setDynStr(mHdr.getRoDynStrInfo().memory_offset, mHdr.getRoDynStrInfo().size); + mRoMeta.setRoBinary(mRoBlob); + mRoMeta.setCliOutputMode(mCliOutputMode); + mRoMeta.process(); + } } \ No newline at end of file diff --git a/programs/nstool/source/NroProcess.h b/src/NroProcess.h similarity index 96% rename from programs/nstool/source/NroProcess.h rename to src/NroProcess.h index a1f67fa..b019208 100644 --- a/programs/nstool/source/NroProcess.h +++ b/src/NroProcess.h @@ -1,53 +1,53 @@ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include "AssetProcess.h" - -#include "common.h" -#include "RoMetadataProcess.h" - -class NroProcess -{ -public: - NroProcess(); - - void process(); - - void setInputFile(const fnd::SharedPtr& file); - void setCliOutputMode(CliOutputMode type); - void setVerifyMode(bool verify); - - void setInstructionType(nn::hac::meta::InstructionType type); - void setListApi(bool listApi); - void setListSymbols(bool listSymbols); - - // for homebrew NROs with Asset blobs appended - void setAssetListFs(bool list); - void setAssetIconExtractPath(const std::string& path); - void setAssetNacpExtractPath(const std::string& path); - void setAssetRomfsExtractPath(const std::string& path); - - const RoMetadataProcess& getRoMetadataProcess() const; -private: - const std::string kModuleName = "NroProcess"; - - fnd::SharedPtr mFile; - CliOutputMode mCliOutputMode; - bool mVerify; - - nn::hac::NroHeader mHdr; - fnd::Vec mTextBlob, mRoBlob, mDataBlob; - RoMetadataProcess mRoMeta; - bool mIsHomebrewNro; - AssetProcess mAssetProc; - - void importHeader(); - void importCodeSegments(); - void displayHeader(); - void processRoMeta(); +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include "AssetProcess.h" + +#include "common.h" +#include "RoMetadataProcess.h" + +class NroProcess +{ +public: + NroProcess(); + + void process(); + + void setInputFile(const fnd::SharedPtr& file); + void setCliOutputMode(CliOutputMode type); + void setVerifyMode(bool verify); + + void setInstructionType(nn::hac::meta::InstructionType type); + void setListApi(bool listApi); + void setListSymbols(bool listSymbols); + + // for homebrew NROs with Asset blobs appended + void setAssetListFs(bool list); + void setAssetIconExtractPath(const std::string& path); + void setAssetNacpExtractPath(const std::string& path); + void setAssetRomfsExtractPath(const std::string& path); + + const RoMetadataProcess& getRoMetadataProcess() const; +private: + const std::string kModuleName = "NroProcess"; + + fnd::SharedPtr mFile; + CliOutputMode mCliOutputMode; + bool mVerify; + + nn::hac::NroHeader mHdr; + fnd::Vec mTextBlob, mRoBlob, mDataBlob; + RoMetadataProcess mRoMeta; + bool mIsHomebrewNro; + AssetProcess mAssetProc; + + void importHeader(); + void importCodeSegments(); + void displayHeader(); + void processRoMeta(); }; \ No newline at end of file diff --git a/programs/nstool/source/NsoProcess.cpp b/src/NsoProcess.cpp similarity index 97% rename from programs/nstool/source/NsoProcess.cpp rename to src/NsoProcess.cpp index 3ea00ed..7db1e16 100644 --- a/programs/nstool/source/NsoProcess.cpp +++ b/src/NsoProcess.cpp @@ -1,237 +1,237 @@ -#include -#include -#include -#include -#include -#include -#include "NsoProcess.h" - -NsoProcess::NsoProcess(): - mFile(), - mCliOutputMode(_BIT(OUTPUT_BASIC)), - mVerify(false) -{ -} - -void NsoProcess::process() -{ - importHeader(); - importCodeSegments(); - if (_HAS_BIT(mCliOutputMode, OUTPUT_BASIC)) - displayNsoHeader(); - - processRoMeta(); -} - -void NsoProcess::setInputFile(const fnd::SharedPtr& file) -{ - mFile = file; -} - -void NsoProcess::setCliOutputMode(CliOutputMode type) -{ - mCliOutputMode = type; -} - -void NsoProcess::setVerifyMode(bool verify) -{ - mVerify = verify; -} - -void NsoProcess::setInstructionType(nn::hac::meta::InstructionType type) -{ - mRoMeta.setInstructionType(type); -} - -void NsoProcess::setListApi(bool listApi) -{ - mRoMeta.setListApi(listApi); -} - -void NsoProcess::setListSymbols(bool listSymbols) -{ - mRoMeta.setListSymbols(listSymbols); -} - -const RoMetadataProcess& NsoProcess::getRoMetadataProcess() const -{ - return mRoMeta; -} - -void NsoProcess::importHeader() -{ - fnd::Vec scratch; - - if (*mFile == nullptr) - { - throw fnd::Exception(kModuleName, "No file reader set."); - } - - if ((*mFile)->size() < sizeof(nn::hac::sNsoHeader)) - { - throw fnd::Exception(kModuleName, "Corrupt NSO: file too small"); - } - - scratch.alloc(sizeof(nn::hac::sNsoHeader)); - (*mFile)->read(scratch.data(), 0, scratch.size()); - - mHdr.fromBytes(scratch.data(), scratch.size()); -} - -void NsoProcess::importCodeSegments() -{ - fnd::Vec scratch; - uint32_t decompressed_len; - fnd::sha::sSha256Hash calc_hash; - - // process text segment - if (mHdr.getTextSegmentInfo().is_compressed) - { - scratch.alloc(mHdr.getTextSegmentInfo().file_layout.size); - (*mFile)->read(scratch.data(), mHdr.getTextSegmentInfo().file_layout.offset, scratch.size()); - mTextBlob.alloc(mHdr.getTextSegmentInfo().memory_layout.size); - fnd::lz4::decompressData(scratch.data(), (uint32_t)scratch.size(), mTextBlob.data(), (uint32_t)mTextBlob.size(), decompressed_len); - if (decompressed_len != mTextBlob.size()) - { - throw fnd::Exception(kModuleName, "NSO text segment failed to decompress"); - } - } - else - { - mTextBlob.alloc(mHdr.getTextSegmentInfo().file_layout.size); - (*mFile)->read(mTextBlob.data(), mHdr.getTextSegmentInfo().file_layout.offset, mTextBlob.size()); - } - if (mHdr.getTextSegmentInfo().is_hashed) - { - fnd::sha::Sha256(mTextBlob.data(), mTextBlob.size(), calc_hash.bytes); - if (calc_hash != mHdr.getTextSegmentInfo().hash) - { - throw fnd::Exception(kModuleName, "NSO text segment failed SHA256 verification"); - } - } - - // process ro segment - if (mHdr.getRoSegmentInfo().is_compressed) - { - scratch.alloc(mHdr.getRoSegmentInfo().file_layout.size); - (*mFile)->read(scratch.data(), mHdr.getRoSegmentInfo().file_layout.offset, scratch.size()); - mRoBlob.alloc(mHdr.getRoSegmentInfo().memory_layout.size); - fnd::lz4::decompressData(scratch.data(), (uint32_t)scratch.size(), mRoBlob.data(), (uint32_t)mRoBlob.size(), decompressed_len); - if (decompressed_len != mRoBlob.size()) - { - throw fnd::Exception(kModuleName, "NSO ro segment failed to decompress"); - } - } - else - { - mRoBlob.alloc(mHdr.getRoSegmentInfo().file_layout.size); - (*mFile)->read(mRoBlob.data(), mHdr.getRoSegmentInfo().file_layout.offset, mRoBlob.size()); - } - if (mHdr.getRoSegmentInfo().is_hashed) - { - fnd::sha::Sha256(mRoBlob.data(), mRoBlob.size(), calc_hash.bytes); - if (calc_hash != mHdr.getRoSegmentInfo().hash) - { - throw fnd::Exception(kModuleName, "NSO ro segment failed SHA256 verification"); - } - } - - // process data segment - if (mHdr.getDataSegmentInfo().is_compressed) - { - scratch.alloc(mHdr.getDataSegmentInfo().file_layout.size); - (*mFile)->read(scratch.data(), mHdr.getDataSegmentInfo().file_layout.offset, scratch.size()); - mDataBlob.alloc(mHdr.getDataSegmentInfo().memory_layout.size); - fnd::lz4::decompressData(scratch.data(), (uint32_t)scratch.size(), mDataBlob.data(), (uint32_t)mDataBlob.size(), decompressed_len); - if (decompressed_len != mDataBlob.size()) - { - throw fnd::Exception(kModuleName, "NSO data segment failed to decompress"); - } - } - else - { - mDataBlob.alloc(mHdr.getDataSegmentInfo().file_layout.size); - (*mFile)->read(mDataBlob.data(), mHdr.getDataSegmentInfo().file_layout.offset, mDataBlob.size()); - } - if (mHdr.getDataSegmentInfo().is_hashed) - { - fnd::sha::Sha256(mDataBlob.data(), mDataBlob.size(), calc_hash.bytes); - if (calc_hash != mHdr.getDataSegmentInfo().hash) - { - throw fnd::Exception(kModuleName, "NSO data segment failed SHA256 verification"); - } - } -} - -void NsoProcess::displayNsoHeader() -{ - std::cout << "[NSO Header]" << std::endl; - std::cout << " ModuleId: " << fnd::SimpleTextOutput::arrayToString(mHdr.getModuleId().data, nn::hac::nso::kModuleIdSize, false, "") << std::endl; - if (_HAS_BIT(mCliOutputMode, OUTPUT_LAYOUT)) - { - std::cout << " Program Segments:" << std::endl; - std::cout << " .module_name:" << std::endl; - std::cout << " FileOffset: 0x" << std::hex << mHdr.getModuleNameInfo().offset << std::endl; - std::cout << " FileSize: 0x" << std::hex << mHdr.getModuleNameInfo().size << std::endl; - std::cout << " .text:" << std::endl; - std::cout << " FileOffset: 0x" << std::hex << mHdr.getTextSegmentInfo().file_layout.offset << std::endl; - std::cout << " FileSize: 0x" << std::hex << mHdr.getTextSegmentInfo().file_layout.size << (mHdr.getTextSegmentInfo().is_compressed? " (COMPRESSED)" : "") << std::endl; - std::cout << " .ro:" << std::endl; - std::cout << " FileOffset: 0x" << std::hex << mHdr.getRoSegmentInfo().file_layout.offset << std::endl; - std::cout << " FileSize: 0x" << std::hex << mHdr.getRoSegmentInfo().file_layout.size << (mHdr.getRoSegmentInfo().is_compressed? " (COMPRESSED)" : "") << std::endl; - std::cout << " .data:" << std::endl; - std::cout << " FileOffset: 0x" << std::hex << mHdr.getDataSegmentInfo().file_layout.offset << std::endl; - std::cout << " FileSize: 0x" << std::hex << mHdr.getDataSegmentInfo().file_layout.size << (mHdr.getDataSegmentInfo().is_compressed? " (COMPRESSED)" : "") << std::endl; - } - std::cout << " Program Sections:" << std::endl; - std::cout << " .text:" << std::endl; - std::cout << " MemoryOffset: 0x" << std::hex << mHdr.getTextSegmentInfo().memory_layout.offset << std::endl; - std::cout << " MemorySize: 0x" << std::hex << mHdr.getTextSegmentInfo().memory_layout.size << std::endl; - if (mHdr.getTextSegmentInfo().is_hashed && _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) - { - std::cout << " Hash: " << fnd::SimpleTextOutput::arrayToString(mHdr.getTextSegmentInfo().hash.bytes, 32, false, "") << std::endl; - } - std::cout << " .ro:" << std::endl; - std::cout << " MemoryOffset: 0x" << std::hex << mHdr.getRoSegmentInfo().memory_layout.offset << std::endl; - std::cout << " MemorySize: 0x" << std::hex << mHdr.getRoSegmentInfo().memory_layout.size << std::endl; - if (mHdr.getRoSegmentInfo().is_hashed && _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) - { - std::cout << " Hash: " << fnd::SimpleTextOutput::arrayToString(mHdr.getRoSegmentInfo().hash.bytes, 32, false, "") << std::endl; - } - if (_HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) - { - std::cout << " .api_info:" << std::endl; - std::cout << " MemoryOffset: 0x" << std::hex << mHdr.getRoEmbeddedInfo().offset << std::endl; - std::cout << " MemorySize: 0x" << std::hex << mHdr.getRoEmbeddedInfo().size << std::endl; - std::cout << " .dynstr:" << std::endl; - std::cout << " MemoryOffset: 0x" << std::hex << mHdr.getRoDynStrInfo().offset << std::endl; - std::cout << " MemorySize: 0x" << std::hex << mHdr.getRoDynStrInfo().size << std::endl; - std::cout << " .dynsym:" << std::endl; - std::cout << " MemoryOffset: 0x" << std::hex << mHdr.getRoDynSymInfo().offset << std::endl; - std::cout << " MemorySize: 0x" << std::hex << mHdr.getRoDynSymInfo().size << std::endl; - } - - std::cout << " .data:" << std::endl; - std::cout << " MemoryOffset: 0x" << std::hex << mHdr.getDataSegmentInfo().memory_layout.offset << std::endl; - std::cout << " MemorySize: 0x" << std::hex << mHdr.getDataSegmentInfo().memory_layout.size << std::endl; - if (mHdr.getDataSegmentInfo().is_hashed && _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) - { - std::cout << " Hash: " << fnd::SimpleTextOutput::arrayToString(mHdr.getDataSegmentInfo().hash.bytes, 32, false, "") << std::endl; - } - std::cout << " .bss:" << std::endl; - std::cout << " MemorySize: 0x" << std::hex << mHdr.getBssSize() << std::endl; -} - -void NsoProcess::processRoMeta() -{ - if (mRoBlob.size()) - { - // setup ro metadata - mRoMeta.setApiInfo(mHdr.getRoEmbeddedInfo().offset, mHdr.getRoEmbeddedInfo().size); - mRoMeta.setDynSym(mHdr.getRoDynSymInfo().offset, mHdr.getRoDynSymInfo().size); - mRoMeta.setDynStr(mHdr.getRoDynStrInfo().offset, mHdr.getRoDynStrInfo().size); - mRoMeta.setRoBinary(mRoBlob); - mRoMeta.setCliOutputMode(mCliOutputMode); - mRoMeta.process(); - } +#include +#include +#include +#include +#include +#include +#include "NsoProcess.h" + +NsoProcess::NsoProcess(): + mFile(), + mCliOutputMode(_BIT(OUTPUT_BASIC)), + mVerify(false) +{ +} + +void NsoProcess::process() +{ + importHeader(); + importCodeSegments(); + if (_HAS_BIT(mCliOutputMode, OUTPUT_BASIC)) + displayNsoHeader(); + + processRoMeta(); +} + +void NsoProcess::setInputFile(const fnd::SharedPtr& file) +{ + mFile = file; +} + +void NsoProcess::setCliOutputMode(CliOutputMode type) +{ + mCliOutputMode = type; +} + +void NsoProcess::setVerifyMode(bool verify) +{ + mVerify = verify; +} + +void NsoProcess::setInstructionType(nn::hac::meta::InstructionType type) +{ + mRoMeta.setInstructionType(type); +} + +void NsoProcess::setListApi(bool listApi) +{ + mRoMeta.setListApi(listApi); +} + +void NsoProcess::setListSymbols(bool listSymbols) +{ + mRoMeta.setListSymbols(listSymbols); +} + +const RoMetadataProcess& NsoProcess::getRoMetadataProcess() const +{ + return mRoMeta; +} + +void NsoProcess::importHeader() +{ + fnd::Vec scratch; + + if (*mFile == nullptr) + { + throw fnd::Exception(kModuleName, "No file reader set."); + } + + if ((*mFile)->size() < sizeof(nn::hac::sNsoHeader)) + { + throw fnd::Exception(kModuleName, "Corrupt NSO: file too small"); + } + + scratch.alloc(sizeof(nn::hac::sNsoHeader)); + (*mFile)->read(scratch.data(), 0, scratch.size()); + + mHdr.fromBytes(scratch.data(), scratch.size()); +} + +void NsoProcess::importCodeSegments() +{ + fnd::Vec scratch; + uint32_t decompressed_len; + fnd::sha::sSha256Hash calc_hash; + + // process text segment + if (mHdr.getTextSegmentInfo().is_compressed) + { + scratch.alloc(mHdr.getTextSegmentInfo().file_layout.size); + (*mFile)->read(scratch.data(), mHdr.getTextSegmentInfo().file_layout.offset, scratch.size()); + mTextBlob.alloc(mHdr.getTextSegmentInfo().memory_layout.size); + fnd::lz4::decompressData(scratch.data(), (uint32_t)scratch.size(), mTextBlob.data(), (uint32_t)mTextBlob.size(), decompressed_len); + if (decompressed_len != mTextBlob.size()) + { + throw fnd::Exception(kModuleName, "NSO text segment failed to decompress"); + } + } + else + { + mTextBlob.alloc(mHdr.getTextSegmentInfo().file_layout.size); + (*mFile)->read(mTextBlob.data(), mHdr.getTextSegmentInfo().file_layout.offset, mTextBlob.size()); + } + if (mHdr.getTextSegmentInfo().is_hashed) + { + fnd::sha::Sha256(mTextBlob.data(), mTextBlob.size(), calc_hash.bytes); + if (calc_hash != mHdr.getTextSegmentInfo().hash) + { + throw fnd::Exception(kModuleName, "NSO text segment failed SHA256 verification"); + } + } + + // process ro segment + if (mHdr.getRoSegmentInfo().is_compressed) + { + scratch.alloc(mHdr.getRoSegmentInfo().file_layout.size); + (*mFile)->read(scratch.data(), mHdr.getRoSegmentInfo().file_layout.offset, scratch.size()); + mRoBlob.alloc(mHdr.getRoSegmentInfo().memory_layout.size); + fnd::lz4::decompressData(scratch.data(), (uint32_t)scratch.size(), mRoBlob.data(), (uint32_t)mRoBlob.size(), decompressed_len); + if (decompressed_len != mRoBlob.size()) + { + throw fnd::Exception(kModuleName, "NSO ro segment failed to decompress"); + } + } + else + { + mRoBlob.alloc(mHdr.getRoSegmentInfo().file_layout.size); + (*mFile)->read(mRoBlob.data(), mHdr.getRoSegmentInfo().file_layout.offset, mRoBlob.size()); + } + if (mHdr.getRoSegmentInfo().is_hashed) + { + fnd::sha::Sha256(mRoBlob.data(), mRoBlob.size(), calc_hash.bytes); + if (calc_hash != mHdr.getRoSegmentInfo().hash) + { + throw fnd::Exception(kModuleName, "NSO ro segment failed SHA256 verification"); + } + } + + // process data segment + if (mHdr.getDataSegmentInfo().is_compressed) + { + scratch.alloc(mHdr.getDataSegmentInfo().file_layout.size); + (*mFile)->read(scratch.data(), mHdr.getDataSegmentInfo().file_layout.offset, scratch.size()); + mDataBlob.alloc(mHdr.getDataSegmentInfo().memory_layout.size); + fnd::lz4::decompressData(scratch.data(), (uint32_t)scratch.size(), mDataBlob.data(), (uint32_t)mDataBlob.size(), decompressed_len); + if (decompressed_len != mDataBlob.size()) + { + throw fnd::Exception(kModuleName, "NSO data segment failed to decompress"); + } + } + else + { + mDataBlob.alloc(mHdr.getDataSegmentInfo().file_layout.size); + (*mFile)->read(mDataBlob.data(), mHdr.getDataSegmentInfo().file_layout.offset, mDataBlob.size()); + } + if (mHdr.getDataSegmentInfo().is_hashed) + { + fnd::sha::Sha256(mDataBlob.data(), mDataBlob.size(), calc_hash.bytes); + if (calc_hash != mHdr.getDataSegmentInfo().hash) + { + throw fnd::Exception(kModuleName, "NSO data segment failed SHA256 verification"); + } + } +} + +void NsoProcess::displayNsoHeader() +{ + std::cout << "[NSO Header]" << std::endl; + std::cout << " ModuleId: " << fnd::SimpleTextOutput::arrayToString(mHdr.getModuleId().data, nn::hac::nso::kModuleIdSize, false, "") << std::endl; + if (_HAS_BIT(mCliOutputMode, OUTPUT_LAYOUT)) + { + std::cout << " Program Segments:" << std::endl; + std::cout << " .module_name:" << std::endl; + std::cout << " FileOffset: 0x" << std::hex << mHdr.getModuleNameInfo().offset << std::endl; + std::cout << " FileSize: 0x" << std::hex << mHdr.getModuleNameInfo().size << std::endl; + std::cout << " .text:" << std::endl; + std::cout << " FileOffset: 0x" << std::hex << mHdr.getTextSegmentInfo().file_layout.offset << std::endl; + std::cout << " FileSize: 0x" << std::hex << mHdr.getTextSegmentInfo().file_layout.size << (mHdr.getTextSegmentInfo().is_compressed? " (COMPRESSED)" : "") << std::endl; + std::cout << " .ro:" << std::endl; + std::cout << " FileOffset: 0x" << std::hex << mHdr.getRoSegmentInfo().file_layout.offset << std::endl; + std::cout << " FileSize: 0x" << std::hex << mHdr.getRoSegmentInfo().file_layout.size << (mHdr.getRoSegmentInfo().is_compressed? " (COMPRESSED)" : "") << std::endl; + std::cout << " .data:" << std::endl; + std::cout << " FileOffset: 0x" << std::hex << mHdr.getDataSegmentInfo().file_layout.offset << std::endl; + std::cout << " FileSize: 0x" << std::hex << mHdr.getDataSegmentInfo().file_layout.size << (mHdr.getDataSegmentInfo().is_compressed? " (COMPRESSED)" : "") << std::endl; + } + std::cout << " Program Sections:" << std::endl; + std::cout << " .text:" << std::endl; + std::cout << " MemoryOffset: 0x" << std::hex << mHdr.getTextSegmentInfo().memory_layout.offset << std::endl; + std::cout << " MemorySize: 0x" << std::hex << mHdr.getTextSegmentInfo().memory_layout.size << std::endl; + if (mHdr.getTextSegmentInfo().is_hashed && _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) + { + std::cout << " Hash: " << fnd::SimpleTextOutput::arrayToString(mHdr.getTextSegmentInfo().hash.bytes, 32, false, "") << std::endl; + } + std::cout << " .ro:" << std::endl; + std::cout << " MemoryOffset: 0x" << std::hex << mHdr.getRoSegmentInfo().memory_layout.offset << std::endl; + std::cout << " MemorySize: 0x" << std::hex << mHdr.getRoSegmentInfo().memory_layout.size << std::endl; + if (mHdr.getRoSegmentInfo().is_hashed && _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) + { + std::cout << " Hash: " << fnd::SimpleTextOutput::arrayToString(mHdr.getRoSegmentInfo().hash.bytes, 32, false, "") << std::endl; + } + if (_HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) + { + std::cout << " .api_info:" << std::endl; + std::cout << " MemoryOffset: 0x" << std::hex << mHdr.getRoEmbeddedInfo().offset << std::endl; + std::cout << " MemorySize: 0x" << std::hex << mHdr.getRoEmbeddedInfo().size << std::endl; + std::cout << " .dynstr:" << std::endl; + std::cout << " MemoryOffset: 0x" << std::hex << mHdr.getRoDynStrInfo().offset << std::endl; + std::cout << " MemorySize: 0x" << std::hex << mHdr.getRoDynStrInfo().size << std::endl; + std::cout << " .dynsym:" << std::endl; + std::cout << " MemoryOffset: 0x" << std::hex << mHdr.getRoDynSymInfo().offset << std::endl; + std::cout << " MemorySize: 0x" << std::hex << mHdr.getRoDynSymInfo().size << std::endl; + } + + std::cout << " .data:" << std::endl; + std::cout << " MemoryOffset: 0x" << std::hex << mHdr.getDataSegmentInfo().memory_layout.offset << std::endl; + std::cout << " MemorySize: 0x" << std::hex << mHdr.getDataSegmentInfo().memory_layout.size << std::endl; + if (mHdr.getDataSegmentInfo().is_hashed && _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED)) + { + std::cout << " Hash: " << fnd::SimpleTextOutput::arrayToString(mHdr.getDataSegmentInfo().hash.bytes, 32, false, "") << std::endl; + } + std::cout << " .bss:" << std::endl; + std::cout << " MemorySize: 0x" << std::hex << mHdr.getBssSize() << std::endl; +} + +void NsoProcess::processRoMeta() +{ + if (mRoBlob.size()) + { + // setup ro metadata + mRoMeta.setApiInfo(mHdr.getRoEmbeddedInfo().offset, mHdr.getRoEmbeddedInfo().size); + mRoMeta.setDynSym(mHdr.getRoDynSymInfo().offset, mHdr.getRoDynSymInfo().size); + mRoMeta.setDynStr(mHdr.getRoDynStrInfo().offset, mHdr.getRoDynStrInfo().size); + mRoMeta.setRoBinary(mRoBlob); + mRoMeta.setCliOutputMode(mCliOutputMode); + mRoMeta.process(); + } } \ No newline at end of file diff --git a/programs/nstool/source/NsoProcess.h b/src/NsoProcess.h similarity index 95% rename from programs/nstool/source/NsoProcess.h rename to src/NsoProcess.h index 9ac4469..70b2f31 100644 --- a/programs/nstool/source/NsoProcess.h +++ b/src/NsoProcess.h @@ -1,47 +1,47 @@ -#pragma once -#include -#include -#include -#include -#include -#include -#include - -#include "common.h" -#include "RoMetadataProcess.h" - -class NsoProcess -{ -public: - NsoProcess(); - - void process(); - - void setInputFile(const fnd::SharedPtr& file); - void setCliOutputMode(CliOutputMode type); - void setVerifyMode(bool verify); - - void setInstructionType(nn::hac::meta::InstructionType type); - void setListApi(bool listApi); - void setListSymbols(bool listSymbols); - - const RoMetadataProcess& getRoMetadataProcess() const; -private: - const std::string kModuleName = "NsoProcess"; - - fnd::SharedPtr mFile; - CliOutputMode mCliOutputMode; - bool mVerify; - nn::hac::meta::InstructionType mInstructionType; - bool mListApi; - bool mListSymbols; - - nn::hac::NsoHeader mHdr; - fnd::Vec mTextBlob, mRoBlob, mDataBlob; - RoMetadataProcess mRoMeta; - - void importHeader(); - void importCodeSegments(); - void displayNsoHeader(); - void processRoMeta(); +#pragma once +#include +#include +#include +#include +#include +#include +#include + +#include "common.h" +#include "RoMetadataProcess.h" + +class NsoProcess +{ +public: + NsoProcess(); + + void process(); + + void setInputFile(const fnd::SharedPtr& file); + void setCliOutputMode(CliOutputMode type); + void setVerifyMode(bool verify); + + void setInstructionType(nn::hac::meta::InstructionType type); + void setListApi(bool listApi); + void setListSymbols(bool listSymbols); + + const RoMetadataProcess& getRoMetadataProcess() const; +private: + const std::string kModuleName = "NsoProcess"; + + fnd::SharedPtr mFile; + CliOutputMode mCliOutputMode; + bool mVerify; + nn::hac::meta::InstructionType mInstructionType; + bool mListApi; + bool mListSymbols; + + nn::hac::NsoHeader mHdr; + fnd::Vec mTextBlob, mRoBlob, mDataBlob; + RoMetadataProcess mRoMeta; + + void importHeader(); + void importCodeSegments(); + void displayNsoHeader(); + void processRoMeta(); }; \ No newline at end of file diff --git a/programs/nstool/source/PfsProcess.cpp b/src/PfsProcess.cpp similarity index 100% rename from programs/nstool/source/PfsProcess.cpp rename to src/PfsProcess.cpp diff --git a/programs/nstool/source/PfsProcess.h b/src/PfsProcess.h similarity index 100% rename from programs/nstool/source/PfsProcess.h rename to src/PfsProcess.h diff --git a/programs/nstool/source/PkiCertProcess.cpp b/src/PkiCertProcess.cpp similarity index 100% rename from programs/nstool/source/PkiCertProcess.cpp rename to src/PkiCertProcess.cpp diff --git a/programs/nstool/source/PkiCertProcess.h b/src/PkiCertProcess.h similarity index 100% rename from programs/nstool/source/PkiCertProcess.h rename to src/PkiCertProcess.h diff --git a/programs/nstool/source/PkiValidator.cpp b/src/PkiValidator.cpp similarity index 100% rename from programs/nstool/source/PkiValidator.cpp rename to src/PkiValidator.cpp diff --git a/programs/nstool/source/PkiValidator.h b/src/PkiValidator.h similarity index 100% rename from programs/nstool/source/PkiValidator.h rename to src/PkiValidator.h diff --git a/programs/nstool/source/RoMetadataProcess.cpp b/src/RoMetadataProcess.cpp similarity index 95% rename from programs/nstool/source/RoMetadataProcess.cpp rename to src/RoMetadataProcess.cpp index 48bcd6f..3025fbf 100644 --- a/programs/nstool/source/RoMetadataProcess.cpp +++ b/src/RoMetadataProcess.cpp @@ -1,283 +1,283 @@ -#include -#include -#include -#include - -#include "RoMetadataProcess.h" - -RoMetadataProcess::RoMetadataProcess() : - mCliOutputMode(_BIT(OUTPUT_BASIC)), - mInstructionType(nn::hac::meta::INSTR_64BIT), - mListApi(false), - mListSymbols(false), - mApiInfo(), - mDynSym(), - mDynStr(), - mRoBlob(), - mSdkVerApiList(), - mPublicApiList(), - mDebugApiList(), - mPrivateApiList(), - mSymbolList() -{ - -} - -void RoMetadataProcess::process() -{ - importApiList(); - - if (_HAS_BIT(mCliOutputMode, OUTPUT_BASIC)) - displayRoMetaData(); -} - -void RoMetadataProcess::setRoBinary(const fnd::Vec& bin) -{ - mRoBlob = bin; -} - -void RoMetadataProcess::setApiInfo(size_t offset, size_t size) -{ - mApiInfo.offset = offset; - mApiInfo.size = size; -} -void RoMetadataProcess::setDynSym(size_t offset, size_t size) -{ - mDynSym.offset = offset; - mDynSym.size = size; -} -void RoMetadataProcess::setDynStr(size_t offset, size_t size) -{ - mDynStr.offset = offset; - mDynStr.size = size; -} - -void RoMetadataProcess::setCliOutputMode(CliOutputMode type) -{ - mCliOutputMode = type; -} - -void RoMetadataProcess::setInstructionType(nn::hac::meta::InstructionType type) -{ - mInstructionType = type; -} - -void RoMetadataProcess::setListApi(bool listApi) -{ - mListApi = listApi; -} - -void RoMetadataProcess::setListSymbols(bool listSymbols) -{ - mListSymbols = listSymbols; -} - -const std::vector& RoMetadataProcess::getSdkVerApiList() const -{ - return mSdkVerApiList; -} - -const std::vector& RoMetadataProcess::getPublicApiList() const -{ - return mPublicApiList; -} - -const std::vector& RoMetadataProcess::getDebugApiList() const -{ - return mDebugApiList; -} - -const std::vector& RoMetadataProcess::getPrivateApiList() const -{ - return mPrivateApiList; -} - -const fnd::List& RoMetadataProcess::getSymbolList() const -{ - return mSymbolList.getSymbolList(); -} - -void RoMetadataProcess::importApiList() -{ - if (mRoBlob.size() == 0) - { - throw fnd::Exception(kModuleName, "No ro binary set."); - } - - if (mApiInfo.size > 0) - { - std::stringstream list_stream(std::string((char*)mRoBlob.data() + mApiInfo.offset, mApiInfo.size)); - std::string api_str; - - while(std::getline(list_stream, api_str, (char)0x00)) - { - SdkApiString api(api_str); - - if (api.getApiType() == SdkApiString::API_SDK_VERSION) - mSdkVerApiList.push_back(api); - else if (api.getApiType() == SdkApiString::API_MIDDLEWARE) - mPublicApiList.push_back(api); - else if (api.getApiType() == SdkApiString::API_DEBUG) - mDebugApiList.push_back(api); - else if (api.getApiType() == SdkApiString::API_PRIVATE) - mPrivateApiList.push_back(api); - } - } - - if (mDynSym.size > 0) - { - mSymbolList.parseData(mRoBlob.data() + mDynSym.offset, mDynSym.size, mRoBlob.data() + mDynStr.offset, mDynStr.size, mInstructionType == nn::hac::meta::INSTR_64BIT); - } -} - -void RoMetadataProcess::displayRoMetaData() -{ - size_t api_num = mSdkVerApiList.size() + mPublicApiList.size() + mDebugApiList.size() + mPrivateApiList.size(); - - if (api_num > 0 && (mListApi || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED))) - { - std::cout << "[SDK API List]" << std::endl; - if (mSdkVerApiList.size() > 0) - { - std::cout << " Sdk Revision: " << mSdkVerApiList[0].getModuleName() << std::endl; - } - if (mPublicApiList.size() > 0) - { - std::cout << " Public APIs:" << std::endl; - for (size_t i = 0; i < mPublicApiList.size(); i++) - { - std::cout << " " << mPublicApiList[i].getModuleName() << " (vender: " << mPublicApiList[i].getVenderName() << ")" << std::endl; - } - } - if (mDebugApiList.size() > 0) - { - std::cout << " Debug APIs:" << std::endl; - for (size_t i = 0; i < mDebugApiList.size(); i++) - { - std::cout << " " << mDebugApiList[i].getModuleName() << " (vender: " << mDebugApiList[i].getVenderName() << ")" << std::endl; - } - } - if (mPrivateApiList.size() > 0) - { - std::cout << " Private APIs:" << std::endl; - for (size_t i = 0; i < mPrivateApiList.size(); i++) - { - std::cout << " " << mPrivateApiList[i].getModuleName() << " (vender: " << mPrivateApiList[i].getVenderName() << ")" << std::endl; - } - } - } - if (mSymbolList.getSymbolList().size() > 0 && (mListSymbols || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED))) - { - std::cout << "[Symbol List]" << std::endl; - for (size_t i = 0; i < mSymbolList.getSymbolList().size(); i++) - { - const ElfSymbolParser::sElfSymbol& symbol = mSymbolList.getSymbolList()[i]; - std::cout << " " << symbol.name << " [SHN=" << getSectionIndexStr(symbol.shn_index) << " (" << std::hex << std::setw(4) << std::setfill('0') << symbol.shn_index << ")][STT=" << getSymbolTypeStr(symbol.symbol_type) << "][STB=" << getSymbolBindingStr(symbol.symbol_binding) << "]" << std::endl; - } - } -} - -const char* RoMetadataProcess::getSectionIndexStr(uint16_t shn_index) const -{ - const char* str; - switch (shn_index) - { - case (fnd::elf::SHN_UNDEF): - str = "UNDEF"; - break; - case (fnd::elf::SHN_LOPROC): - str = "LOPROC"; - break; - case (fnd::elf::SHN_HIPROC): - str = "HIPROC"; - break; - case (fnd::elf::SHN_LOOS): - str = "LOOS"; - break; - case (fnd::elf::SHN_HIOS): - str = "HIOS"; - break; - case (fnd::elf::SHN_ABS): - str = "ABS"; - break; - case (fnd::elf::SHN_COMMON): - str = "COMMON"; - break; - default: - str = "UNKNOWN"; - break; - } - return str; -} - -const char* RoMetadataProcess::getSymbolTypeStr(byte_t symbol_type) const -{ - const char* str; - switch (symbol_type) - { - case (fnd::elf::STT_NOTYPE): - str = "NOTYPE"; - break; - case (fnd::elf::STT_OBJECT): - str = "OBJECT"; - break; - case (fnd::elf::STT_FUNC): - str = "FUNC"; - break; - case (fnd::elf::STT_SECTION): - str = "SECTION"; - break; - case (fnd::elf::STT_FILE): - str = "FILE"; - break; - case (fnd::elf::STT_LOOS): - str = "LOOS"; - break; - case (fnd::elf::STT_HIOS): - str = "HIOS"; - break; - case (fnd::elf::STT_LOPROC): - str = "LOPROC"; - break; - case (fnd::elf::STT_HIPROC): - str = "HIPROC"; - break; - default: - str = "UNKNOWN"; - break; - } - return str; -} - -const char* RoMetadataProcess::getSymbolBindingStr(byte_t symbol_binding) const -{ - const char* str; - switch (symbol_binding) - { - case (fnd::elf::STB_LOCAL): - str = "LOCAL"; - break; - case (fnd::elf::STB_GLOBAL): - str = "GLOBAL"; - break; - case (fnd::elf::STB_WEAK): - str = "WEAK"; - break; - case (fnd::elf::STB_LOOS): - str = "LOOS"; - break; - case (fnd::elf::STB_HIOS): - str = "HIOS"; - break; - case (fnd::elf::STB_LOPROC): - str = "LOPROC"; - break; - case (fnd::elf::STB_HIPROC): - str = "HIPROC"; - break; - default: - str = "UNKNOWN"; - break; - } - return str; +#include +#include +#include +#include + +#include "RoMetadataProcess.h" + +RoMetadataProcess::RoMetadataProcess() : + mCliOutputMode(_BIT(OUTPUT_BASIC)), + mInstructionType(nn::hac::meta::INSTR_64BIT), + mListApi(false), + mListSymbols(false), + mApiInfo(), + mDynSym(), + mDynStr(), + mRoBlob(), + mSdkVerApiList(), + mPublicApiList(), + mDebugApiList(), + mPrivateApiList(), + mSymbolList() +{ + +} + +void RoMetadataProcess::process() +{ + importApiList(); + + if (_HAS_BIT(mCliOutputMode, OUTPUT_BASIC)) + displayRoMetaData(); +} + +void RoMetadataProcess::setRoBinary(const fnd::Vec& bin) +{ + mRoBlob = bin; +} + +void RoMetadataProcess::setApiInfo(size_t offset, size_t size) +{ + mApiInfo.offset = offset; + mApiInfo.size = size; +} +void RoMetadataProcess::setDynSym(size_t offset, size_t size) +{ + mDynSym.offset = offset; + mDynSym.size = size; +} +void RoMetadataProcess::setDynStr(size_t offset, size_t size) +{ + mDynStr.offset = offset; + mDynStr.size = size; +} + +void RoMetadataProcess::setCliOutputMode(CliOutputMode type) +{ + mCliOutputMode = type; +} + +void RoMetadataProcess::setInstructionType(nn::hac::meta::InstructionType type) +{ + mInstructionType = type; +} + +void RoMetadataProcess::setListApi(bool listApi) +{ + mListApi = listApi; +} + +void RoMetadataProcess::setListSymbols(bool listSymbols) +{ + mListSymbols = listSymbols; +} + +const std::vector& RoMetadataProcess::getSdkVerApiList() const +{ + return mSdkVerApiList; +} + +const std::vector& RoMetadataProcess::getPublicApiList() const +{ + return mPublicApiList; +} + +const std::vector& RoMetadataProcess::getDebugApiList() const +{ + return mDebugApiList; +} + +const std::vector& RoMetadataProcess::getPrivateApiList() const +{ + return mPrivateApiList; +} + +const fnd::List& RoMetadataProcess::getSymbolList() const +{ + return mSymbolList.getSymbolList(); +} + +void RoMetadataProcess::importApiList() +{ + if (mRoBlob.size() == 0) + { + throw fnd::Exception(kModuleName, "No ro binary set."); + } + + if (mApiInfo.size > 0) + { + std::stringstream list_stream(std::string((char*)mRoBlob.data() + mApiInfo.offset, mApiInfo.size)); + std::string api_str; + + while(std::getline(list_stream, api_str, (char)0x00)) + { + SdkApiString api(api_str); + + if (api.getApiType() == SdkApiString::API_SDK_VERSION) + mSdkVerApiList.push_back(api); + else if (api.getApiType() == SdkApiString::API_MIDDLEWARE) + mPublicApiList.push_back(api); + else if (api.getApiType() == SdkApiString::API_DEBUG) + mDebugApiList.push_back(api); + else if (api.getApiType() == SdkApiString::API_PRIVATE) + mPrivateApiList.push_back(api); + } + } + + if (mDynSym.size > 0) + { + mSymbolList.parseData(mRoBlob.data() + mDynSym.offset, mDynSym.size, mRoBlob.data() + mDynStr.offset, mDynStr.size, mInstructionType == nn::hac::meta::INSTR_64BIT); + } +} + +void RoMetadataProcess::displayRoMetaData() +{ + size_t api_num = mSdkVerApiList.size() + mPublicApiList.size() + mDebugApiList.size() + mPrivateApiList.size(); + + if (api_num > 0 && (mListApi || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED))) + { + std::cout << "[SDK API List]" << std::endl; + if (mSdkVerApiList.size() > 0) + { + std::cout << " Sdk Revision: " << mSdkVerApiList[0].getModuleName() << std::endl; + } + if (mPublicApiList.size() > 0) + { + std::cout << " Public APIs:" << std::endl; + for (size_t i = 0; i < mPublicApiList.size(); i++) + { + std::cout << " " << mPublicApiList[i].getModuleName() << " (vender: " << mPublicApiList[i].getVenderName() << ")" << std::endl; + } + } + if (mDebugApiList.size() > 0) + { + std::cout << " Debug APIs:" << std::endl; + for (size_t i = 0; i < mDebugApiList.size(); i++) + { + std::cout << " " << mDebugApiList[i].getModuleName() << " (vender: " << mDebugApiList[i].getVenderName() << ")" << std::endl; + } + } + if (mPrivateApiList.size() > 0) + { + std::cout << " Private APIs:" << std::endl; + for (size_t i = 0; i < mPrivateApiList.size(); i++) + { + std::cout << " " << mPrivateApiList[i].getModuleName() << " (vender: " << mPrivateApiList[i].getVenderName() << ")" << std::endl; + } + } + } + if (mSymbolList.getSymbolList().size() > 0 && (mListSymbols || _HAS_BIT(mCliOutputMode, OUTPUT_EXTENDED))) + { + std::cout << "[Symbol List]" << std::endl; + for (size_t i = 0; i < mSymbolList.getSymbolList().size(); i++) + { + const ElfSymbolParser::sElfSymbol& symbol = mSymbolList.getSymbolList()[i]; + std::cout << " " << symbol.name << " [SHN=" << getSectionIndexStr(symbol.shn_index) << " (" << std::hex << std::setw(4) << std::setfill('0') << symbol.shn_index << ")][STT=" << getSymbolTypeStr(symbol.symbol_type) << "][STB=" << getSymbolBindingStr(symbol.symbol_binding) << "]" << std::endl; + } + } +} + +const char* RoMetadataProcess::getSectionIndexStr(uint16_t shn_index) const +{ + const char* str; + switch (shn_index) + { + case (fnd::elf::SHN_UNDEF): + str = "UNDEF"; + break; + case (fnd::elf::SHN_LOPROC): + str = "LOPROC"; + break; + case (fnd::elf::SHN_HIPROC): + str = "HIPROC"; + break; + case (fnd::elf::SHN_LOOS): + str = "LOOS"; + break; + case (fnd::elf::SHN_HIOS): + str = "HIOS"; + break; + case (fnd::elf::SHN_ABS): + str = "ABS"; + break; + case (fnd::elf::SHN_COMMON): + str = "COMMON"; + break; + default: + str = "UNKNOWN"; + break; + } + return str; +} + +const char* RoMetadataProcess::getSymbolTypeStr(byte_t symbol_type) const +{ + const char* str; + switch (symbol_type) + { + case (fnd::elf::STT_NOTYPE): + str = "NOTYPE"; + break; + case (fnd::elf::STT_OBJECT): + str = "OBJECT"; + break; + case (fnd::elf::STT_FUNC): + str = "FUNC"; + break; + case (fnd::elf::STT_SECTION): + str = "SECTION"; + break; + case (fnd::elf::STT_FILE): + str = "FILE"; + break; + case (fnd::elf::STT_LOOS): + str = "LOOS"; + break; + case (fnd::elf::STT_HIOS): + str = "HIOS"; + break; + case (fnd::elf::STT_LOPROC): + str = "LOPROC"; + break; + case (fnd::elf::STT_HIPROC): + str = "HIPROC"; + break; + default: + str = "UNKNOWN"; + break; + } + return str; +} + +const char* RoMetadataProcess::getSymbolBindingStr(byte_t symbol_binding) const +{ + const char* str; + switch (symbol_binding) + { + case (fnd::elf::STB_LOCAL): + str = "LOCAL"; + break; + case (fnd::elf::STB_GLOBAL): + str = "GLOBAL"; + break; + case (fnd::elf::STB_WEAK): + str = "WEAK"; + break; + case (fnd::elf::STB_LOOS): + str = "LOOS"; + break; + case (fnd::elf::STB_HIOS): + str = "HIOS"; + break; + case (fnd::elf::STB_LOPROC): + str = "LOPROC"; + break; + case (fnd::elf::STB_HIPROC): + str = "HIPROC"; + break; + default: + str = "UNKNOWN"; + break; + } + return str; } \ No newline at end of file diff --git a/programs/nstool/source/RoMetadataProcess.h b/src/RoMetadataProcess.h similarity index 96% rename from programs/nstool/source/RoMetadataProcess.h rename to src/RoMetadataProcess.h index 71dab32..bef72d9 100644 --- a/programs/nstool/source/RoMetadataProcess.h +++ b/src/RoMetadataProcess.h @@ -1,68 +1,68 @@ -#pragma once -#include -#include -#include -#include - -#include - -#include "common.h" -#include "SdkApiString.h" -#include "ElfSymbolParser.h" - -class RoMetadataProcess -{ -public: - RoMetadataProcess(); - - void process(); - - void setRoBinary(const fnd::Vec& bin); - void setApiInfo(size_t offset, size_t size); - void setDynSym(size_t offset, size_t size); - void setDynStr(size_t offset, size_t size); - - void setCliOutputMode(CliOutputMode type); - - void setInstructionType(nn::hac::meta::InstructionType type); - void setListApi(bool listApi); - void setListSymbols(bool listSymbols); - - const std::vector& getSdkVerApiList() const; - const std::vector& getPublicApiList() const; - const std::vector& getDebugApiList() const; - const std::vector& getPrivateApiList() const; - const fnd::List& getSymbolList() const; -private: - const std::string kModuleName = "RoMetadataProcess"; - - CliOutputMode mCliOutputMode; - nn::hac::meta::InstructionType mInstructionType; - bool mListApi; - bool mListSymbols; - - struct sLayout - { - sLayout() : offset(0), size(0) {} - size_t offset; - size_t size; - }; - - sLayout mApiInfo; - sLayout mDynSym; - sLayout mDynStr; - fnd::Vec mRoBlob; - std::vector mSdkVerApiList; - std::vector mPublicApiList; - std::vector mDebugApiList; - std::vector mPrivateApiList; - - ElfSymbolParser mSymbolList; - - void importApiList(); - void displayRoMetaData(); - - const char* getSectionIndexStr(uint16_t shn_index) const; - const char* getSymbolTypeStr(byte_t symbol_type) const; - const char* getSymbolBindingStr(byte_t symbol_binding) const; +#pragma once +#include +#include +#include +#include + +#include + +#include "common.h" +#include "SdkApiString.h" +#include "ElfSymbolParser.h" + +class RoMetadataProcess +{ +public: + RoMetadataProcess(); + + void process(); + + void setRoBinary(const fnd::Vec& bin); + void setApiInfo(size_t offset, size_t size); + void setDynSym(size_t offset, size_t size); + void setDynStr(size_t offset, size_t size); + + void setCliOutputMode(CliOutputMode type); + + void setInstructionType(nn::hac::meta::InstructionType type); + void setListApi(bool listApi); + void setListSymbols(bool listSymbols); + + const std::vector& getSdkVerApiList() const; + const std::vector& getPublicApiList() const; + const std::vector& getDebugApiList() const; + const std::vector& getPrivateApiList() const; + const fnd::List& getSymbolList() const; +private: + const std::string kModuleName = "RoMetadataProcess"; + + CliOutputMode mCliOutputMode; + nn::hac::meta::InstructionType mInstructionType; + bool mListApi; + bool mListSymbols; + + struct sLayout + { + sLayout() : offset(0), size(0) {} + size_t offset; + size_t size; + }; + + sLayout mApiInfo; + sLayout mDynSym; + sLayout mDynStr; + fnd::Vec mRoBlob; + std::vector mSdkVerApiList; + std::vector mPublicApiList; + std::vector mDebugApiList; + std::vector mPrivateApiList; + + ElfSymbolParser mSymbolList; + + void importApiList(); + void displayRoMetaData(); + + const char* getSectionIndexStr(uint16_t shn_index) const; + const char* getSymbolTypeStr(byte_t symbol_type) const; + const char* getSymbolBindingStr(byte_t symbol_binding) const; }; \ No newline at end of file diff --git a/programs/nstool/source/RomfsProcess.cpp b/src/RomfsProcess.cpp similarity index 100% rename from programs/nstool/source/RomfsProcess.cpp rename to src/RomfsProcess.cpp diff --git a/programs/nstool/source/RomfsProcess.h b/src/RomfsProcess.h similarity index 95% rename from programs/nstool/source/RomfsProcess.h rename to src/RomfsProcess.h index 14e2e52..d6cee47 100644 --- a/programs/nstool/source/RomfsProcess.h +++ b/src/RomfsProcess.h @@ -1,134 +1,134 @@ -#pragma once -#include -#include -#include -#include -#include -#include -#include - -#include "common.h" - -class RomfsProcess -{ -public: - struct sDirectory; - struct sFile; - - struct sDirectory - { - std::string name; - fnd::List dir_list; - fnd::List file_list; - - void operator=(const sDirectory& other) - { - name = other.name; - dir_list = other.dir_list; - file_list = other.file_list; - } - - bool operator==(const sDirectory& other) const - { - return (name == other.name) \ - && (dir_list == other.dir_list) \ - && (file_list == other.file_list); - } - - bool operator!=(const sDirectory& other) const - { - return !operator==(other); - } - - bool operator==(const std::string& other) const - { - return (name == other); - } - }; - - struct sFile - { - std::string name; - uint64_t offset; - uint64_t size; - - void operator=(const sFile& other) - { - name = other.name; - offset = other.offset; - size = other.size; - } - - bool operator==(const sFile& other) const - { - return (name == other.name) \ - && (offset == other.offset) \ - && (size == other.size); - } - - bool operator!=(const sFile& other) const - { - return !operator==(other); - } - - bool operator==(const std::string& other) const - { - return (name == other); - } - }; - - RomfsProcess(); - - void process(); - - // generic - void setInputFile(const fnd::SharedPtr& file); - void setCliOutputMode(CliOutputMode type); - void setVerifyMode(bool verify); - - // romfs specific - void setMountPointName(const std::string& mount_name); - void setExtractPath(const std::string& path); - void setListFs(bool list_fs); - - const sDirectory& getRootDir() const; -private: - const std::string kModuleName = "RomfsProcess"; - static const size_t kCacheSize = 0x10000; - - fnd::SharedPtr mFile; - CliOutputMode mCliOutputMode; - bool mVerify; - - std::string mExtractPath; - bool mExtract; - std::string mMountName; - bool mListFs; - - fnd::Vec mCache; - - size_t mDirNum; - size_t mFileNum; - nn::hac::sRomfsHeader mHdr; - fnd::Vec mDirNodes; - fnd::Vec mFileNodes; - sDirectory mRootDir; - - inline nn::hac::sRomfsDirEntry* get_dir_node(uint32_t offset) { return (nn::hac::sRomfsDirEntry*)(mDirNodes.data() + offset); } - inline nn::hac::sRomfsFileEntry* get_file_node(uint32_t offset) { return (nn::hac::sRomfsFileEntry*)(mFileNodes.data() + offset); } - - - void printTab(size_t tab) const; - void displayFile(const sFile& file, size_t tab) const; - void displayDir(const sDirectory& dir, size_t tab) const; - - void displayHeader(); - void displayFs(); - - void extractDir(const std::string& path, const sDirectory& dir); - void extractFs(); - - bool validateHeaderLayout(const nn::hac::sRomfsHeader* hdr) const; - void importDirectory(uint32_t dir_offset, sDirectory& dir); - void resolveRomfs(); +#pragma once +#include +#include +#include +#include +#include +#include +#include + +#include "common.h" + +class RomfsProcess +{ +public: + struct sDirectory; + struct sFile; + + struct sDirectory + { + std::string name; + fnd::List dir_list; + fnd::List file_list; + + void operator=(const sDirectory& other) + { + name = other.name; + dir_list = other.dir_list; + file_list = other.file_list; + } + + bool operator==(const sDirectory& other) const + { + return (name == other.name) \ + && (dir_list == other.dir_list) \ + && (file_list == other.file_list); + } + + bool operator!=(const sDirectory& other) const + { + return !operator==(other); + } + + bool operator==(const std::string& other) const + { + return (name == other); + } + }; + + struct sFile + { + std::string name; + uint64_t offset; + uint64_t size; + + void operator=(const sFile& other) + { + name = other.name; + offset = other.offset; + size = other.size; + } + + bool operator==(const sFile& other) const + { + return (name == other.name) \ + && (offset == other.offset) \ + && (size == other.size); + } + + bool operator!=(const sFile& other) const + { + return !operator==(other); + } + + bool operator==(const std::string& other) const + { + return (name == other); + } + }; + + RomfsProcess(); + + void process(); + + // generic + void setInputFile(const fnd::SharedPtr& file); + void setCliOutputMode(CliOutputMode type); + void setVerifyMode(bool verify); + + // romfs specific + void setMountPointName(const std::string& mount_name); + void setExtractPath(const std::string& path); + void setListFs(bool list_fs); + + const sDirectory& getRootDir() const; +private: + const std::string kModuleName = "RomfsProcess"; + static const size_t kCacheSize = 0x10000; + + fnd::SharedPtr mFile; + CliOutputMode mCliOutputMode; + bool mVerify; + + std::string mExtractPath; + bool mExtract; + std::string mMountName; + bool mListFs; + + fnd::Vec mCache; + + size_t mDirNum; + size_t mFileNum; + nn::hac::sRomfsHeader mHdr; + fnd::Vec mDirNodes; + fnd::Vec mFileNodes; + sDirectory mRootDir; + + inline nn::hac::sRomfsDirEntry* get_dir_node(uint32_t offset) { return (nn::hac::sRomfsDirEntry*)(mDirNodes.data() + offset); } + inline nn::hac::sRomfsFileEntry* get_file_node(uint32_t offset) { return (nn::hac::sRomfsFileEntry*)(mFileNodes.data() + offset); } + + + void printTab(size_t tab) const; + void displayFile(const sFile& file, size_t tab) const; + void displayDir(const sDirectory& dir, size_t tab) const; + + void displayHeader(); + void displayFs(); + + void extractDir(const std::string& path, const sDirectory& dir); + void extractFs(); + + bool validateHeaderLayout(const nn::hac::sRomfsHeader* hdr) const; + void importDirectory(uint32_t dir_offset, sDirectory& dir); + void resolveRomfs(); }; \ No newline at end of file diff --git a/programs/nstool/source/SdkApiString.cpp b/src/SdkApiString.cpp similarity index 100% rename from programs/nstool/source/SdkApiString.cpp rename to src/SdkApiString.cpp diff --git a/programs/nstool/source/SdkApiString.h b/src/SdkApiString.h similarity index 100% rename from programs/nstool/source/SdkApiString.h rename to src/SdkApiString.h diff --git a/programs/nstool/source/UserSettings.cpp b/src/UserSettings.cpp similarity index 96% rename from programs/nstool/source/UserSettings.cpp rename to src/UserSettings.cpp index 9ac9dc2..46ce86e 100644 --- a/programs/nstool/source/UserSettings.cpp +++ b/src/UserSettings.cpp @@ -1,1060 +1,1060 @@ -#include "UserSettings.h" -#include "version.h" -#include "PkiValidator.h" -#include "KeyConfiguration.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -UserSettings::UserSettings() -{} - -void UserSettings::parseCmdArgs(const std::vector& arg_list) -{ - sCmdArgs args; - populateCmdArgs(arg_list, args); - populateKeyset(args); - populateUserSettings(args); - if (_HAS_BIT(mOutputMode, OUTPUT_KEY_DATA)) - dumpKeyConfig(); -} - -void UserSettings::showHelp() -{ - printf("%s v%d.%d.%d (C) %s\n", APP_NAME, VER_MAJOR, VER_MINOR, VER_PATCH, AUTHORS); - printf("Built: %s %s\n\n", __TIME__, __DATE__); - - printf("Usage: %s [options... ] \n", BIN_NAME); - printf("\n General Options:\n"); - printf(" -d, --dev Use devkit keyset.\n"); - printf(" -k, --keyset Specify keyset file.\n"); - printf(" -t, --type Specify input file type. [xci, pfs, romfs, nca, meta, cnmt, nso, nro, ini, kip, nacp, aset, cert, tik]\n"); - printf(" -y, --verify Verify file.\n"); - printf("\n Output Options:\n"); - printf(" --showkeys Show keys generated.\n"); - printf(" --showlayout Show layout metadata.\n"); - printf(" -v, --verbose Verbose output.\n"); - printf("\n XCI (GameCard Image)\n"); - printf(" %s [--listfs] [--update --logo --normal --secure ] <.xci file>\n", BIN_NAME); - printf(" --listfs Print file system in embedded partitions.\n"); - printf(" --update Extract \"update\" partition to directory.\n"); - printf(" --logo Extract \"logo\" partition to directory.\n"); - printf(" --normal Extract \"normal\" partition to directory.\n"); - printf(" --secure Extract \"secure\" partition to directory.\n"); - printf("\n PFS0/HFS0 (PartitionFs), RomFs, NSP (Ninendo Submission Package)\n"); - printf(" %s [--listfs] [--fsdir ] \n", BIN_NAME); - printf(" --listfs Print file system.\n"); - printf(" --fsdir Extract file system to directory.\n"); - printf("\n NCA (Nintendo Content Archive)\n"); - printf(" %s [--listfs] [--bodykey --titlekey ] [--part0 ...] <.nca file>\n", BIN_NAME); - printf(" --listfs Print file system in embedded partitions.\n"); - printf(" --titlekey Specify title key extracted from ticket.\n"); - printf(" --bodykey Specify body encryption key.\n"); - printf(" --tik Specify ticket to source title key.\n"); - printf(" --cert Specify certificate chain to verify ticket.\n"); - printf(" --part0 Extract \"partition 0\" to directory.\n"); - printf(" --part1 Extract \"partition 1\" to directory.\n"); - printf(" --part2 Extract \"partition 2\" to directory.\n"); - printf(" --part3 Extract \"partition 3\" to directory.\n"); - printf("\n NSO (Nintendo Software Object), NRO (Nintendo Relocatable Object)\n"); - printf(" %s [--listapi --listsym] [--insttype ] \n", BIN_NAME); - printf(" --listapi Print SDK API List.\n"); - printf(" --listsym Print Code Symbols.\n"); - printf(" --insttype Specify instruction type [64bit|32bit] (64bit is assumed).\n"); - printf("\n INI (Initial Process List Blob)\n"); - printf(" %s [--kipdir ] \n", BIN_NAME); - printf(" --kipdir Extract embedded KIPs to directory.\n"); - printf("\n ASET (Homebrew Asset Blob)\n"); - printf(" %s [--listfs] [--icon --nacp --fsdir ] \n", BIN_NAME); - printf(" --listfs Print filesystem in embedded RomFS partition.\n"); - printf(" --icon Extract icon partition to file.\n"); - printf(" --nacp Extract NACP partition to file.\n"); - printf(" --fsdir Extract RomFS partition to directory.\n"); - -} - -const std::string UserSettings::getInputPath() const -{ - return mInputPath; -} - -const KeyConfiguration& UserSettings::getKeyCfg() const -{ - return mKeyCfg; -} - -FileType UserSettings::getFileType() const -{ - return mFileType; -} - -bool UserSettings::isVerifyFile() const -{ - return mVerifyFile; -} - -CliOutputMode UserSettings::getCliOutputMode() const -{ - return mOutputMode; -} - -bool UserSettings::isListFs() const -{ - return mListFs; -} - -bool UserSettings::isListApi() const -{ - return mListApi; -} -bool UserSettings::isListSymbols() const -{ - return mListSymbols; -} - -nn::hac::meta::InstructionType UserSettings::getInstType() const -{ - return mInstructionType; -} - -const sOptional& UserSettings::getXciUpdatePath() const -{ - return mXciUpdatePath; -} - -const sOptional& UserSettings::getXciLogoPath() const -{ - return mXciLogoPath; -} - -const sOptional& UserSettings::getXciNormalPath() const -{ - return mXciNormalPath; -} - -const sOptional& UserSettings::getXciSecurePath() const -{ - return mXciSecurePath; -} - -const sOptional& UserSettings::getFsPath() const -{ - return mFsPath; -} - -const sOptional& UserSettings::getNcaPart0Path() const -{ - return mNcaPart0Path; -} - -const sOptional& UserSettings::getNcaPart1Path() const -{ - return mNcaPart1Path; -} - -const sOptional& UserSettings::getNcaPart2Path() const -{ - return mNcaPart2Path; -} - -const sOptional& UserSettings::getNcaPart3Path() const -{ - return mNcaPart3Path; -} - -const sOptional& UserSettings::getKipExtractPath() const -{ - return mKipExtractPath; -} - -const sOptional& UserSettings::getAssetIconPath() const -{ - return mAssetIconPath; -} - -const sOptional& UserSettings::getAssetNacpPath() const -{ - return mAssetNacpPath; -} - -const fnd::List>& UserSettings::getCertificateChain() const -{ - return mCertChain; -} - -void UserSettings::populateCmdArgs(const std::vector& arg_list, sCmdArgs& cmd_args) -{ - // show help text - if (arg_list.size() < 2) - { - showHelp(); - throw fnd::Exception(kModuleName, "Not enough arguments."); - } - - cmd_args.input_path = arg_list.back(); - - for (size_t i = 1; i < arg_list.size(); i++) - { - if (arg_list[i] == "-h" || arg_list[i] == "--help") - { - showHelp(); - throw fnd::Exception(kModuleName, "Nothing to do."); - } - } - - for (size_t i = 1; i+1 < arg_list.size(); i++) - { - bool hasParamter = arg_list[i+1][0] != '-' && i+2 < arg_list.size(); - - if (arg_list[i] == "-d" || arg_list[i] == "--dev") - { - if (hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " does not take a parameter."); - cmd_args.devkit_keys = true; - } - - else if (arg_list[i] == "-y" || arg_list[i] == "--verify") - { - if (hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " does not take a parameter."); - cmd_args.verify_file = true; - } - - else if (arg_list[i] == "--showkeys") - { - if (hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " does not take a parameter."); - cmd_args.show_keys = true; - } - - else if (arg_list[i] == "--showlayout") - { - if (hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " does not take a parameter."); - cmd_args.show_layout = true; - } - - else if (arg_list[i] == "-v" || arg_list[i] == "--verbose") - { - if (hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " does not take a parameter."); - cmd_args.verbose_output = true; - } - - else if (arg_list[i] == "-k" || arg_list[i] == "--keyset") - { - if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); - cmd_args.keyset_path = arg_list[i+1]; - } - - else if (arg_list[i] == "-t" || arg_list[i] == "--type") - { - if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); - cmd_args.file_type = arg_list[i+1]; - } - - else if (arg_list[i] == "--listfs") - { - if (hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " does not take a parameter."); - cmd_args.list_fs = true; - } - - else if (arg_list[i] == "--update") - { - if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); - cmd_args.update_path = arg_list[i+1]; - } - - else if (arg_list[i] == "--normal") - { - if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); - cmd_args.normal_path = arg_list[i+1]; - } - - else if (arg_list[i] == "--secure") - { - if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); - cmd_args.secure_path = arg_list[i+1]; - } - - else if (arg_list[i] == "--logo") - { - if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); - cmd_args.logo_path = arg_list[i+1]; - } - - else if (arg_list[i] == "--fsdir") - { - if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); - cmd_args.fs_path = arg_list[i+1]; - } - - else if (arg_list[i] == "--titlekey") - { - if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); - cmd_args.nca_titlekey = arg_list[i+1]; - } - - else if (arg_list[i] == "--bodykey") - { - if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); - cmd_args.nca_bodykey = arg_list[i+1]; - } - - else if (arg_list[i] == "--tik") - { - if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); - cmd_args.ticket_path = arg_list[i+1]; - } - - else if (arg_list[i] == "--cert") - { - if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); - cmd_args.cert_path = arg_list[i+1]; - } - - else if (arg_list[i] == "--part0") - { - if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); - cmd_args.part0_path = arg_list[i+1]; - } - - else if (arg_list[i] == "--part1") - { - if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); - cmd_args.part1_path = arg_list[i+1]; - } - - else if (arg_list[i] == "--part2") - { - if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); - cmd_args.part2_path = arg_list[i+1]; - } - - else if (arg_list[i] == "--part3") - { - if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); - cmd_args.part3_path = arg_list[i+1]; - } - - else if (arg_list[i] == "--listapi") - { - if (hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " does not take a parameter."); - cmd_args.list_api = true; - } - - else if (arg_list[i] == "--listsym") - { - if (hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " does not take a parameter."); - cmd_args.list_sym = true; - } - - else if (arg_list[i] == "--insttype") - { - if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); - cmd_args.inst_type = arg_list[i + 1]; - } - - else if (arg_list[i] == "--kipdir") - { - if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); - cmd_args.kip_extract_path = arg_list[i + 1]; - } - - else if (arg_list[i] == "--icon") - { - if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); - cmd_args.asset_icon_path = arg_list[i + 1]; - } - - else if (arg_list[i] == "--nacp") - { - if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); - cmd_args.asset_nacp_path = arg_list[i + 1]; - } - - else - { - throw fnd::Exception(kModuleName, arg_list[i] + " is not recognised."); - } - - i += hasParamter; - } -} - -void UserSettings::populateKeyset(sCmdArgs& args) -{ - if (args.keyset_path.isSet) - { - mKeyCfg.importHactoolGenericKeyfile(*args.keyset_path); - } - else - { - // open other resource files in $HOME/.switch/prod.keys (or $HOME/.switch/dev.keys if -d/--dev is set). - std::string keyset_path; - getSwitchPath(keyset_path); - if (keyset_path.empty()) - return; - - fnd::io::appendToPath(keyset_path, kGeneralKeyfileName[args.devkit_keys.isSet]); - - try - { - mKeyCfg.importHactoolGenericKeyfile(keyset_path); - } - catch (const fnd::Exception&) - { - return; - } - - } - - - - if (args.nca_bodykey.isSet) - { - fnd::aes::sAes128Key tmp_key; - fnd::Vec tmp_raw; - fnd::SimpleTextOutput::stringToArray(args.nca_bodykey.var, tmp_raw); - if (tmp_raw.size() != sizeof(fnd::aes::sAes128Key)) - throw fnd::Exception(kModuleName, "Key: \"--bodykey\" has incorrect length"); - memcpy(tmp_key.key, tmp_raw.data(), 16); - mKeyCfg.addNcaExternalContentKey(kDummyRightsIdForUserBodyKey, tmp_key); - } - - if (args.nca_titlekey.isSet) - { - fnd::aes::sAes128Key tmp_key; - fnd::Vec tmp_raw; - fnd::SimpleTextOutput::stringToArray(args.nca_titlekey.var, tmp_raw); - if (tmp_raw.size() != sizeof(fnd::aes::sAes128Key)) - throw fnd::Exception(kModuleName, "Key: \"--titlekey\" has incorrect length"); - memcpy(tmp_key.key, tmp_raw.data(), 16); - mKeyCfg.addNcaExternalContentKey(kDummyRightsIdForUserTitleKey, tmp_key); - } - - // import certificate chain - if (args.cert_path.isSet) - { - fnd::SimpleFile cert_file; - fnd::Vec cert_raw; - nn::pki::SignedData cert; - - cert_file.open(args.cert_path.var, fnd::SimpleFile::Read); - cert_raw.alloc(cert_file.size()); - cert_file.read(cert_raw.data(), cert_raw.size()); - - for (size_t i = 0; i < cert_raw.size(); i+= cert.getBytes().size()) - { - cert.fromBytes(cert_raw.data() + i, cert_raw.size() - i); - mCertChain.addElement(cert); - } - } - - // get titlekey from ticket - if (args.ticket_path.isSet) - { - fnd::SimpleFile tik_file; - fnd::Vec tik_raw; - nn::pki::SignedData tik; - - // open and import ticket - tik_file.open(args.ticket_path.var, fnd::SimpleFile::Read); - tik_raw.alloc(tik_file.size()); - tik_file.read(tik_raw.data(), tik_raw.size()); - tik.fromBytes(tik_raw.data(), tik_raw.size()); - - // validate ticket signature - if (mCertChain.size() > 0) - { - PkiValidator pki_validator; - fnd::Vec tik_hash; - - switch (nn::pki::sign::getHashAlgo(tik.getSignature().getSignType())) - { - case (nn::pki::sign::HASH_ALGO_SHA1): - tik_hash.alloc(fnd::sha::kSha1HashLen); - fnd::sha::Sha1(tik.getBody().getBytes().data(), tik.getBody().getBytes().size(), tik_hash.data()); - break; - case (nn::pki::sign::HASH_ALGO_SHA256): - tik_hash.alloc(fnd::sha::kSha256HashLen); - fnd::sha::Sha256(tik.getBody().getBytes().data(), tik.getBody().getBytes().size(), tik_hash.data()); - break; - } - - try - { - pki_validator.setKeyCfg(mKeyCfg); - pki_validator.addCertificates(mCertChain); - pki_validator.validateSignature(tik.getBody().getIssuer(), tik.getSignature().getSignType(), tik.getSignature().getSignature(), tik_hash); - } - catch (const fnd::Exception& e) - { - std::cout << "[WARNING] Ticket signature could not be validated (" << e.error() << ")" << std::endl; - } - - } - - // extract title key - if (tik.getBody().getTitleKeyEncType() == nn::es::ticket::AES128_CBC) - { - fnd::aes::sAes128Key enc_title_key; - memcpy(enc_title_key.key, tik.getBody().getEncTitleKey(), 16); - fnd::aes::sAes128Key common_key, external_content_key; - if (mKeyCfg.getETicketCommonKey(nn::hac::ContentArchiveUtils::getMasterKeyRevisionFromKeyGeneration(tik.getBody().getCommonKeyId()), common_key) == true) - { - nn::hac::AesKeygen::generateKey(external_content_key.key, tik.getBody().getEncTitleKey(), common_key.key); - mKeyCfg.addNcaExternalContentKey(tik.getBody().getRightsId(), external_content_key); - } - else - { - std::cout << "[WARNING] Titlekey not imported from ticket because commonkey was not available" << std::endl; - } - } - else - { - std::cout << "[WARNING] Titlekey not imported from ticket because it is personalised" << std::endl; - } - } -} - -void UserSettings::populateUserSettings(sCmdArgs& args) -{ - // check invalid input - if (args.input_path.isSet == false) - throw fnd::Exception(kModuleName, "No input file specified"); - - // save arguments - mInputPath = *args.input_path; - mVerifyFile = args.verify_file.isSet; - mListFs = args.list_fs.isSet; - mXciUpdatePath = args.update_path; - mXciNormalPath = args.normal_path; - mXciSecurePath = args.secure_path; - mXciLogoPath = args.logo_path; - - mFsPath = args.fs_path; - mNcaPart0Path = args.part0_path; - mNcaPart1Path = args.part1_path; - mNcaPart2Path = args.part2_path; - mNcaPart3Path = args.part3_path; - - mKipExtractPath = args.kip_extract_path; - - // determine the architecture type for NSO/NRO - if (args.inst_type.isSet) - mInstructionType = getInstructionTypeFromString(*args.inst_type); - else - mInstructionType = nn::hac::meta::INSTR_64BIT; // default 64bit - - mListApi = args.list_api.isSet; - mListSymbols = args.list_sym.isSet; - - mAssetIconPath = args.asset_icon_path; - mAssetNacpPath = args.asset_nacp_path; - - // determine output mode - mOutputMode = _BIT(OUTPUT_BASIC); - if (args.verbose_output.isSet) - { - mOutputMode |= _BIT(OUTPUT_KEY_DATA); - mOutputMode |= _BIT(OUTPUT_LAYOUT); - mOutputMode |= _BIT(OUTPUT_EXTENDED); - } - if (args.show_keys.isSet) - { - mOutputMode |= _BIT(OUTPUT_KEY_DATA); - } - if (args.show_layout.isSet) - { - mOutputMode |= _BIT(OUTPUT_LAYOUT); - } - - // determine input file type - if (args.file_type.isSet) - mFileType = getFileTypeFromString(*args.file_type); - else - mFileType = determineFileTypeFromFile(mInputPath); - - // check is the input file could be identified - if (mFileType == FILE_INVALID) - throw fnd::Exception(kModuleName, "Unknown file type."); -} - -FileType UserSettings::getFileTypeFromString(const std::string& type_str) -{ - std::string str = type_str; - std::transform(str.begin(), str.end(), str.begin(), ::tolower); - - FileType type; - if (str == "gc" || str == "gamecard" || str == "xci") - type = FILE_GC; - else if (str == "nsp") - type = FILE_NSP; - else if (str == "partitionfs" || str == "hashedpartitionfs" \ - || str == "pfs" || str == "pfs0" \ - || str == "hfs" || str == "hfs0") - type = FILE_PARTITIONFS; - else if (str == "romfs") - type = FILE_ROMFS; - else if (str == "nca" || str == "contentarchive") - type = FILE_NCA; - else if (str == "meta" || str == "npdm") - type = FILE_META; - else if (str == "cnmt") - type = FILE_CNMT; - else if (str == "nso") - type = FILE_NSO; - else if (str == "nro") - type = FILE_NRO; - else if (str == "ini") - type = FILE_INI; - else if (str == "kip") - type = FILE_KIP; - else if (str == "nacp") - type = FILE_NACP; - else if (str == "cert") - type = FILE_PKI_CERT; - else if (str == "tik") - type = FILE_ES_TIK; - else if (str == "aset" || str == "asset") - type = FILE_HB_ASSET; - else - type = FILE_INVALID; - - return type; -} - -FileType UserSettings::determineFileTypeFromFile(const std::string& path) -{ - static const size_t kMaxReadSize = 0x5000; - FileType file_type = FILE_INVALID; - fnd::SimpleFile file; - fnd::Vec scratch; - - // open file - file.open(path, file.Read); - - // read file - scratch.alloc(_MIN(kMaxReadSize, file.size())); - file.read(scratch.data(), 0, scratch.size()); - // close file - file.close(); - - // _TYPE_PTR resolves to a pointer of type 'st' located at scratch.data() -#define _TYPE_PTR(st) ((st*)(scratch.data())) -#define _ASSERT_SIZE(sz) (scratch.size() >= (sz)) - - // test npdm - if (_ASSERT_SIZE(sizeof(nn::hac::sGcHeaderPage)) && _TYPE_PTR(nn::hac::sGcHeaderPage)->header.st_magic.get() == nn::hac::gc::kGcHeaderStructMagic) - file_type = FILE_GC; - // test pfs0 - else if (_ASSERT_SIZE(sizeof(nn::hac::sPfsHeader)) && _TYPE_PTR(nn::hac::sPfsHeader)->st_magic.get() == nn::hac::pfs::kPfsStructMagic) - file_type = FILE_PARTITIONFS; - // test hfs0 - else if (_ASSERT_SIZE(sizeof(nn::hac::sPfsHeader)) && _TYPE_PTR(nn::hac::sPfsHeader)->st_magic.get() == nn::hac::pfs::kHashedPfsStructMagic) - file_type = FILE_PARTITIONFS; - // test romfs - else if (_ASSERT_SIZE(sizeof(nn::hac::sRomfsHeader)) && _TYPE_PTR(nn::hac::sRomfsHeader)->header_size.get() == sizeof(nn::hac::sRomfsHeader) && _TYPE_PTR(nn::hac::sRomfsHeader)->sections[1].offset.get() == (_TYPE_PTR(nn::hac::sRomfsHeader)->sections[0].offset.get() + _TYPE_PTR(nn::hac::sRomfsHeader)->sections[0].size.get())) - file_type = FILE_ROMFS; - // test npdm - else if (_ASSERT_SIZE(sizeof(nn::hac::sMetaHeader)) && _TYPE_PTR(nn::hac::sMetaHeader)->st_magic.get() == nn::hac::meta::kMetaStructMagic) - file_type = FILE_META; - // test nca - else if (determineValidNcaFromSample(scratch)) - file_type = FILE_NCA; - // test nso - else if (_ASSERT_SIZE(sizeof(nn::hac::sNsoHeader)) && _TYPE_PTR(nn::hac::sNsoHeader)->st_magic.get() == nn::hac::nso::kNsoStructMagic) - file_type = FILE_NSO; - // test nro - else if (_ASSERT_SIZE(sizeof(nn::hac::sNroHeader)) && _TYPE_PTR(nn::hac::sNroHeader)->st_magic.get() == nn::hac::nro::kNroStructMagic) - file_type = FILE_NRO; - // test ini - else if (_ASSERT_SIZE(sizeof(nn::hac::sIniHeader)) && _TYPE_PTR(nn::hac::sIniHeader)->st_magic.get() == nn::hac::ini::kIniStructMagic) - file_type = FILE_INI; - // test kip - else if (_ASSERT_SIZE(sizeof(nn::hac::sKipHeader)) && _TYPE_PTR(nn::hac::sKipHeader)->st_magic.get() == nn::hac::kip::kKipStructMagic) - file_type = FILE_KIP; - // test pki certificate - else if (determineValidEsCertFromSample(scratch)) - file_type = FILE_PKI_CERT; - // test ticket - else if (determineValidEsTikFromSample(scratch)) - file_type = FILE_ES_TIK; - // test hb asset - else if (_ASSERT_SIZE(sizeof(nn::hac::sAssetHeader)) && _TYPE_PTR(nn::hac::sAssetHeader)->st_magic.get() == nn::hac::aset::kAssetStructMagic) - file_type = FILE_HB_ASSET; - - // do heuristics - // test cnmt - else if (determineValidCnmtFromSample(scratch)) - file_type = FILE_CNMT; - // test nacp - else if (determineValidNacpFromSample(scratch)) - file_type = FILE_NACP; - - - // else unrecognised - else - file_type = FILE_INVALID; - -#undef _ASSERT_SIZE -#undef _TYPE_PTR - - return file_type; -} - -bool UserSettings::determineValidNcaFromSample(const fnd::Vec& sample) const -{ - // prepare decrypted NCA data - byte_t nca_raw[nn::hac::nca::kHeaderSize]; - nn::hac::sContentArchiveHeader* nca_header = (nn::hac::sContentArchiveHeader*)(nca_raw + nn::hac::ContentArchiveUtils::sectorToOffset(1)); - - if (sample.size() < nn::hac::nca::kHeaderSize) - return false; - - fnd::aes::sAesXts128Key header_key; - mKeyCfg.getContentArchiveHeaderKey(header_key); - nn::hac::ContentArchiveUtils::decryptContentArchiveHeader(sample.data(), nca_raw, header_key); - - if (nca_header->st_magic.get() != nn::hac::nca::kNca2StructMagic && nca_header->st_magic.get() != nn::hac::nca::kNca3StructMagic) - return false; - - return true; -} - -bool UserSettings::determineValidCnmtFromSample(const fnd::Vec& sample) const -{ - if (sample.size() < sizeof(nn::hac::sContentMetaHeader)) - return false; - - const nn::hac::sContentMetaHeader* data = (const nn::hac::sContentMetaHeader*)sample.data(); - - size_t minimum_size = sizeof(nn::hac::sContentMetaHeader) + data->exhdr_size.get() + data->content_count.get() * sizeof(nn::hac::sContentInfo) + data->content_meta_count.get() * sizeof(nn::hac::sContentMetaInfo) + nn::hac::cnmt::kDigestLen; - - if (sample.size() < minimum_size) - return false; - - if (data->type == nn::hac::cnmt::METATYPE_APPLICATION) - { - const nn::hac::sApplicationMetaExtendedHeader* meta = (const nn::hac::sApplicationMetaExtendedHeader*)(sample.data() + sizeof(nn::hac::sContentMetaHeader)); - if ((meta->patch_id.get() & data->id.get()) != data->id.get()) - return false; - } - else if (data->type == nn::hac::cnmt::METATYPE_PATCH) - { - const nn::hac::sPatchMetaExtendedHeader* meta = (const nn::hac::sPatchMetaExtendedHeader*)(sample.data() + sizeof(nn::hac::sContentMetaHeader)); - if ((meta->application_id.get() & data->id.get()) != meta->application_id.get()) - return false; - - minimum_size += meta->extended_data_size.get(); - } - else if (data->type == nn::hac::cnmt::METATYPE_ADD_ON_CONTENT) - { - const nn::hac::sAddOnContentMetaExtendedHeader* meta = (const nn::hac::sAddOnContentMetaExtendedHeader*)(sample.data() + sizeof(nn::hac::sContentMetaHeader)); - if ((meta->application_id.get() & data->id.get()) != meta->application_id.get()) - return false; - } - else if (data->type == nn::hac::cnmt::METATYPE_DELTA) - { - const nn::hac::sDeltaMetaExtendedHeader* meta = (const nn::hac::sDeltaMetaExtendedHeader*)(sample.data() + sizeof(nn::hac::sContentMetaHeader)); - if ((meta->application_id.get() & data->id.get()) != meta->application_id.get()) - return false; - - minimum_size += meta->extended_data_size.get(); - } - - if (sample.size() != minimum_size) - return false; - - return true; -} - -bool UserSettings::determineValidNacpFromSample(const fnd::Vec& sample) const -{ - if (sample.size() != sizeof(nn::hac::sApplicationControlProperty)) - return false; - - const nn::hac::sApplicationControlProperty* data = (const nn::hac::sApplicationControlProperty*)sample.data(); - - if (data->logo_type > nn::hac::nacp::LOGO_Nintendo) - return false; - - if (data->display_version[0] == 0) - return false; - - if (data->user_account_save_data_size.get() == 0 && data->user_account_save_data_journal_size.get() != 0) - return false; - - if (data->user_account_save_data_journal_size.get() == 0 && data->user_account_save_data_size.get() != 0) - return false; - - if (data->supported_language_flag.get() == 0) - return false; - - return true; -} - -bool UserSettings::determineValidEsCertFromSample(const fnd::Vec& sample) const -{ - nn::pki::SignatureBlock sign; - - try - { - sign.fromBytes(sample.data(), sample.size()); - } - catch (...) - { - return false; - } - - if (sign.isLittleEndian() == true) - return false; - - if (sign.getSignType() != nn::pki::sign::SIGN_ID_RSA4096_SHA256 && sign.getSignType() != nn::pki::sign::SIGN_ID_RSA2048_SHA256 && sign.getSignType() != nn::pki::sign::SIGN_ID_ECDSA240_SHA256) - return false; - - return true; -} - -bool UserSettings::determineValidEsTikFromSample(const fnd::Vec& sample) const -{ - nn::pki::SignatureBlock sign; - - try - { - sign.fromBytes(sample.data(), sample.size()); - } - catch (...) - { - return false; - } - - if (sign.isLittleEndian() == false) - return false; - - if (sign.getSignType() != nn::pki::sign::SIGN_ID_RSA2048_SHA256) - return false; - - return true; -} - -nn::hac::meta::InstructionType UserSettings::getInstructionTypeFromString(const std::string & type_str) -{ - std::string str = type_str; - std::transform(str.begin(), str.end(), str.begin(), ::tolower); - - nn::hac::meta::InstructionType type; - if (str == "32bit") - type = nn::hac::meta::INSTR_32BIT; - else if (str == "64bit") - type = nn::hac::meta::INSTR_64BIT; - else - throw fnd::Exception(kModuleName, "Unsupported instruction type: " + str); - - return type; -} - -void UserSettings::getHomePath(std::string& path) const -{ - // open other resource files in $HOME/.switch/prod.keys (or $HOME/.switch/dev.keys if -d/--dev is set). - path.clear(); - if (path.empty()) fnd::io::getEnvironVar(path, "HOME"); - if (path.empty()) fnd::io::getEnvironVar(path, "USERPROFILE"); - if (path.empty()) return; -} - -void UserSettings::getSwitchPath(std::string& path) const -{ - std::string home; - home.clear(); - getHomePath(home); - if (home.empty()) - return; - - path.clear(); - fnd::io::appendToPath(path, home); - fnd::io::appendToPath(path, kHomeSwitchDirStr); -} - -void UserSettings::dumpKeyConfig() const -{ - fnd::aes::sAes128Key aes_key; - fnd::aes::sAesXts128Key aesxts_key; - fnd::rsa::sRsa2048Key rsa2048_key; - fnd::rsa::sRsa4096Key rsa4096_key; - - const std::string kKeyIndex[kMasterKeyNum] = {"00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f"}; - - - std::cout << "[KeyConfiguration]" << std::endl; - std::cout << " NCA Keys:" << std::endl; - if (mKeyCfg.getContentArchiveHeader0SignKey(rsa2048_key) == true) - dumpRsa2048Key(rsa2048_key, "Header Signature[0] Key", 2); - if (mKeyCfg.getContentArchiveHeaderKey(aesxts_key) == true) - dumpAesXtsKey(aesxts_key, "Header Encryption Key", 2); - - for (size_t i = 0; i < kMasterKeyNum; i++) - { - if (mKeyCfg.getNcaKeyAreaEncryptionKey(i,0, aes_key) == true) - dumpAesKey(aes_key, "KeyAreaEncryptionKey-Application-" + kKeyIndex[i], 2); - if (mKeyCfg.getNcaKeyAreaEncryptionKey(i,1, aes_key) == true) - dumpAesKey(aes_key, "KeyAreaEncryptionKey-Ocean-" + kKeyIndex[i], 2); - if (mKeyCfg.getNcaKeyAreaEncryptionKey(i,2, aes_key) == true) - dumpAesKey(aes_key, "KeyAreaEncryptionKey-System-" + kKeyIndex[i], 2); - } - - for (size_t i = 0; i < kMasterKeyNum; i++) - { - if (mKeyCfg.getNcaKeyAreaEncryptionKeyHw(i,0, aes_key) == true) - dumpAesKey(aes_key, "KeyAreaEncryptionKeyHw-Application-" + kKeyIndex[i], 2); - if (mKeyCfg.getNcaKeyAreaEncryptionKeyHw(i,1, aes_key) == true) - dumpAesKey(aes_key, "KeyAreaEncryptionKeyHw-Ocean-" + kKeyIndex[i], 2); - if (mKeyCfg.getNcaKeyAreaEncryptionKeyHw(i,2, aes_key) == true) - dumpAesKey(aes_key, "KeyAreaEncryptionKeyHw-System-" + kKeyIndex[i], 2); - } - - std::cout << " XCI Keys:" << std::endl; - if (mKeyCfg.getXciHeaderSignKey(rsa2048_key) == true) - dumpRsa2048Key(rsa2048_key, "Header Signature Key", 2); - if (mKeyCfg.getXciHeaderKey(aes_key) == true) - dumpAesKey(aes_key, "Extended Header Encryption Key", 2); - - - if (mKeyCfg.getAcidSignKey(rsa2048_key) == true) - dumpRsa2048Key(rsa2048_key, "ACID Signer Key", 1); - - - std::cout << " Package1 Keys:" << std::endl; - for (size_t i = 0; i < kMasterKeyNum; i++) - { - if (mKeyCfg.getPkg1Key(i, aes_key) == true) - dumpAesKey(aes_key, "EncryptionKey-" + kKeyIndex[i], 2); - } - - std::cout << " Package2 Keys:" << std::endl; - if (mKeyCfg.getPkg2SignKey(rsa2048_key) == true) - dumpRsa2048Key(rsa2048_key, "Signature Key", 2); - for (size_t i = 0; i < kMasterKeyNum; i++) - { - if (mKeyCfg.getPkg2Key(i, aes_key) == true) - dumpAesKey(aes_key, "EncryptionKey-" + kKeyIndex[i], 2); - } - - std::cout << " ETicket Keys:" << std::endl; - for (size_t i = 0; i < kMasterKeyNum; i++) - { - if (mKeyCfg.getETicketCommonKey(i, aes_key) == true) - dumpAesKey(aes_key, "CommonKey-" + kKeyIndex[i], 2); - } - - if (mKeyCfg.getPkiRootSignKey("Root", rsa4096_key) == true) - dumpRsa4096Key(rsa4096_key, "NNPKI Root Key", 1); -} - -void UserSettings::dumpRsa2048Key(const fnd::rsa::sRsa2048Key& key, const std::string& name, size_t indent) const -{ - std::string indent_str; - - indent_str.clear(); - for (size_t i = 0; i < indent; i++) - { - indent_str += " "; - } - - std::cout << indent_str << name << ":" << std::endl; - if (key.modulus[0] != 0x00 && key.modulus[1] != 0x00) - { - std::cout << indent_str << " Modulus:" << std::endl; - for (size_t i = 0; i < 0x10; i++) - { - std::cout << indent_str << " " << fnd::SimpleTextOutput::arrayToString(key.modulus + i * 0x10, 0x10, true, ":") << std::endl; - } - } - if (key.priv_exponent[0] != 0x00 && key.priv_exponent[1] != 0x00) - { - std::cout << indent_str << " Private Exponent:" << std::endl; - for (size_t i = 0; i < 0x10; i++) - { - std::cout << indent_str << " " << fnd::SimpleTextOutput::arrayToString(key.priv_exponent + i * 0x10, 0x10, true, ":") << std::endl; - } - } -} - -void UserSettings::dumpRsa4096Key(const fnd::rsa::sRsa4096Key& key, const std::string& name, size_t indent) const -{ - std::string indent_str; - - indent_str.clear(); - for (size_t i = 0; i < indent; i++) - { - indent_str += " "; - } - - std::cout << indent_str << name << ":" << std::endl; - if (key.modulus[0] != 0x00 && key.modulus[1] != 0x00) - { - std::cout << indent_str << " Modulus:" << std::endl; - for (size_t i = 0; i < 0x20; i++) - { - std::cout << indent_str << " " << fnd::SimpleTextOutput::arrayToString(key.modulus + i * 0x10, 0x10, true, ":") << std::endl; - } - } - if (key.priv_exponent[0] != 0x00 && key.priv_exponent[1] != 0x00) - { - std::cout << indent_str << " Private Exponent:" << std::endl; - for (size_t i = 0; i < 0x20; i++) - { - std::cout << indent_str << " " << fnd::SimpleTextOutput::arrayToString(key.priv_exponent + i * 0x10, 0x10, true, ":") << std::endl; - } - } -} - -void UserSettings::dumpAesKey(const fnd::aes::sAes128Key& key, const std::string& name, size_t indent) const -{ - std::string indent_str; - - indent_str.clear(); - for (size_t i = 0; i < indent; i++) - { - indent_str += " "; - } - - std::cout << indent_str << name << ":" << std::endl; - std::cout << indent_str << " " << fnd::SimpleTextOutput::arrayToString(key.key, 0x10, true, ":") << std::endl; -} - -void UserSettings::dumpAesXtsKey(const fnd::aes::sAesXts128Key& key, const std::string& name, size_t indent) const -{ - std::string indent_str; - - indent_str.clear(); - for (size_t i = 0; i < indent; i++) - { - indent_str += " "; - } - - std::cout << indent_str << name << ":" << std::endl; - std::cout << indent_str << " " << fnd::SimpleTextOutput::arrayToString(key.key[0], 0x20, true, ":") << std::endl; +#include "UserSettings.h" +#include "version.h" +#include "PkiValidator.h" +#include "KeyConfiguration.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +UserSettings::UserSettings() +{} + +void UserSettings::parseCmdArgs(const std::vector& arg_list) +{ + sCmdArgs args; + populateCmdArgs(arg_list, args); + populateKeyset(args); + populateUserSettings(args); + if (_HAS_BIT(mOutputMode, OUTPUT_KEY_DATA)) + dumpKeyConfig(); +} + +void UserSettings::showHelp() +{ + printf("%s v%d.%d.%d (C) %s\n", APP_NAME, VER_MAJOR, VER_MINOR, VER_PATCH, AUTHORS); + printf("Built: %s %s\n\n", __TIME__, __DATE__); + + printf("Usage: %s [options... ] \n", BIN_NAME); + printf("\n General Options:\n"); + printf(" -d, --dev Use devkit keyset.\n"); + printf(" -k, --keyset Specify keyset file.\n"); + printf(" -t, --type Specify input file type. [xci, pfs, romfs, nca, meta, cnmt, nso, nro, ini, kip, nacp, aset, cert, tik]\n"); + printf(" -y, --verify Verify file.\n"); + printf("\n Output Options:\n"); + printf(" --showkeys Show keys generated.\n"); + printf(" --showlayout Show layout metadata.\n"); + printf(" -v, --verbose Verbose output.\n"); + printf("\n XCI (GameCard Image)\n"); + printf(" %s [--listfs] [--update --logo --normal --secure ] <.xci file>\n", BIN_NAME); + printf(" --listfs Print file system in embedded partitions.\n"); + printf(" --update Extract \"update\" partition to directory.\n"); + printf(" --logo Extract \"logo\" partition to directory.\n"); + printf(" --normal Extract \"normal\" partition to directory.\n"); + printf(" --secure Extract \"secure\" partition to directory.\n"); + printf("\n PFS0/HFS0 (PartitionFs), RomFs, NSP (Ninendo Submission Package)\n"); + printf(" %s [--listfs] [--fsdir ] \n", BIN_NAME); + printf(" --listfs Print file system.\n"); + printf(" --fsdir Extract file system to directory.\n"); + printf("\n NCA (Nintendo Content Archive)\n"); + printf(" %s [--listfs] [--bodykey --titlekey ] [--part0 ...] <.nca file>\n", BIN_NAME); + printf(" --listfs Print file system in embedded partitions.\n"); + printf(" --titlekey Specify title key extracted from ticket.\n"); + printf(" --bodykey Specify body encryption key.\n"); + printf(" --tik Specify ticket to source title key.\n"); + printf(" --cert Specify certificate chain to verify ticket.\n"); + printf(" --part0 Extract \"partition 0\" to directory.\n"); + printf(" --part1 Extract \"partition 1\" to directory.\n"); + printf(" --part2 Extract \"partition 2\" to directory.\n"); + printf(" --part3 Extract \"partition 3\" to directory.\n"); + printf("\n NSO (Nintendo Software Object), NRO (Nintendo Relocatable Object)\n"); + printf(" %s [--listapi --listsym] [--insttype ] \n", BIN_NAME); + printf(" --listapi Print SDK API List.\n"); + printf(" --listsym Print Code Symbols.\n"); + printf(" --insttype Specify instruction type [64bit|32bit] (64bit is assumed).\n"); + printf("\n INI (Initial Process List Blob)\n"); + printf(" %s [--kipdir ] \n", BIN_NAME); + printf(" --kipdir Extract embedded KIPs to directory.\n"); + printf("\n ASET (Homebrew Asset Blob)\n"); + printf(" %s [--listfs] [--icon --nacp --fsdir ] \n", BIN_NAME); + printf(" --listfs Print filesystem in embedded RomFS partition.\n"); + printf(" --icon Extract icon partition to file.\n"); + printf(" --nacp Extract NACP partition to file.\n"); + printf(" --fsdir Extract RomFS partition to directory.\n"); + +} + +const std::string UserSettings::getInputPath() const +{ + return mInputPath; +} + +const KeyConfiguration& UserSettings::getKeyCfg() const +{ + return mKeyCfg; +} + +FileType UserSettings::getFileType() const +{ + return mFileType; +} + +bool UserSettings::isVerifyFile() const +{ + return mVerifyFile; +} + +CliOutputMode UserSettings::getCliOutputMode() const +{ + return mOutputMode; +} + +bool UserSettings::isListFs() const +{ + return mListFs; +} + +bool UserSettings::isListApi() const +{ + return mListApi; +} +bool UserSettings::isListSymbols() const +{ + return mListSymbols; +} + +nn::hac::meta::InstructionType UserSettings::getInstType() const +{ + return mInstructionType; +} + +const sOptional& UserSettings::getXciUpdatePath() const +{ + return mXciUpdatePath; +} + +const sOptional& UserSettings::getXciLogoPath() const +{ + return mXciLogoPath; +} + +const sOptional& UserSettings::getXciNormalPath() const +{ + return mXciNormalPath; +} + +const sOptional& UserSettings::getXciSecurePath() const +{ + return mXciSecurePath; +} + +const sOptional& UserSettings::getFsPath() const +{ + return mFsPath; +} + +const sOptional& UserSettings::getNcaPart0Path() const +{ + return mNcaPart0Path; +} + +const sOptional& UserSettings::getNcaPart1Path() const +{ + return mNcaPart1Path; +} + +const sOptional& UserSettings::getNcaPart2Path() const +{ + return mNcaPart2Path; +} + +const sOptional& UserSettings::getNcaPart3Path() const +{ + return mNcaPart3Path; +} + +const sOptional& UserSettings::getKipExtractPath() const +{ + return mKipExtractPath; +} + +const sOptional& UserSettings::getAssetIconPath() const +{ + return mAssetIconPath; +} + +const sOptional& UserSettings::getAssetNacpPath() const +{ + return mAssetNacpPath; +} + +const fnd::List>& UserSettings::getCertificateChain() const +{ + return mCertChain; +} + +void UserSettings::populateCmdArgs(const std::vector& arg_list, sCmdArgs& cmd_args) +{ + // show help text + if (arg_list.size() < 2) + { + showHelp(); + throw fnd::Exception(kModuleName, "Not enough arguments."); + } + + cmd_args.input_path = arg_list.back(); + + for (size_t i = 1; i < arg_list.size(); i++) + { + if (arg_list[i] == "-h" || arg_list[i] == "--help") + { + showHelp(); + throw fnd::Exception(kModuleName, "Nothing to do."); + } + } + + for (size_t i = 1; i+1 < arg_list.size(); i++) + { + bool hasParamter = arg_list[i+1][0] != '-' && i+2 < arg_list.size(); + + if (arg_list[i] == "-d" || arg_list[i] == "--dev") + { + if (hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " does not take a parameter."); + cmd_args.devkit_keys = true; + } + + else if (arg_list[i] == "-y" || arg_list[i] == "--verify") + { + if (hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " does not take a parameter."); + cmd_args.verify_file = true; + } + + else if (arg_list[i] == "--showkeys") + { + if (hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " does not take a parameter."); + cmd_args.show_keys = true; + } + + else if (arg_list[i] == "--showlayout") + { + if (hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " does not take a parameter."); + cmd_args.show_layout = true; + } + + else if (arg_list[i] == "-v" || arg_list[i] == "--verbose") + { + if (hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " does not take a parameter."); + cmd_args.verbose_output = true; + } + + else if (arg_list[i] == "-k" || arg_list[i] == "--keyset") + { + if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); + cmd_args.keyset_path = arg_list[i+1]; + } + + else if (arg_list[i] == "-t" || arg_list[i] == "--type") + { + if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); + cmd_args.file_type = arg_list[i+1]; + } + + else if (arg_list[i] == "--listfs") + { + if (hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " does not take a parameter."); + cmd_args.list_fs = true; + } + + else if (arg_list[i] == "--update") + { + if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); + cmd_args.update_path = arg_list[i+1]; + } + + else if (arg_list[i] == "--normal") + { + if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); + cmd_args.normal_path = arg_list[i+1]; + } + + else if (arg_list[i] == "--secure") + { + if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); + cmd_args.secure_path = arg_list[i+1]; + } + + else if (arg_list[i] == "--logo") + { + if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); + cmd_args.logo_path = arg_list[i+1]; + } + + else if (arg_list[i] == "--fsdir") + { + if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); + cmd_args.fs_path = arg_list[i+1]; + } + + else if (arg_list[i] == "--titlekey") + { + if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); + cmd_args.nca_titlekey = arg_list[i+1]; + } + + else if (arg_list[i] == "--bodykey") + { + if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); + cmd_args.nca_bodykey = arg_list[i+1]; + } + + else if (arg_list[i] == "--tik") + { + if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); + cmd_args.ticket_path = arg_list[i+1]; + } + + else if (arg_list[i] == "--cert") + { + if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); + cmd_args.cert_path = arg_list[i+1]; + } + + else if (arg_list[i] == "--part0") + { + if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); + cmd_args.part0_path = arg_list[i+1]; + } + + else if (arg_list[i] == "--part1") + { + if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); + cmd_args.part1_path = arg_list[i+1]; + } + + else if (arg_list[i] == "--part2") + { + if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); + cmd_args.part2_path = arg_list[i+1]; + } + + else if (arg_list[i] == "--part3") + { + if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); + cmd_args.part3_path = arg_list[i+1]; + } + + else if (arg_list[i] == "--listapi") + { + if (hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " does not take a parameter."); + cmd_args.list_api = true; + } + + else if (arg_list[i] == "--listsym") + { + if (hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " does not take a parameter."); + cmd_args.list_sym = true; + } + + else if (arg_list[i] == "--insttype") + { + if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); + cmd_args.inst_type = arg_list[i + 1]; + } + + else if (arg_list[i] == "--kipdir") + { + if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); + cmd_args.kip_extract_path = arg_list[i + 1]; + } + + else if (arg_list[i] == "--icon") + { + if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); + cmd_args.asset_icon_path = arg_list[i + 1]; + } + + else if (arg_list[i] == "--nacp") + { + if (!hasParamter) throw fnd::Exception(kModuleName, arg_list[i] + " requries a parameter."); + cmd_args.asset_nacp_path = arg_list[i + 1]; + } + + else + { + throw fnd::Exception(kModuleName, arg_list[i] + " is not recognised."); + } + + i += hasParamter; + } +} + +void UserSettings::populateKeyset(sCmdArgs& args) +{ + if (args.keyset_path.isSet) + { + mKeyCfg.importHactoolGenericKeyfile(*args.keyset_path); + } + else + { + // open other resource files in $HOME/.switch/prod.keys (or $HOME/.switch/dev.keys if -d/--dev is set). + std::string keyset_path; + getSwitchPath(keyset_path); + if (keyset_path.empty()) + return; + + fnd::io::appendToPath(keyset_path, kGeneralKeyfileName[args.devkit_keys.isSet]); + + try + { + mKeyCfg.importHactoolGenericKeyfile(keyset_path); + } + catch (const fnd::Exception&) + { + return; + } + + } + + + + if (args.nca_bodykey.isSet) + { + fnd::aes::sAes128Key tmp_key; + fnd::Vec tmp_raw; + fnd::SimpleTextOutput::stringToArray(args.nca_bodykey.var, tmp_raw); + if (tmp_raw.size() != sizeof(fnd::aes::sAes128Key)) + throw fnd::Exception(kModuleName, "Key: \"--bodykey\" has incorrect length"); + memcpy(tmp_key.key, tmp_raw.data(), 16); + mKeyCfg.addNcaExternalContentKey(kDummyRightsIdForUserBodyKey, tmp_key); + } + + if (args.nca_titlekey.isSet) + { + fnd::aes::sAes128Key tmp_key; + fnd::Vec tmp_raw; + fnd::SimpleTextOutput::stringToArray(args.nca_titlekey.var, tmp_raw); + if (tmp_raw.size() != sizeof(fnd::aes::sAes128Key)) + throw fnd::Exception(kModuleName, "Key: \"--titlekey\" has incorrect length"); + memcpy(tmp_key.key, tmp_raw.data(), 16); + mKeyCfg.addNcaExternalContentKey(kDummyRightsIdForUserTitleKey, tmp_key); + } + + // import certificate chain + if (args.cert_path.isSet) + { + fnd::SimpleFile cert_file; + fnd::Vec cert_raw; + nn::pki::SignedData cert; + + cert_file.open(args.cert_path.var, fnd::SimpleFile::Read); + cert_raw.alloc(cert_file.size()); + cert_file.read(cert_raw.data(), cert_raw.size()); + + for (size_t i = 0; i < cert_raw.size(); i+= cert.getBytes().size()) + { + cert.fromBytes(cert_raw.data() + i, cert_raw.size() - i); + mCertChain.addElement(cert); + } + } + + // get titlekey from ticket + if (args.ticket_path.isSet) + { + fnd::SimpleFile tik_file; + fnd::Vec tik_raw; + nn::pki::SignedData tik; + + // open and import ticket + tik_file.open(args.ticket_path.var, fnd::SimpleFile::Read); + tik_raw.alloc(tik_file.size()); + tik_file.read(tik_raw.data(), tik_raw.size()); + tik.fromBytes(tik_raw.data(), tik_raw.size()); + + // validate ticket signature + if (mCertChain.size() > 0) + { + PkiValidator pki_validator; + fnd::Vec tik_hash; + + switch (nn::pki::sign::getHashAlgo(tik.getSignature().getSignType())) + { + case (nn::pki::sign::HASH_ALGO_SHA1): + tik_hash.alloc(fnd::sha::kSha1HashLen); + fnd::sha::Sha1(tik.getBody().getBytes().data(), tik.getBody().getBytes().size(), tik_hash.data()); + break; + case (nn::pki::sign::HASH_ALGO_SHA256): + tik_hash.alloc(fnd::sha::kSha256HashLen); + fnd::sha::Sha256(tik.getBody().getBytes().data(), tik.getBody().getBytes().size(), tik_hash.data()); + break; + } + + try + { + pki_validator.setKeyCfg(mKeyCfg); + pki_validator.addCertificates(mCertChain); + pki_validator.validateSignature(tik.getBody().getIssuer(), tik.getSignature().getSignType(), tik.getSignature().getSignature(), tik_hash); + } + catch (const fnd::Exception& e) + { + std::cout << "[WARNING] Ticket signature could not be validated (" << e.error() << ")" << std::endl; + } + + } + + // extract title key + if (tik.getBody().getTitleKeyEncType() == nn::es::ticket::AES128_CBC) + { + fnd::aes::sAes128Key enc_title_key; + memcpy(enc_title_key.key, tik.getBody().getEncTitleKey(), 16); + fnd::aes::sAes128Key common_key, external_content_key; + if (mKeyCfg.getETicketCommonKey(nn::hac::ContentArchiveUtils::getMasterKeyRevisionFromKeyGeneration(tik.getBody().getCommonKeyId()), common_key) == true) + { + nn::hac::AesKeygen::generateKey(external_content_key.key, tik.getBody().getEncTitleKey(), common_key.key); + mKeyCfg.addNcaExternalContentKey(tik.getBody().getRightsId(), external_content_key); + } + else + { + std::cout << "[WARNING] Titlekey not imported from ticket because commonkey was not available" << std::endl; + } + } + else + { + std::cout << "[WARNING] Titlekey not imported from ticket because it is personalised" << std::endl; + } + } +} + +void UserSettings::populateUserSettings(sCmdArgs& args) +{ + // check invalid input + if (args.input_path.isSet == false) + throw fnd::Exception(kModuleName, "No input file specified"); + + // save arguments + mInputPath = *args.input_path; + mVerifyFile = args.verify_file.isSet; + mListFs = args.list_fs.isSet; + mXciUpdatePath = args.update_path; + mXciNormalPath = args.normal_path; + mXciSecurePath = args.secure_path; + mXciLogoPath = args.logo_path; + + mFsPath = args.fs_path; + mNcaPart0Path = args.part0_path; + mNcaPart1Path = args.part1_path; + mNcaPart2Path = args.part2_path; + mNcaPart3Path = args.part3_path; + + mKipExtractPath = args.kip_extract_path; + + // determine the architecture type for NSO/NRO + if (args.inst_type.isSet) + mInstructionType = getInstructionTypeFromString(*args.inst_type); + else + mInstructionType = nn::hac::meta::INSTR_64BIT; // default 64bit + + mListApi = args.list_api.isSet; + mListSymbols = args.list_sym.isSet; + + mAssetIconPath = args.asset_icon_path; + mAssetNacpPath = args.asset_nacp_path; + + // determine output mode + mOutputMode = _BIT(OUTPUT_BASIC); + if (args.verbose_output.isSet) + { + mOutputMode |= _BIT(OUTPUT_KEY_DATA); + mOutputMode |= _BIT(OUTPUT_LAYOUT); + mOutputMode |= _BIT(OUTPUT_EXTENDED); + } + if (args.show_keys.isSet) + { + mOutputMode |= _BIT(OUTPUT_KEY_DATA); + } + if (args.show_layout.isSet) + { + mOutputMode |= _BIT(OUTPUT_LAYOUT); + } + + // determine input file type + if (args.file_type.isSet) + mFileType = getFileTypeFromString(*args.file_type); + else + mFileType = determineFileTypeFromFile(mInputPath); + + // check is the input file could be identified + if (mFileType == FILE_INVALID) + throw fnd::Exception(kModuleName, "Unknown file type."); +} + +FileType UserSettings::getFileTypeFromString(const std::string& type_str) +{ + std::string str = type_str; + std::transform(str.begin(), str.end(), str.begin(), ::tolower); + + FileType type; + if (str == "gc" || str == "gamecard" || str == "xci") + type = FILE_GC; + else if (str == "nsp") + type = FILE_NSP; + else if (str == "partitionfs" || str == "hashedpartitionfs" \ + || str == "pfs" || str == "pfs0" \ + || str == "hfs" || str == "hfs0") + type = FILE_PARTITIONFS; + else if (str == "romfs") + type = FILE_ROMFS; + else if (str == "nca" || str == "contentarchive") + type = FILE_NCA; + else if (str == "meta" || str == "npdm") + type = FILE_META; + else if (str == "cnmt") + type = FILE_CNMT; + else if (str == "nso") + type = FILE_NSO; + else if (str == "nro") + type = FILE_NRO; + else if (str == "ini") + type = FILE_INI; + else if (str == "kip") + type = FILE_KIP; + else if (str == "nacp") + type = FILE_NACP; + else if (str == "cert") + type = FILE_PKI_CERT; + else if (str == "tik") + type = FILE_ES_TIK; + else if (str == "aset" || str == "asset") + type = FILE_HB_ASSET; + else + type = FILE_INVALID; + + return type; +} + +FileType UserSettings::determineFileTypeFromFile(const std::string& path) +{ + static const size_t kMaxReadSize = 0x5000; + FileType file_type = FILE_INVALID; + fnd::SimpleFile file; + fnd::Vec scratch; + + // open file + file.open(path, file.Read); + + // read file + scratch.alloc(_MIN(kMaxReadSize, file.size())); + file.read(scratch.data(), 0, scratch.size()); + // close file + file.close(); + + // _TYPE_PTR resolves to a pointer of type 'st' located at scratch.data() +#define _TYPE_PTR(st) ((st*)(scratch.data())) +#define _ASSERT_SIZE(sz) (scratch.size() >= (sz)) + + // test npdm + if (_ASSERT_SIZE(sizeof(nn::hac::sGcHeaderPage)) && _TYPE_PTR(nn::hac::sGcHeaderPage)->header.st_magic.get() == nn::hac::gc::kGcHeaderStructMagic) + file_type = FILE_GC; + // test pfs0 + else if (_ASSERT_SIZE(sizeof(nn::hac::sPfsHeader)) && _TYPE_PTR(nn::hac::sPfsHeader)->st_magic.get() == nn::hac::pfs::kPfsStructMagic) + file_type = FILE_PARTITIONFS; + // test hfs0 + else if (_ASSERT_SIZE(sizeof(nn::hac::sPfsHeader)) && _TYPE_PTR(nn::hac::sPfsHeader)->st_magic.get() == nn::hac::pfs::kHashedPfsStructMagic) + file_type = FILE_PARTITIONFS; + // test romfs + else if (_ASSERT_SIZE(sizeof(nn::hac::sRomfsHeader)) && _TYPE_PTR(nn::hac::sRomfsHeader)->header_size.get() == sizeof(nn::hac::sRomfsHeader) && _TYPE_PTR(nn::hac::sRomfsHeader)->sections[1].offset.get() == (_TYPE_PTR(nn::hac::sRomfsHeader)->sections[0].offset.get() + _TYPE_PTR(nn::hac::sRomfsHeader)->sections[0].size.get())) + file_type = FILE_ROMFS; + // test npdm + else if (_ASSERT_SIZE(sizeof(nn::hac::sMetaHeader)) && _TYPE_PTR(nn::hac::sMetaHeader)->st_magic.get() == nn::hac::meta::kMetaStructMagic) + file_type = FILE_META; + // test nca + else if (determineValidNcaFromSample(scratch)) + file_type = FILE_NCA; + // test nso + else if (_ASSERT_SIZE(sizeof(nn::hac::sNsoHeader)) && _TYPE_PTR(nn::hac::sNsoHeader)->st_magic.get() == nn::hac::nso::kNsoStructMagic) + file_type = FILE_NSO; + // test nro + else if (_ASSERT_SIZE(sizeof(nn::hac::sNroHeader)) && _TYPE_PTR(nn::hac::sNroHeader)->st_magic.get() == nn::hac::nro::kNroStructMagic) + file_type = FILE_NRO; + // test ini + else if (_ASSERT_SIZE(sizeof(nn::hac::sIniHeader)) && _TYPE_PTR(nn::hac::sIniHeader)->st_magic.get() == nn::hac::ini::kIniStructMagic) + file_type = FILE_INI; + // test kip + else if (_ASSERT_SIZE(sizeof(nn::hac::sKipHeader)) && _TYPE_PTR(nn::hac::sKipHeader)->st_magic.get() == nn::hac::kip::kKipStructMagic) + file_type = FILE_KIP; + // test pki certificate + else if (determineValidEsCertFromSample(scratch)) + file_type = FILE_PKI_CERT; + // test ticket + else if (determineValidEsTikFromSample(scratch)) + file_type = FILE_ES_TIK; + // test hb asset + else if (_ASSERT_SIZE(sizeof(nn::hac::sAssetHeader)) && _TYPE_PTR(nn::hac::sAssetHeader)->st_magic.get() == nn::hac::aset::kAssetStructMagic) + file_type = FILE_HB_ASSET; + + // do heuristics + // test cnmt + else if (determineValidCnmtFromSample(scratch)) + file_type = FILE_CNMT; + // test nacp + else if (determineValidNacpFromSample(scratch)) + file_type = FILE_NACP; + + + // else unrecognised + else + file_type = FILE_INVALID; + +#undef _ASSERT_SIZE +#undef _TYPE_PTR + + return file_type; +} + +bool UserSettings::determineValidNcaFromSample(const fnd::Vec& sample) const +{ + // prepare decrypted NCA data + byte_t nca_raw[nn::hac::nca::kHeaderSize]; + nn::hac::sContentArchiveHeader* nca_header = (nn::hac::sContentArchiveHeader*)(nca_raw + nn::hac::ContentArchiveUtils::sectorToOffset(1)); + + if (sample.size() < nn::hac::nca::kHeaderSize) + return false; + + fnd::aes::sAesXts128Key header_key; + mKeyCfg.getContentArchiveHeaderKey(header_key); + nn::hac::ContentArchiveUtils::decryptContentArchiveHeader(sample.data(), nca_raw, header_key); + + if (nca_header->st_magic.get() != nn::hac::nca::kNca2StructMagic && nca_header->st_magic.get() != nn::hac::nca::kNca3StructMagic) + return false; + + return true; +} + +bool UserSettings::determineValidCnmtFromSample(const fnd::Vec& sample) const +{ + if (sample.size() < sizeof(nn::hac::sContentMetaHeader)) + return false; + + const nn::hac::sContentMetaHeader* data = (const nn::hac::sContentMetaHeader*)sample.data(); + + size_t minimum_size = sizeof(nn::hac::sContentMetaHeader) + data->exhdr_size.get() + data->content_count.get() * sizeof(nn::hac::sContentInfo) + data->content_meta_count.get() * sizeof(nn::hac::sContentMetaInfo) + nn::hac::cnmt::kDigestLen; + + if (sample.size() < minimum_size) + return false; + + if (data->type == nn::hac::cnmt::METATYPE_APPLICATION) + { + const nn::hac::sApplicationMetaExtendedHeader* meta = (const nn::hac::sApplicationMetaExtendedHeader*)(sample.data() + sizeof(nn::hac::sContentMetaHeader)); + if ((meta->patch_id.get() & data->id.get()) != data->id.get()) + return false; + } + else if (data->type == nn::hac::cnmt::METATYPE_PATCH) + { + const nn::hac::sPatchMetaExtendedHeader* meta = (const nn::hac::sPatchMetaExtendedHeader*)(sample.data() + sizeof(nn::hac::sContentMetaHeader)); + if ((meta->application_id.get() & data->id.get()) != meta->application_id.get()) + return false; + + minimum_size += meta->extended_data_size.get(); + } + else if (data->type == nn::hac::cnmt::METATYPE_ADD_ON_CONTENT) + { + const nn::hac::sAddOnContentMetaExtendedHeader* meta = (const nn::hac::sAddOnContentMetaExtendedHeader*)(sample.data() + sizeof(nn::hac::sContentMetaHeader)); + if ((meta->application_id.get() & data->id.get()) != meta->application_id.get()) + return false; + } + else if (data->type == nn::hac::cnmt::METATYPE_DELTA) + { + const nn::hac::sDeltaMetaExtendedHeader* meta = (const nn::hac::sDeltaMetaExtendedHeader*)(sample.data() + sizeof(nn::hac::sContentMetaHeader)); + if ((meta->application_id.get() & data->id.get()) != meta->application_id.get()) + return false; + + minimum_size += meta->extended_data_size.get(); + } + + if (sample.size() != minimum_size) + return false; + + return true; +} + +bool UserSettings::determineValidNacpFromSample(const fnd::Vec& sample) const +{ + if (sample.size() != sizeof(nn::hac::sApplicationControlProperty)) + return false; + + const nn::hac::sApplicationControlProperty* data = (const nn::hac::sApplicationControlProperty*)sample.data(); + + if (data->logo_type > nn::hac::nacp::LOGO_Nintendo) + return false; + + if (data->display_version[0] == 0) + return false; + + if (data->user_account_save_data_size.get() == 0 && data->user_account_save_data_journal_size.get() != 0) + return false; + + if (data->user_account_save_data_journal_size.get() == 0 && data->user_account_save_data_size.get() != 0) + return false; + + if (data->supported_language_flag.get() == 0) + return false; + + return true; +} + +bool UserSettings::determineValidEsCertFromSample(const fnd::Vec& sample) const +{ + nn::pki::SignatureBlock sign; + + try + { + sign.fromBytes(sample.data(), sample.size()); + } + catch (...) + { + return false; + } + + if (sign.isLittleEndian() == true) + return false; + + if (sign.getSignType() != nn::pki::sign::SIGN_ID_RSA4096_SHA256 && sign.getSignType() != nn::pki::sign::SIGN_ID_RSA2048_SHA256 && sign.getSignType() != nn::pki::sign::SIGN_ID_ECDSA240_SHA256) + return false; + + return true; +} + +bool UserSettings::determineValidEsTikFromSample(const fnd::Vec& sample) const +{ + nn::pki::SignatureBlock sign; + + try + { + sign.fromBytes(sample.data(), sample.size()); + } + catch (...) + { + return false; + } + + if (sign.isLittleEndian() == false) + return false; + + if (sign.getSignType() != nn::pki::sign::SIGN_ID_RSA2048_SHA256) + return false; + + return true; +} + +nn::hac::meta::InstructionType UserSettings::getInstructionTypeFromString(const std::string & type_str) +{ + std::string str = type_str; + std::transform(str.begin(), str.end(), str.begin(), ::tolower); + + nn::hac::meta::InstructionType type; + if (str == "32bit") + type = nn::hac::meta::INSTR_32BIT; + else if (str == "64bit") + type = nn::hac::meta::INSTR_64BIT; + else + throw fnd::Exception(kModuleName, "Unsupported instruction type: " + str); + + return type; +} + +void UserSettings::getHomePath(std::string& path) const +{ + // open other resource files in $HOME/.switch/prod.keys (or $HOME/.switch/dev.keys if -d/--dev is set). + path.clear(); + if (path.empty()) fnd::io::getEnvironVar(path, "HOME"); + if (path.empty()) fnd::io::getEnvironVar(path, "USERPROFILE"); + if (path.empty()) return; +} + +void UserSettings::getSwitchPath(std::string& path) const +{ + std::string home; + home.clear(); + getHomePath(home); + if (home.empty()) + return; + + path.clear(); + fnd::io::appendToPath(path, home); + fnd::io::appendToPath(path, kHomeSwitchDirStr); +} + +void UserSettings::dumpKeyConfig() const +{ + fnd::aes::sAes128Key aes_key; + fnd::aes::sAesXts128Key aesxts_key; + fnd::rsa::sRsa2048Key rsa2048_key; + fnd::rsa::sRsa4096Key rsa4096_key; + + const std::string kKeyIndex[kMasterKeyNum] = {"00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f"}; + + + std::cout << "[KeyConfiguration]" << std::endl; + std::cout << " NCA Keys:" << std::endl; + if (mKeyCfg.getContentArchiveHeader0SignKey(rsa2048_key) == true) + dumpRsa2048Key(rsa2048_key, "Header Signature[0] Key", 2); + if (mKeyCfg.getContentArchiveHeaderKey(aesxts_key) == true) + dumpAesXtsKey(aesxts_key, "Header Encryption Key", 2); + + for (size_t i = 0; i < kMasterKeyNum; i++) + { + if (mKeyCfg.getNcaKeyAreaEncryptionKey(i,0, aes_key) == true) + dumpAesKey(aes_key, "KeyAreaEncryptionKey-Application-" + kKeyIndex[i], 2); + if (mKeyCfg.getNcaKeyAreaEncryptionKey(i,1, aes_key) == true) + dumpAesKey(aes_key, "KeyAreaEncryptionKey-Ocean-" + kKeyIndex[i], 2); + if (mKeyCfg.getNcaKeyAreaEncryptionKey(i,2, aes_key) == true) + dumpAesKey(aes_key, "KeyAreaEncryptionKey-System-" + kKeyIndex[i], 2); + } + + for (size_t i = 0; i < kMasterKeyNum; i++) + { + if (mKeyCfg.getNcaKeyAreaEncryptionKeyHw(i,0, aes_key) == true) + dumpAesKey(aes_key, "KeyAreaEncryptionKeyHw-Application-" + kKeyIndex[i], 2); + if (mKeyCfg.getNcaKeyAreaEncryptionKeyHw(i,1, aes_key) == true) + dumpAesKey(aes_key, "KeyAreaEncryptionKeyHw-Ocean-" + kKeyIndex[i], 2); + if (mKeyCfg.getNcaKeyAreaEncryptionKeyHw(i,2, aes_key) == true) + dumpAesKey(aes_key, "KeyAreaEncryptionKeyHw-System-" + kKeyIndex[i], 2); + } + + std::cout << " XCI Keys:" << std::endl; + if (mKeyCfg.getXciHeaderSignKey(rsa2048_key) == true) + dumpRsa2048Key(rsa2048_key, "Header Signature Key", 2); + if (mKeyCfg.getXciHeaderKey(aes_key) == true) + dumpAesKey(aes_key, "Extended Header Encryption Key", 2); + + + if (mKeyCfg.getAcidSignKey(rsa2048_key) == true) + dumpRsa2048Key(rsa2048_key, "ACID Signer Key", 1); + + + std::cout << " Package1 Keys:" << std::endl; + for (size_t i = 0; i < kMasterKeyNum; i++) + { + if (mKeyCfg.getPkg1Key(i, aes_key) == true) + dumpAesKey(aes_key, "EncryptionKey-" + kKeyIndex[i], 2); + } + + std::cout << " Package2 Keys:" << std::endl; + if (mKeyCfg.getPkg2SignKey(rsa2048_key) == true) + dumpRsa2048Key(rsa2048_key, "Signature Key", 2); + for (size_t i = 0; i < kMasterKeyNum; i++) + { + if (mKeyCfg.getPkg2Key(i, aes_key) == true) + dumpAesKey(aes_key, "EncryptionKey-" + kKeyIndex[i], 2); + } + + std::cout << " ETicket Keys:" << std::endl; + for (size_t i = 0; i < kMasterKeyNum; i++) + { + if (mKeyCfg.getETicketCommonKey(i, aes_key) == true) + dumpAesKey(aes_key, "CommonKey-" + kKeyIndex[i], 2); + } + + if (mKeyCfg.getPkiRootSignKey("Root", rsa4096_key) == true) + dumpRsa4096Key(rsa4096_key, "NNPKI Root Key", 1); +} + +void UserSettings::dumpRsa2048Key(const fnd::rsa::sRsa2048Key& key, const std::string& name, size_t indent) const +{ + std::string indent_str; + + indent_str.clear(); + for (size_t i = 0; i < indent; i++) + { + indent_str += " "; + } + + std::cout << indent_str << name << ":" << std::endl; + if (key.modulus[0] != 0x00 && key.modulus[1] != 0x00) + { + std::cout << indent_str << " Modulus:" << std::endl; + for (size_t i = 0; i < 0x10; i++) + { + std::cout << indent_str << " " << fnd::SimpleTextOutput::arrayToString(key.modulus + i * 0x10, 0x10, true, ":") << std::endl; + } + } + if (key.priv_exponent[0] != 0x00 && key.priv_exponent[1] != 0x00) + { + std::cout << indent_str << " Private Exponent:" << std::endl; + for (size_t i = 0; i < 0x10; i++) + { + std::cout << indent_str << " " << fnd::SimpleTextOutput::arrayToString(key.priv_exponent + i * 0x10, 0x10, true, ":") << std::endl; + } + } +} + +void UserSettings::dumpRsa4096Key(const fnd::rsa::sRsa4096Key& key, const std::string& name, size_t indent) const +{ + std::string indent_str; + + indent_str.clear(); + for (size_t i = 0; i < indent; i++) + { + indent_str += " "; + } + + std::cout << indent_str << name << ":" << std::endl; + if (key.modulus[0] != 0x00 && key.modulus[1] != 0x00) + { + std::cout << indent_str << " Modulus:" << std::endl; + for (size_t i = 0; i < 0x20; i++) + { + std::cout << indent_str << " " << fnd::SimpleTextOutput::arrayToString(key.modulus + i * 0x10, 0x10, true, ":") << std::endl; + } + } + if (key.priv_exponent[0] != 0x00 && key.priv_exponent[1] != 0x00) + { + std::cout << indent_str << " Private Exponent:" << std::endl; + for (size_t i = 0; i < 0x20; i++) + { + std::cout << indent_str << " " << fnd::SimpleTextOutput::arrayToString(key.priv_exponent + i * 0x10, 0x10, true, ":") << std::endl; + } + } +} + +void UserSettings::dumpAesKey(const fnd::aes::sAes128Key& key, const std::string& name, size_t indent) const +{ + std::string indent_str; + + indent_str.clear(); + for (size_t i = 0; i < indent; i++) + { + indent_str += " "; + } + + std::cout << indent_str << name << ":" << std::endl; + std::cout << indent_str << " " << fnd::SimpleTextOutput::arrayToString(key.key, 0x10, true, ":") << std::endl; +} + +void UserSettings::dumpAesXtsKey(const fnd::aes::sAesXts128Key& key, const std::string& name, size_t indent) const +{ + std::string indent_str; + + indent_str.clear(); + for (size_t i = 0; i < indent; i++) + { + indent_str += " "; + } + + std::cout << indent_str << name << ":" << std::endl; + std::cout << indent_str << " " << fnd::SimpleTextOutput::arrayToString(key.key[0], 0x20, true, ":") << std::endl; } \ No newline at end of file diff --git a/programs/nstool/source/UserSettings.h b/src/UserSettings.h similarity index 97% rename from programs/nstool/source/UserSettings.h rename to src/UserSettings.h index 6e69aeb..dff6153 100644 --- a/programs/nstool/source/UserSettings.h +++ b/src/UserSettings.h @@ -1,138 +1,138 @@ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include "common.h" -#include "KeyConfiguration.h" - -class UserSettings -{ -public: - UserSettings(); - - void parseCmdArgs(const std::vector& arg_list); - void showHelp(); - - // generic options - const std::string getInputPath() const; - const KeyConfiguration& getKeyCfg() const; - FileType getFileType() const; - bool isVerifyFile() const; - CliOutputMode getCliOutputMode() const; - - // specialised toggles - bool isListFs() const; - bool isListApi() const; - bool isListSymbols() const; - nn::hac::meta::InstructionType getInstType() const; - - // specialised paths - const sOptional& getXciUpdatePath() const; - const sOptional& getXciLogoPath() const; - const sOptional& getXciNormalPath() const; - const sOptional& getXciSecurePath() const; - const sOptional& getFsPath() const; - const sOptional& getNcaPart0Path() const; - const sOptional& getNcaPart1Path() const; - const sOptional& getNcaPart2Path() const; - const sOptional& getNcaPart3Path() const; - const sOptional& getKipExtractPath() const; - const sOptional& getAssetIconPath() const; - const sOptional& getAssetNacpPath() const; - const fnd::List>& getCertificateChain() const; - -private: - const std::string kModuleName = "UserSettings"; - - const std::string kHomeSwitchDirStr = ".switch"; - const std::string kGeneralKeyfileName[2] = { "prod.keys", "dev.keys" }; - const std::string kTitleKeyfileName = "title.keys"; - - - struct sCmdArgs - { - sCmdArgs() {} - sOptional input_path; - sOptional devkit_keys; - sOptional keyset_path; - sOptional file_type; - sOptional verify_file; - sOptional show_keys; - sOptional show_layout; - sOptional verbose_output; - sOptional list_fs; - sOptional update_path; - sOptional logo_path; - sOptional normal_path; - sOptional secure_path; - sOptional fs_path; - sOptional nca_titlekey; - sOptional nca_bodykey; - sOptional ticket_path; - sOptional cert_path; - sOptional part0_path; - sOptional part1_path; - sOptional part2_path; - sOptional part3_path; - sOptional kip_extract_path; - sOptional list_api; - sOptional list_sym; - sOptional inst_type; - sOptional asset_icon_path; - sOptional asset_nacp_path; - }; - - std::string mInputPath; - FileType mFileType; - KeyConfiguration mKeyCfg; - bool mVerifyFile; - CliOutputMode mOutputMode; - - bool mListFs; - sOptional mXciUpdatePath; - sOptional mXciLogoPath; - sOptional mXciNormalPath; - sOptional mXciSecurePath; - sOptional mFsPath; - - sOptional mNcaPart0Path; - sOptional mNcaPart1Path; - sOptional mNcaPart2Path; - sOptional mNcaPart3Path; - - sOptional mKipExtractPath; - - sOptional mAssetIconPath; - sOptional mAssetNacpPath; - - fnd::List> mCertChain; - - bool mListApi; - bool mListSymbols; - nn::hac::meta::InstructionType mInstructionType; - - void populateCmdArgs(const std::vector& arg_list, sCmdArgs& cmd_args); - void populateKeyset(sCmdArgs& args); - void populateUserSettings(sCmdArgs& args); - FileType getFileTypeFromString(const std::string& type_str); - FileType determineFileTypeFromFile(const std::string& path); - bool determineValidNcaFromSample(const fnd::Vec& sample) const; - bool determineValidCnmtFromSample(const fnd::Vec& sample) const; - bool determineValidNacpFromSample(const fnd::Vec& sample) const; - bool determineValidEsCertFromSample(const fnd::Vec& sample) const; - bool determineValidEsTikFromSample(const fnd::Vec& sample) const; - nn::hac::meta::InstructionType getInstructionTypeFromString(const std::string& type_str); - void getHomePath(std::string& path) const; - void getSwitchPath(std::string& path) const; - - void dumpKeyConfig() const; - void dumpRsa2048Key(const fnd::rsa::sRsa2048Key& key, const std::string& name, size_t indent) const; - void dumpRsa4096Key(const fnd::rsa::sRsa4096Key& key, const std::string& name, size_t indent) const; - void dumpAesKey(const fnd::aes::sAes128Key& key, const std::string& name, size_t indent) const; - void dumpAesXtsKey(const fnd::aes::sAesXts128Key& key, const std::string& name, size_t indent) const; +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include "common.h" +#include "KeyConfiguration.h" + +class UserSettings +{ +public: + UserSettings(); + + void parseCmdArgs(const std::vector& arg_list); + void showHelp(); + + // generic options + const std::string getInputPath() const; + const KeyConfiguration& getKeyCfg() const; + FileType getFileType() const; + bool isVerifyFile() const; + CliOutputMode getCliOutputMode() const; + + // specialised toggles + bool isListFs() const; + bool isListApi() const; + bool isListSymbols() const; + nn::hac::meta::InstructionType getInstType() const; + + // specialised paths + const sOptional& getXciUpdatePath() const; + const sOptional& getXciLogoPath() const; + const sOptional& getXciNormalPath() const; + const sOptional& getXciSecurePath() const; + const sOptional& getFsPath() const; + const sOptional& getNcaPart0Path() const; + const sOptional& getNcaPart1Path() const; + const sOptional& getNcaPart2Path() const; + const sOptional& getNcaPart3Path() const; + const sOptional& getKipExtractPath() const; + const sOptional& getAssetIconPath() const; + const sOptional& getAssetNacpPath() const; + const fnd::List>& getCertificateChain() const; + +private: + const std::string kModuleName = "UserSettings"; + + const std::string kHomeSwitchDirStr = ".switch"; + const std::string kGeneralKeyfileName[2] = { "prod.keys", "dev.keys" }; + const std::string kTitleKeyfileName = "title.keys"; + + + struct sCmdArgs + { + sCmdArgs() {} + sOptional input_path; + sOptional devkit_keys; + sOptional keyset_path; + sOptional file_type; + sOptional verify_file; + sOptional show_keys; + sOptional show_layout; + sOptional verbose_output; + sOptional list_fs; + sOptional update_path; + sOptional logo_path; + sOptional normal_path; + sOptional secure_path; + sOptional fs_path; + sOptional nca_titlekey; + sOptional nca_bodykey; + sOptional ticket_path; + sOptional cert_path; + sOptional part0_path; + sOptional part1_path; + sOptional part2_path; + sOptional part3_path; + sOptional kip_extract_path; + sOptional list_api; + sOptional list_sym; + sOptional inst_type; + sOptional asset_icon_path; + sOptional asset_nacp_path; + }; + + std::string mInputPath; + FileType mFileType; + KeyConfiguration mKeyCfg; + bool mVerifyFile; + CliOutputMode mOutputMode; + + bool mListFs; + sOptional mXciUpdatePath; + sOptional mXciLogoPath; + sOptional mXciNormalPath; + sOptional mXciSecurePath; + sOptional mFsPath; + + sOptional mNcaPart0Path; + sOptional mNcaPart1Path; + sOptional mNcaPart2Path; + sOptional mNcaPart3Path; + + sOptional mKipExtractPath; + + sOptional mAssetIconPath; + sOptional mAssetNacpPath; + + fnd::List> mCertChain; + + bool mListApi; + bool mListSymbols; + nn::hac::meta::InstructionType mInstructionType; + + void populateCmdArgs(const std::vector& arg_list, sCmdArgs& cmd_args); + void populateKeyset(sCmdArgs& args); + void populateUserSettings(sCmdArgs& args); + FileType getFileTypeFromString(const std::string& type_str); + FileType determineFileTypeFromFile(const std::string& path); + bool determineValidNcaFromSample(const fnd::Vec& sample) const; + bool determineValidCnmtFromSample(const fnd::Vec& sample) const; + bool determineValidNacpFromSample(const fnd::Vec& sample) const; + bool determineValidEsCertFromSample(const fnd::Vec& sample) const; + bool determineValidEsTikFromSample(const fnd::Vec& sample) const; + nn::hac::meta::InstructionType getInstructionTypeFromString(const std::string& type_str); + void getHomePath(std::string& path) const; + void getSwitchPath(std::string& path) const; + + void dumpKeyConfig() const; + void dumpRsa2048Key(const fnd::rsa::sRsa2048Key& key, const std::string& name, size_t indent) const; + void dumpRsa4096Key(const fnd::rsa::sRsa4096Key& key, const std::string& name, size_t indent) const; + void dumpAesKey(const fnd::aes::sAes128Key& key, const std::string& name, size_t indent) const; + void dumpAesXtsKey(const fnd::aes::sAesXts128Key& key, const std::string& name, size_t indent) const; }; \ No newline at end of file diff --git a/programs/nstool/source/common.h b/src/common.h similarity index 96% rename from programs/nstool/source/common.h rename to src/common.h index d8f637e..df33d69 100644 --- a/programs/nstool/source/common.h +++ b/src/common.h @@ -1,62 +1,62 @@ -#pragma once -#include -#include -#include -#include -#include - -static const size_t kMasterKeyNum = 0x20; -static const size_t kNcaKeakNum = nn::hac::nca::kKeyAreaEncryptionKeyNum; - -enum FileType -{ - FILE_GC, - FILE_NSP, - FILE_PARTITIONFS, - FILE_ROMFS, - FILE_NCA, - FILE_META, - FILE_CNMT, - FILE_NSO, - FILE_NRO, - FILE_NACP, - FILE_INI, - FILE_KIP, - FILE_PKI_CERT, - FILE_ES_TIK, - FILE_HB_ASSET, - FILE_INVALID = -1, -}; - -enum CliOutputModeFlag -{ - OUTPUT_BASIC, - OUTPUT_LAYOUT, - OUTPUT_KEY_DATA, - OUTPUT_EXTENDED -}; - -typedef byte_t CliOutputMode; - -template -struct sOptional -{ - bool isSet; - T var; - inline sOptional() : isSet(false) {} - inline sOptional(const T& other) : isSet(true), var(other) {} - inline sOptional(const sOptional& other) : isSet(other.isSet), var(other.var) {} - inline const T& operator=(const T& other) { isSet = true; var = other; return var; } - inline const sOptional& operator=(const sOptional& other) - { - isSet = other.isSet; - if (isSet) { - var = other.var; - } - return *this; - } - inline T& operator*() { return var; } -}; - -const byte_t kDummyRightsIdForUserTitleKey[nn::hac::nca::kRightsIdLen] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; +#pragma once +#include +#include +#include +#include +#include + +static const size_t kMasterKeyNum = 0x20; +static const size_t kNcaKeakNum = nn::hac::nca::kKeyAreaEncryptionKeyNum; + +enum FileType +{ + FILE_GC, + FILE_NSP, + FILE_PARTITIONFS, + FILE_ROMFS, + FILE_NCA, + FILE_META, + FILE_CNMT, + FILE_NSO, + FILE_NRO, + FILE_NACP, + FILE_INI, + FILE_KIP, + FILE_PKI_CERT, + FILE_ES_TIK, + FILE_HB_ASSET, + FILE_INVALID = -1, +}; + +enum CliOutputModeFlag +{ + OUTPUT_BASIC, + OUTPUT_LAYOUT, + OUTPUT_KEY_DATA, + OUTPUT_EXTENDED +}; + +typedef byte_t CliOutputMode; + +template +struct sOptional +{ + bool isSet; + T var; + inline sOptional() : isSet(false) {} + inline sOptional(const T& other) : isSet(true), var(other) {} + inline sOptional(const sOptional& other) : isSet(other.isSet), var(other.var) {} + inline const T& operator=(const T& other) { isSet = true; var = other; return var; } + inline const sOptional& operator=(const sOptional& other) + { + isSet = other.isSet; + if (isSet) { + var = other.var; + } + return *this; + } + inline T& operator*() { return var; } +}; + +const byte_t kDummyRightsIdForUserTitleKey[nn::hac::nca::kRightsIdLen] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; const byte_t kDummyRightsIdForUserBodyKey[nn::hac::nca::kRightsIdLen] = {0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe}; \ No newline at end of file diff --git a/programs/nstool/source/main.cpp b/src/main.cpp similarity index 96% rename from programs/nstool/source/main.cpp rename to src/main.cpp index a12867b..2ed927b 100644 --- a/programs/nstool/source/main.cpp +++ b/src/main.cpp @@ -1,257 +1,257 @@ -#include -#include -#include -#include -#include "UserSettings.h" -#include "GameCardProcess.h" -#include "PfsProcess.h" -#include "RomfsProcess.h" -#include "NcaProcess.h" -#include "MetaProcess.h" -#include "CnmtProcess.h" -#include "NsoProcess.h" -#include "NroProcess.h" -#include "NacpProcess.h" -#include "IniProcess.h" -#include "KipProcess.h" -#include "PkiCertProcess.h" -#include "EsTikProcess.h" -#include "AssetProcess.h" - -#ifdef _WIN32 -int wmain(int argc, wchar_t** argv) -#else -int main(int argc, char** argv) -#endif -{ - std::vector args; - for (size_t i = 0; i < (size_t)argc; i++) - { -#ifdef _WIN32 - args.push_back(fnd::StringConv::ConvertChar16ToChar8(std::u16string((char16_t*)argv[i]))); -#else - args.push_back(argv[i]); -#endif - } - - UserSettings user_set; - try { - user_set.parseCmdArgs(args); - - fnd::SharedPtr inputFile(new fnd::SimpleFile(user_set.getInputPath(), fnd::SimpleFile::Read)); - - if (user_set.getFileType() == FILE_GC) - { - GameCardProcess obj; - - obj.setInputFile(inputFile); - - obj.setKeyCfg(user_set.getKeyCfg()); - obj.setCliOutputMode(user_set.getCliOutputMode()); - obj.setVerifyMode(user_set.isVerifyFile()); - - if (user_set.getXciUpdatePath().isSet) - obj.setPartitionForExtract(nn::hac::gc::kUpdatePartitionStr, user_set.getXciUpdatePath().var); - if (user_set.getXciLogoPath().isSet) - obj.setPartitionForExtract(nn::hac::gc::kLogoPartitionStr, user_set.getXciLogoPath().var); - if (user_set.getXciNormalPath().isSet) - obj.setPartitionForExtract(nn::hac::gc::kNormalPartitionStr, user_set.getXciNormalPath().var); - if (user_set.getXciSecurePath().isSet) - obj.setPartitionForExtract(nn::hac::gc::kSecurePartitionStr, user_set.getXciSecurePath().var); - obj.setListFs(user_set.isListFs()); - - obj.process(); - } - else if (user_set.getFileType() == FILE_PARTITIONFS || user_set.getFileType() == FILE_NSP) - { - PfsProcess obj; - - obj.setInputFile(inputFile); - obj.setCliOutputMode(user_set.getCliOutputMode()); - obj.setVerifyMode(user_set.isVerifyFile()); - - if (user_set.getFsPath().isSet) - obj.setExtractPath(user_set.getFsPath().var); - obj.setListFs(user_set.isListFs()); - - obj.process(); - } - else if (user_set.getFileType() == FILE_ROMFS) - { - RomfsProcess obj; - - obj.setInputFile(inputFile); - obj.setCliOutputMode(user_set.getCliOutputMode()); - obj.setVerifyMode(user_set.isVerifyFile()); - - if (user_set.getFsPath().isSet) - obj.setExtractPath(user_set.getFsPath().var); - obj.setListFs(user_set.isListFs()); - - obj.process(); - } - else if (user_set.getFileType() == FILE_NCA) - { - NcaProcess obj; - - obj.setInputFile(inputFile); - obj.setKeyCfg(user_set.getKeyCfg()); - obj.setCliOutputMode(user_set.getCliOutputMode()); - obj.setVerifyMode(user_set.isVerifyFile()); - - - if (user_set.getNcaPart0Path().isSet) - obj.setPartition0ExtractPath(user_set.getNcaPart0Path().var); - if (user_set.getNcaPart1Path().isSet) - obj.setPartition1ExtractPath(user_set.getNcaPart1Path().var); - if (user_set.getNcaPart2Path().isSet) - obj.setPartition2ExtractPath(user_set.getNcaPart2Path().var); - if (user_set.getNcaPart3Path().isSet) - obj.setPartition3ExtractPath(user_set.getNcaPart3Path().var); - obj.setListFs(user_set.isListFs()); - - obj.process(); - } - else if (user_set.getFileType() == FILE_META) - { - MetaProcess obj; - - obj.setInputFile(inputFile); - obj.setKeyCfg(user_set.getKeyCfg()); - obj.setCliOutputMode(user_set.getCliOutputMode()); - obj.setVerifyMode(user_set.isVerifyFile()); - - obj.process(); - } - else if (user_set.getFileType() == FILE_CNMT) - { - CnmtProcess obj; - - obj.setInputFile(inputFile); - obj.setCliOutputMode(user_set.getCliOutputMode()); - obj.setVerifyMode(user_set.isVerifyFile()); - - obj.process(); - } - else if (user_set.getFileType() == FILE_NSO) - { - NsoProcess obj; - - obj.setInputFile(inputFile); - obj.setCliOutputMode(user_set.getCliOutputMode()); - obj.setVerifyMode(user_set.isVerifyFile()); - - obj.setInstructionType(user_set.getInstType()); - obj.setListApi(user_set.isListApi()); - obj.setListSymbols(user_set.isListSymbols()); - - obj.process(); - } - else if (user_set.getFileType() == FILE_NRO) - { - NroProcess obj; - - obj.setInputFile(inputFile); - obj.setCliOutputMode(user_set.getCliOutputMode()); - obj.setVerifyMode(user_set.isVerifyFile()); - - obj.setInstructionType(user_set.getInstType()); - obj.setListApi(user_set.isListApi()); - obj.setListSymbols(user_set.isListSymbols()); - - if (user_set.getAssetIconPath().isSet) - obj.setAssetIconExtractPath(user_set.getAssetIconPath().var); - if (user_set.getAssetNacpPath().isSet) - obj.setAssetNacpExtractPath(user_set.getAssetNacpPath().var); - - if (user_set.getFsPath().isSet) - obj.setAssetRomfsExtractPath(user_set.getFsPath().var); - obj.setAssetListFs(user_set.isListFs()); - - obj.process(); - } - else if (user_set.getFileType() == FILE_NACP) - { - NacpProcess obj; - - obj.setInputFile(inputFile); - obj.setCliOutputMode(user_set.getCliOutputMode()); - obj.setVerifyMode(user_set.isVerifyFile()); - - obj.process(); - } - else if (user_set.getFileType() == FILE_INI) - { - IniProcess obj; - - obj.setInputFile(inputFile); - obj.setCliOutputMode(user_set.getCliOutputMode()); - obj.setVerifyMode(user_set.isVerifyFile()); - - if (user_set.getKipExtractPath().isSet) - obj.setKipExtractPath(user_set.getKipExtractPath().var); - - obj.process(); - } - else if (user_set.getFileType() == FILE_KIP) - { - KipProcess obj; - - obj.setInputFile(inputFile); - obj.setCliOutputMode(user_set.getCliOutputMode()); - obj.setVerifyMode(user_set.isVerifyFile()); - - obj.process(); - } - else if (user_set.getFileType() == FILE_PKI_CERT) - { - PkiCertProcess obj; - - obj.setInputFile(inputFile); - obj.setKeyCfg(user_set.getKeyCfg()); - obj.setCliOutputMode(user_set.getCliOutputMode()); - obj.setVerifyMode(user_set.isVerifyFile()); - - obj.process(); - } - else if (user_set.getFileType() == FILE_ES_TIK) - { - EsTikProcess obj; - - obj.setInputFile(inputFile); - obj.setKeyCfg(user_set.getKeyCfg()); - obj.setCertificateChain(user_set.getCertificateChain()); - obj.setCliOutputMode(user_set.getCliOutputMode()); - obj.setVerifyMode(user_set.isVerifyFile()); - - obj.process(); - } - else if (user_set.getFileType() == FILE_HB_ASSET) - { - AssetProcess obj; - - obj.setInputFile(inputFile); - obj.setCliOutputMode(user_set.getCliOutputMode()); - obj.setVerifyMode(user_set.isVerifyFile()); - - if (user_set.getAssetIconPath().isSet) - obj.setIconExtractPath(user_set.getAssetIconPath().var); - if (user_set.getAssetNacpPath().isSet) - obj.setNacpExtractPath(user_set.getAssetNacpPath().var); - - if (user_set.getFsPath().isSet) - obj.setRomfsExtractPath(user_set.getFsPath().var); - obj.setListFs(user_set.isListFs()); - - obj.process(); - } - else - { - throw fnd::Exception("main", "Unhandled file type"); - } - } - catch (const fnd::Exception& e) { - printf("\n\n%s\n", e.what()); - } - return 0; +#include +#include +#include +#include +#include "UserSettings.h" +#include "GameCardProcess.h" +#include "PfsProcess.h" +#include "RomfsProcess.h" +#include "NcaProcess.h" +#include "MetaProcess.h" +#include "CnmtProcess.h" +#include "NsoProcess.h" +#include "NroProcess.h" +#include "NacpProcess.h" +#include "IniProcess.h" +#include "KipProcess.h" +#include "PkiCertProcess.h" +#include "EsTikProcess.h" +#include "AssetProcess.h" + +#ifdef _WIN32 +int wmain(int argc, wchar_t** argv) +#else +int main(int argc, char** argv) +#endif +{ + std::vector args; + for (size_t i = 0; i < (size_t)argc; i++) + { +#ifdef _WIN32 + args.push_back(fnd::StringConv::ConvertChar16ToChar8(std::u16string((char16_t*)argv[i]))); +#else + args.push_back(argv[i]); +#endif + } + + UserSettings user_set; + try { + user_set.parseCmdArgs(args); + + fnd::SharedPtr inputFile(new fnd::SimpleFile(user_set.getInputPath(), fnd::SimpleFile::Read)); + + if (user_set.getFileType() == FILE_GC) + { + GameCardProcess obj; + + obj.setInputFile(inputFile); + + obj.setKeyCfg(user_set.getKeyCfg()); + obj.setCliOutputMode(user_set.getCliOutputMode()); + obj.setVerifyMode(user_set.isVerifyFile()); + + if (user_set.getXciUpdatePath().isSet) + obj.setPartitionForExtract(nn::hac::gc::kUpdatePartitionStr, user_set.getXciUpdatePath().var); + if (user_set.getXciLogoPath().isSet) + obj.setPartitionForExtract(nn::hac::gc::kLogoPartitionStr, user_set.getXciLogoPath().var); + if (user_set.getXciNormalPath().isSet) + obj.setPartitionForExtract(nn::hac::gc::kNormalPartitionStr, user_set.getXciNormalPath().var); + if (user_set.getXciSecurePath().isSet) + obj.setPartitionForExtract(nn::hac::gc::kSecurePartitionStr, user_set.getXciSecurePath().var); + obj.setListFs(user_set.isListFs()); + + obj.process(); + } + else if (user_set.getFileType() == FILE_PARTITIONFS || user_set.getFileType() == FILE_NSP) + { + PfsProcess obj; + + obj.setInputFile(inputFile); + obj.setCliOutputMode(user_set.getCliOutputMode()); + obj.setVerifyMode(user_set.isVerifyFile()); + + if (user_set.getFsPath().isSet) + obj.setExtractPath(user_set.getFsPath().var); + obj.setListFs(user_set.isListFs()); + + obj.process(); + } + else if (user_set.getFileType() == FILE_ROMFS) + { + RomfsProcess obj; + + obj.setInputFile(inputFile); + obj.setCliOutputMode(user_set.getCliOutputMode()); + obj.setVerifyMode(user_set.isVerifyFile()); + + if (user_set.getFsPath().isSet) + obj.setExtractPath(user_set.getFsPath().var); + obj.setListFs(user_set.isListFs()); + + obj.process(); + } + else if (user_set.getFileType() == FILE_NCA) + { + NcaProcess obj; + + obj.setInputFile(inputFile); + obj.setKeyCfg(user_set.getKeyCfg()); + obj.setCliOutputMode(user_set.getCliOutputMode()); + obj.setVerifyMode(user_set.isVerifyFile()); + + + if (user_set.getNcaPart0Path().isSet) + obj.setPartition0ExtractPath(user_set.getNcaPart0Path().var); + if (user_set.getNcaPart1Path().isSet) + obj.setPartition1ExtractPath(user_set.getNcaPart1Path().var); + if (user_set.getNcaPart2Path().isSet) + obj.setPartition2ExtractPath(user_set.getNcaPart2Path().var); + if (user_set.getNcaPart3Path().isSet) + obj.setPartition3ExtractPath(user_set.getNcaPart3Path().var); + obj.setListFs(user_set.isListFs()); + + obj.process(); + } + else if (user_set.getFileType() == FILE_META) + { + MetaProcess obj; + + obj.setInputFile(inputFile); + obj.setKeyCfg(user_set.getKeyCfg()); + obj.setCliOutputMode(user_set.getCliOutputMode()); + obj.setVerifyMode(user_set.isVerifyFile()); + + obj.process(); + } + else if (user_set.getFileType() == FILE_CNMT) + { + CnmtProcess obj; + + obj.setInputFile(inputFile); + obj.setCliOutputMode(user_set.getCliOutputMode()); + obj.setVerifyMode(user_set.isVerifyFile()); + + obj.process(); + } + else if (user_set.getFileType() == FILE_NSO) + { + NsoProcess obj; + + obj.setInputFile(inputFile); + obj.setCliOutputMode(user_set.getCliOutputMode()); + obj.setVerifyMode(user_set.isVerifyFile()); + + obj.setInstructionType(user_set.getInstType()); + obj.setListApi(user_set.isListApi()); + obj.setListSymbols(user_set.isListSymbols()); + + obj.process(); + } + else if (user_set.getFileType() == FILE_NRO) + { + NroProcess obj; + + obj.setInputFile(inputFile); + obj.setCliOutputMode(user_set.getCliOutputMode()); + obj.setVerifyMode(user_set.isVerifyFile()); + + obj.setInstructionType(user_set.getInstType()); + obj.setListApi(user_set.isListApi()); + obj.setListSymbols(user_set.isListSymbols()); + + if (user_set.getAssetIconPath().isSet) + obj.setAssetIconExtractPath(user_set.getAssetIconPath().var); + if (user_set.getAssetNacpPath().isSet) + obj.setAssetNacpExtractPath(user_set.getAssetNacpPath().var); + + if (user_set.getFsPath().isSet) + obj.setAssetRomfsExtractPath(user_set.getFsPath().var); + obj.setAssetListFs(user_set.isListFs()); + + obj.process(); + } + else if (user_set.getFileType() == FILE_NACP) + { + NacpProcess obj; + + obj.setInputFile(inputFile); + obj.setCliOutputMode(user_set.getCliOutputMode()); + obj.setVerifyMode(user_set.isVerifyFile()); + + obj.process(); + } + else if (user_set.getFileType() == FILE_INI) + { + IniProcess obj; + + obj.setInputFile(inputFile); + obj.setCliOutputMode(user_set.getCliOutputMode()); + obj.setVerifyMode(user_set.isVerifyFile()); + + if (user_set.getKipExtractPath().isSet) + obj.setKipExtractPath(user_set.getKipExtractPath().var); + + obj.process(); + } + else if (user_set.getFileType() == FILE_KIP) + { + KipProcess obj; + + obj.setInputFile(inputFile); + obj.setCliOutputMode(user_set.getCliOutputMode()); + obj.setVerifyMode(user_set.isVerifyFile()); + + obj.process(); + } + else if (user_set.getFileType() == FILE_PKI_CERT) + { + PkiCertProcess obj; + + obj.setInputFile(inputFile); + obj.setKeyCfg(user_set.getKeyCfg()); + obj.setCliOutputMode(user_set.getCliOutputMode()); + obj.setVerifyMode(user_set.isVerifyFile()); + + obj.process(); + } + else if (user_set.getFileType() == FILE_ES_TIK) + { + EsTikProcess obj; + + obj.setInputFile(inputFile); + obj.setKeyCfg(user_set.getKeyCfg()); + obj.setCertificateChain(user_set.getCertificateChain()); + obj.setCliOutputMode(user_set.getCliOutputMode()); + obj.setVerifyMode(user_set.isVerifyFile()); + + obj.process(); + } + else if (user_set.getFileType() == FILE_HB_ASSET) + { + AssetProcess obj; + + obj.setInputFile(inputFile); + obj.setCliOutputMode(user_set.getCliOutputMode()); + obj.setVerifyMode(user_set.isVerifyFile()); + + if (user_set.getAssetIconPath().isSet) + obj.setIconExtractPath(user_set.getAssetIconPath().var); + if (user_set.getAssetNacpPath().isSet) + obj.setNacpExtractPath(user_set.getAssetNacpPath().var); + + if (user_set.getFsPath().isSet) + obj.setRomfsExtractPath(user_set.getFsPath().var); + obj.setListFs(user_set.isListFs()); + + obj.process(); + } + else + { + throw fnd::Exception("main", "Unhandled file type"); + } + } + catch (const fnd::Exception& e) { + printf("\n\n%s\n", e.what()); + } + return 0; } \ No newline at end of file diff --git a/programs/nstool/source/version.h b/src/version.h similarity index 100% rename from programs/nstool/source/version.h rename to src/version.h