From f1edd1932e4b2d8dea2cfbce0395dec3782ed8f5 Mon Sep 17 00:00:00 2001 From: Kevin Froman Date: Wed, 30 Dec 2020 06:48:59 +0000 Subject: [PATCH 01/14] added work on faster and safer database for blocks and general KV --- src/filepaths/__init__.py | 2 + src/rinseoff/.gitignore | 435 +++++++++++++ src/rinseoff/.vscode/launch.json | 27 + src/rinseoff/.vscode/tasks.json | 42 ++ src/rinseoff/LICENSE.txt | 661 ++++++++++++++++++++ src/rinseoff/README.md | 58 ++ src/rinseoff/rinseoff/RinseOff.cs | 53 ++ src/rinseoff/rinseoff/rinseoff.csproj | 11 + src/rinseoff/rinseoffcli/RinseOffCLI.cs | 215 +++++++ src/rinseoff/rinseoffcli/rinseoffcli.csproj | 12 + src/rinseoff/tests/TestDecrypt.cs | 49 ++ src/rinseoff/tests/TestEncrypt.cs | 49 ++ src/rinseoff/tests/TestKeyGen.cs | 41 ++ src/rinseoff/tests/tests.csproj | 19 + src/safedb/__init__.py | 22 + src/safedb/securestring/__init__.py | 62 ++ tests/test_blocklist_class.py | 1 - tests/test_secure_string.py | 33 + 18 files changed, 1791 insertions(+), 1 deletion(-) create mode 100644 src/rinseoff/.gitignore create mode 100644 src/rinseoff/.vscode/launch.json create mode 100644 src/rinseoff/.vscode/tasks.json create mode 100644 src/rinseoff/LICENSE.txt create mode 100644 src/rinseoff/README.md create mode 100644 src/rinseoff/rinseoff/RinseOff.cs create mode 100644 src/rinseoff/rinseoff/rinseoff.csproj create mode 100644 src/rinseoff/rinseoffcli/RinseOffCLI.cs create mode 100644 src/rinseoff/rinseoffcli/rinseoffcli.csproj create mode 100644 src/rinseoff/tests/TestDecrypt.cs create mode 100644 src/rinseoff/tests/TestEncrypt.cs create mode 100644 src/rinseoff/tests/TestKeyGen.cs create mode 100644 src/rinseoff/tests/tests.csproj create mode 100644 src/safedb/__init__.py create mode 100644 src/safedb/securestring/__init__.py create mode 100644 tests/test_secure_string.py diff --git a/src/filepaths/__init__.py b/src/filepaths/__init__.py index ba205383..32330f6d 100644 --- a/src/filepaths/__init__.py +++ b/src/filepaths/__init__.py @@ -36,3 +36,5 @@ log_file = home + 'onionr.log' ephemeral_services_file = home + 'ephemeral-services.list' restarting_indicator = home + "is-restarting" + +secure_erase_key_file = home + "erase-key" diff --git a/src/rinseoff/.gitignore b/src/rinseoff/.gitignore new file mode 100644 index 00000000..6315c08e --- /dev/null +++ b/src/rinseoff/.gitignore @@ -0,0 +1,435 @@ +## 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 +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +tests/tests/* + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +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/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.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 +*.appxbundle +*.appxupload + +# 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 +*- Backup*.rdl + +# 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/ + +# CodeRush personal settings +.cr/personal + +# 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/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# JetBrains Rider +.idea/ +*.sln.iml + +## +## Visual Studio Code +## +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json diff --git a/src/rinseoff/.vscode/launch.json b/src/rinseoff/.vscode/launch.json new file mode 100644 index 00000000..2d29806c --- /dev/null +++ b/src/rinseoff/.vscode/launch.json @@ -0,0 +1,27 @@ +{ + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md + "version": "0.2.0", + "configurations": [ + { + "name": ".NET Core Launch (console)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/tests/bin/Debug/netcoreapp3.1/tests.dll", + "args": [], + "cwd": "${workspaceFolder}/tests", + // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console + "console": "internalConsole", + "stopAtEntry": false + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach", + "processId": "${command:pickProcess}" + } + ] +} \ No newline at end of file diff --git a/src/rinseoff/.vscode/tasks.json b/src/rinseoff/.vscode/tasks.json new file mode 100644 index 00000000..ab3984f9 --- /dev/null +++ b/src/rinseoff/.vscode/tasks.json @@ -0,0 +1,42 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/tests/tests.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "publish", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "${workspaceFolder}/tests/tests.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "watch", + "command": "dotnet", + "type": "process", + "args": [ + "watch", + "run", + "${workspaceFolder}/tests/tests.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + } + ] +} \ No newline at end of file diff --git a/src/rinseoff/LICENSE.txt b/src/rinseoff/LICENSE.txt new file mode 100644 index 00000000..be3f7b28 --- /dev/null +++ b/src/rinseoff/LICENSE.txt @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/src/rinseoff/README.md b/src/rinseoff/README.md new file mode 100644 index 00000000..e501cae8 --- /dev/null +++ b/src/rinseoff/README.md @@ -0,0 +1,58 @@ +

RinseOff

+ +RinseOff is a simple CLI utility written in C# to store data to a file and encrypt it using a keyfile. + +The name doesn't make a lot of sense, but it means you can "rinse" your data off by just overwriting a 32 byte key file instead of the normal "scrub" process of 1 or more passes over many files. + +It is mainly intended for scripts/apps to use. In the future I may make a FUSE wrapper so users can drop files into it. + +Internally it uses libsodium's secretbox and stores a unique nonce alongside the 32 byte key. + +# Build + +Build a standalone binary (change [runtime based on system](https://docs.microsoft.com/en-us/dotnet/core/rid-catalog)): + +`$ dotnet publish -p:PublishSingleFile=true --self-contained --runtime linux-x64` + +The binary will be somewhere like bin/Debug/[dotnet version]/[runtime version]/publish/rinseoffcli + +You can make a smaller binary by not bundling the runtime. + +Or you can just "run" the project file: `$ dotnet run --project rinseoffcli` + +# Usage + +## Generate your key file + +`$ rinseoffcli keygen /path/to/key` + +Store your key somewhere it can be securely erased (not flash storage if you can help it) [security.stackexchange.com/a/62591](https://security.stackexchange.com/a/62591) + +Be sure to make it accessible only to your user. + +## Encrypt your data + +`$ rinseoffcli store /path/to/output /path/to/key` + +Then input the data to store through stdin. + +## Load your data + +`$ rinseoffcli load /path/to/stored/data /path/to/key` + +If the key is valid, the plaintext will be outputted through stdout. + +## Securely erase data + +`$ shred /path/to/key` +`$ rm /path/to/datafile` + + +# Warnings: + +The point of this utility is to help with defense in depth and to be better than nothing. + +**This does not hold up to serious data recovery experts who could quite possibly recover your key file** + +If the OS pages or swaps your plaintext or duplicates your key, you are probably doomed. + diff --git a/src/rinseoff/rinseoff/RinseOff.cs b/src/rinseoff/rinseoff/RinseOff.cs new file mode 100644 index 00000000..6e51b901 --- /dev/null +++ b/src/rinseoff/rinseoff/RinseOff.cs @@ -0,0 +1,53 @@ +using System; +using Sodium; +using System.IO; +using System.Collections.Generic; + +/* + RinseOff - Encrypt or load data with a key file to help with secure erasure + Copyright (C) <2020> Kevin Froman + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +namespace rinseoff +{ + public class RinseOff + { + public static void generateKeyFile(string path){ + var key = Sodium.SodiumCore.GetRandomBytes(32); + File.WriteAllBytes(path, key); + } + + public static byte[] encrypt_secret_bytes(byte[] secret, byte[] key){ + byte[] nonce = Sodium.SecretBox.GenerateNonce(); + var ciphertext = SecretBox.Create(secret, nonce, key); + var combined = new List(); + combined.AddRange(nonce); + combined.AddRange(ciphertext); + return combined.ToArray(); + } + + public static byte[] decrypt_secret_bytes(byte[] ciphertext, byte[] key){ + var ciphertextList = new List(); + ciphertextList.AddRange(ciphertext); + return Sodium.SecretBox.Open( + ciphertextList.GetRange(24, ciphertextList.Count - 24).ToArray(), + ciphertextList.GetRange(0, 24).ToArray(), + key); + } + + + } +} diff --git a/src/rinseoff/rinseoff/rinseoff.csproj b/src/rinseoff/rinseoff/rinseoff.csproj new file mode 100644 index 00000000..14aac8b8 --- /dev/null +++ b/src/rinseoff/rinseoff/rinseoff.csproj @@ -0,0 +1,11 @@ + + + + net5.0 + + + + + + + diff --git a/src/rinseoff/rinseoffcli/RinseOffCLI.cs b/src/rinseoff/rinseoffcli/RinseOffCLI.cs new file mode 100644 index 00000000..91e62fc6 --- /dev/null +++ b/src/rinseoff/rinseoffcli/RinseOffCLI.cs @@ -0,0 +1,215 @@ +using System; +using System.IO; +using System.Collections.Generic; +using rinseoff; +/* + RinseOff - Encrypt or load data with a key file to help with secure erasure + Copyright (C) <2020> Kevin Froman + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +namespace rinseoffcli +{ + class Program + { + public static string version = "1.0.0"; + enum ErrorCode : byte + { + // Exit error codes indexed from 1 + InvaildArgs = 1, + NoDataFileFound, + NoPermissionToReadDataFile, + FailedToReadDataFile, + FailedToWriteDataFile, + InvalidKeyFileSize, + InvalidKeyFile, + KeyFileNotFound, + NoPermissionToWriteKeyFile, + FailedToReadKeyFile, + FailedToWriteKeyFile + } + + + static void showHelp(ErrorCode exitCode = ErrorCode.InvaildArgs){ + Console.WriteLine("RinseOff " + version + " High level secure-erasure utility"); + Console.WriteLine("For stdout output, specify 'stdout' as the data file for the store command"); + Console.WriteLine("Must specify keygen or store/load, then a file name followed by a key file.\nFormat: "); + Environment.Exit((int) exitCode); + } + static void validateArgCount(string[] args, int count){ + if (args.Length != count){ + stderrWrite("Invalid number of arguments"); + showHelp(ErrorCode.InvaildArgs); + } + } + static void stderrWrite(string msg){ + var stderrStream = Console.Error; + stderrStream.WriteLine(msg); + stderrStream.Flush(); + } + static void loadData(string filepath, string keypath){ + // Load in an encrypted file and use a key file to decrypt it, then log bytes back to stdout + byte[] plaintext = {}; + byte[] readBytes(string file){ + // Read bytes in from a file, exit with error message if not possible + byte[] bytesToRead = {}; + try{ + bytesToRead = File.ReadAllBytes(file); + } + catch(FileNotFoundException){ + stderrWrite(file + " is not found"); + Environment.Exit((int)ErrorCode.NoDataFileFound); + } + catch(UnauthorizedAccessException){ + stderrWrite("No permssion to read " + file); + Environment.Exit((int)ErrorCode.NoPermissionToReadDataFile); + } + catch(IOException){ + stderrWrite("Failed to read " + file); + Environment.Exit((int)ErrorCode.FailedToReadDataFile); + } + return bytesToRead; + } + var stdout = Console.OpenStandardOutput(); + try{ + // Decrypt a file using a key file + plaintext = RinseOff.decrypt_secret_bytes( + readBytes(filepath), + readBytes(keypath) + ); + } + catch(Sodium.Exceptions.KeyOutOfRangeException){ + stderrWrite("Keyfile is not appropriate size for key"); + Environment.Exit((int)ErrorCode.InvalidKeyFileSize); + } + catch(System.Security.Cryptography.CryptographicException){ + stderrWrite("Could not decrypt " + filepath + " with " + keypath); + Environment.Exit((int)ErrorCode.InvalidKeyFile); + } + // print the plaintext and exit + foreach(byte b in plaintext){ + stdout.WriteByte(b); + } + stdout.Flush(); + } + + static void storeData(string filepath, string keypath){ + byte[] encryptedInput = new byte[0]; + + void writeStdoutBytes(byte[] data){ + var stdout = Console.OpenStandardOutput(); + foreach (byte b in data){ + stdout.WriteByte(b); + } + stdout.Flush(); + } + + byte[] readUntilClose(){ + // Read binary from STDIN until close + var readData = new List(); + Stream inputStream = Console.OpenStandardInput(); + int inp; + while(true){ + inp = inputStream.ReadByte(); + if (inp != -1){ + readData.Add((byte) inp); + } + else{ + return readData.ToArray(); + } + } + } + // Encrypt stdin with keyfile data then write out to output file + try{ + encryptedInput = RinseOff.encrypt_secret_bytes(readUntilClose(), File.ReadAllBytes(keypath)); + } + catch(FileNotFoundException){ + stderrWrite("Key file " + keypath + " does not exist"); + Environment.Exit((int)ErrorCode.KeyFileNotFound); + } + catch(Sodium.Exceptions.KeyOutOfRangeException){ + stderrWrite("Keyfile is not appropriate size for key"); + Environment.Exit((int)ErrorCode.InvalidKeyFileSize); + } + catch(IOException){ + stderrWrite("Failed to read key file " + keypath); + Environment.Exit((int)ErrorCode.FailedToReadKeyFile); + } + if (filepath == "stdout"){ + writeStdoutBytes(encryptedInput); + return; + } + try{ + File.WriteAllBytes(filepath, encryptedInput); + } + catch(ArgumentNullException) + { + Environment.Exit(0); + } + catch(DirectoryNotFoundException){ + stderrWrite("Output path " + filepath + " not found"); + Environment.Exit((int)ErrorCode.NoDataFileFound); + } + catch(IOException){ + stderrWrite("Could not write to " + filepath); + Environment.Exit((int)ErrorCode.FailedToWriteDataFile); + } + } + static void Main(string[] args) + { + if (args.Length == 0){ + showHelp(); + } + var cmd = args[0].ToLower(); + switch(cmd){ + case "keygen": + validateArgCount(args, 2); + try{ + RinseOff.generateKeyFile(args[1]); + } + catch(UnauthorizedAccessException){ + stderrWrite("Cannot write to key file due to lack of perms " + args[1]); + Environment.Exit((int)ErrorCode.NoPermissionToWriteKeyFile); + } + catch(DirectoryNotFoundException){ + stderrWrite("Path not found " + args[1]); + Environment.Exit((int)ErrorCode.KeyFileNotFound); + } + catch(IOException){ + stderrWrite("Error writing keyfile " + args[1]); + Environment.Exit((int)ErrorCode.FailedToWriteKeyFile); + } + break; + case "store": + validateArgCount(args, 3); + storeData(args[1], args[2]); + break; + case "load": + validateArgCount(args, 3); + loadData(args[1], args[2]); + break; + default: + stderrWrite("Invalid command"); + showHelp(); + break; + case "help": + case "--help": + case "-h": + showHelp(); + break; + } + } + } +} diff --git a/src/rinseoff/rinseoffcli/rinseoffcli.csproj b/src/rinseoff/rinseoffcli/rinseoffcli.csproj new file mode 100644 index 00000000..99e84eb8 --- /dev/null +++ b/src/rinseoff/rinseoffcli/rinseoffcli.csproj @@ -0,0 +1,12 @@ + + + + + + + + Exe + net5.0 + + + diff --git a/src/rinseoff/tests/TestDecrypt.cs b/src/rinseoff/tests/TestDecrypt.cs new file mode 100644 index 00000000..520acf45 --- /dev/null +++ b/src/rinseoff/tests/TestDecrypt.cs @@ -0,0 +1,49 @@ +using NUnit.Framework; +using System.Text; +using System.Collections.Generic; +using Sodium; +using rinseoff; +/* + RinseOff - Encrypt or load data with a key file to help with secure erasure + Copyright (C) <2020> Kevin Froman + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ +namespace testDecrypted +{ + public class Tests + { + [SetUp] + public void Setup() + { + } + + [Test] + public void testDecrypted() + { + var key = Sodium.SecretBox.GenerateKey(); + var nonce = Sodium.SecretBox.GenerateNonce(); + var msg = Encoding.Default.GetBytes("hey"); + var encrypted = Sodium.SecretBox.Create(msg, nonce, key); + var combined = new List(); + combined.AddRange(nonce); + combined.AddRange(encrypted); + + Assert.AreEqual( + RinseOff.decrypt_secret_bytes(combined.ToArray(), key), + msg + ); + } + } +} \ No newline at end of file diff --git a/src/rinseoff/tests/TestEncrypt.cs b/src/rinseoff/tests/TestEncrypt.cs new file mode 100644 index 00000000..31244437 --- /dev/null +++ b/src/rinseoff/tests/TestEncrypt.cs @@ -0,0 +1,49 @@ +using NUnit.Framework; +using System.Text; +using System.Collections.Generic; +using rinseoff; +/* + RinseOff - Encrypt or load data with a key file to help with secure erasure + Copyright (C) <2020> Kevin Froman + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ +namespace testEncrypted +{ + public class Tests + { + [SetUp] + public void Setup() + { + } + + [Test] + public void TestEncrypt() + { + var key = Sodium.SecretBox.GenerateKey(); + var secret = Encoding.UTF8.GetBytes("Hello world"); + var encrypted = RinseOff.encrypt_secret_bytes(secret, key); + var encryptedList = new List(); + encryptedList.AddRange(encrypted); + + Assert.AreNotEqual(secret, encrypted); + var nonce = encryptedList.GetRange(0, 24).ToArray(); + var cipher = encryptedList.GetRange(24, encryptedList.Count - 24).ToArray(); + + var decrypted = Sodium.SecretBox.Open(cipher, nonce, key); + Assert.AreEqual(decrypted, secret); + + } + } +} \ No newline at end of file diff --git a/src/rinseoff/tests/TestKeyGen.cs b/src/rinseoff/tests/TestKeyGen.cs new file mode 100644 index 00000000..3940ff66 --- /dev/null +++ b/src/rinseoff/tests/TestKeyGen.cs @@ -0,0 +1,41 @@ +using NUnit.Framework; +using System.IO; +using rinseoff; +/* + RinseOff - Encrypt or load data with a key file to help with secure erasure + Copyright (C) <2020> Kevin Froman + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ +namespace tests +{ + public class Tests + { + [SetUp] + public void Setup() + { + } + + [Test] + public void TestKeyGenBasic() + { + var f = Path.GetTempFileName(); + RinseOff.generateKeyFile(f); + var k = File.ReadAllBytes(f); + Assert.IsTrue(k.Length == 32); + Assert.IsFalse(k[0] == k[1]); + File.Delete(f); + } + } +} \ No newline at end of file diff --git a/src/rinseoff/tests/tests.csproj b/src/rinseoff/tests/tests.csproj new file mode 100644 index 00000000..03bb7036 --- /dev/null +++ b/src/rinseoff/tests/tests.csproj @@ -0,0 +1,19 @@ + + + + net5.0 + + false + + + + + + + + + + + + + diff --git a/src/safedb/__init__.py b/src/safedb/__init__.py new file mode 100644 index 00000000..dd1f02f1 --- /dev/null +++ b/src/safedb/__init__.py @@ -0,0 +1,22 @@ +from typing import Union +from enum import Enum, auto + +import dbm + + + +class SafeDB: + def safe_get(key: Union[str, bytes]) -> bytes: + return + + def __enter__(self): + self.db = dbm.open(self.db_path, "c") + return self.db + + def __exit__(self): + self.db.close() + + def __init__(self, db_path: str, use_): + self.db_path = db_path + + diff --git a/src/safedb/securestring/__init__.py b/src/safedb/securestring/__init__.py new file mode 100644 index 00000000..55cd753b --- /dev/null +++ b/src/safedb/securestring/__init__.py @@ -0,0 +1,62 @@ +import os +from typing import Union + +import subprocess + +from filepaths import secure_erase_key_file, app_root +import logger + +_rinseoff = f"{app_root}/src/rinseoff/rinseoffcli" + + + + +def generate_secure_string_key_file(): + if os.path.exists(secure_erase_key_file): + raise FileExistsError + + process = subprocess.Popen( + ["dotnet", "run", + "--project", _rinseoff, + "keygen", f"{secure_erase_key_file}"], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + res = process.communicate() + + if res[0]: + for line in res[0].decode('utf-8').split('\n'): + logger.info(line, terminal=True) + if res[1]: + logger.warn("Error when generating database encryption keyfile") + for line in res[1].decode('utf-8').split('\n'): + logger.error(line, terminal=True) + raise subprocess.CalledProcessError + + + +def secure_string_create(plaintext: Union[bytes, bytearray, str]) -> bytes: + """Create a "secure" string. Dont really rely on this, and dont use for comms + + This is just to make forensics a little harder""" + try: + plaintext = plaintext.encode('utf-8') + except AttributeError: + pass + + + process = subprocess.Popen( + ["dotnet", "run", + "--project", _rinseoff, + "store", "stdout", f"{secure_erase_key_file}"], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + stdin=subprocess.PIPE) + res = process.communicate(plaintext) + + if res[0] and not res[1]: + return res[0] + else: + logger.warn("Error when encrypting plaintext", terminal=True) + for line in res[1].decode('utf-8').split('\n'): + logger.error(line, terminal=True) + raise subprocess.CalledProcessError \ No newline at end of file diff --git a/tests/test_blocklist_class.py b/tests/test_blocklist_class.py index ce46905a..5f591b77 100644 --- a/tests/test_blocklist_class.py +++ b/tests/test_blocklist_class.py @@ -13,7 +13,6 @@ from onionrsetup import setup_config, setup_default_plugins createdirs.create_dirs() setup_config() -setup_config() setup_default_plugins() import config diff --git a/tests/test_secure_string.py b/tests/test_secure_string.py new file mode 100644 index 00000000..2bd2b61d --- /dev/null +++ b/tests/test_secure_string.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +import sys, os +sys.path.append(".") +sys.path.append("src/") +import uuid +TEST_DIR = 'testdata/%s-%s' % (uuid.uuid4(), os.path.basename(__file__)) + '/' +print("Test directory:", TEST_DIR) +os.environ["ONIONR_HOME"] = TEST_DIR +import unittest, json + +from utils import identifyhome, createdirs +from onionrsetup import setup_config +from safedb import securestring + +import filepaths +createdirs.create_dirs() +setup_config() + +class TestSecureString(unittest.TestCase): + def test_keyfile_gen(self): + assert not os.path.exists(filepaths.secure_erase_key_file) + securestring.generate_secure_string_key_file() + assert os.path.exists(filepaths.secure_erase_key_file) + + def test_secure_string_encrypt(self): + with open(filepaths.secure_erase_key_file, 'wb') as ef: + ef.write(os.urandom(32)) + pt = "hello world" + enc = securestring.secure_string_create(pt) + self.assertTrue(len(enc) > len(pt)) + + +unittest.main() From 2eb3e9366675113ef51fd70f3016eb7fb261fdf9 Mon Sep 17 00:00:00 2001 From: Kevin Froman Date: Wed, 30 Dec 2020 07:26:30 +0000 Subject: [PATCH 02/14] bump dependencies --- requirements.in | 2 +- requirements.txt | 36 +++++++++++++------- src/rinseoff/README.md | 1 + src/rinseoff/rinseoffcli/RinseOffCLI.cs | 44 +++++++++++++++---------- 4 files changed, 54 insertions(+), 29 deletions(-) diff --git a/requirements.in b/requirements.in index 4da3250f..a4809cdf 100644 --- a/requirements.in +++ b/requirements.in @@ -1,7 +1,7 @@ urllib3==1.25.11 requests==2.25.1 PyNaCl==1.4.0 -gevent==20.9.0 +gevent==20.12.1 Flask==1.1.2 PySocks==1.7.1 stem==1.8.0 diff --git a/requirements.txt b/requirements.txt index 865d9951..951e212a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -66,17 +66,31 @@ flask==1.1.2 \ --hash=sha256:4efa1ae2d7c9865af48986de8aeb8504bf32c7f3d6fdc9353d34b21f4b127060 \ --hash=sha256:8a4fdd8936eba2512e9c85df320a37e694c93945b33ef33c89946a340a238557 \ # via -r requirements.in -gevent==20.9.0 \ - --hash=sha256:1628a403fc9c3ea9b35924638a4d4fbe236f60ecdf4e22ed133fbbaf0bc7cb6b \ - --hash=sha256:2269574444113cb4ca1c1808ab9460a87fe25e1c34a6e36d975d4af46e4afff9 \ - --hash=sha256:324808a8558c733f7a9734525483795d52ca3bbd5662b24b361d81c075414b1f \ - --hash=sha256:5f6d48051d336561ec08995431ee4d265ac723a64bba99cc58c3eb1a4d4f5c8d \ - --hash=sha256:a8733a01974433d91308f8c44fa6cc13428b15bb39d46540657e260ff8852cb1 \ - --hash=sha256:adbb267067f56696b2babced3d0856aa39dcf14b8ccd2dffa1fab587b00c6f80 \ - --hash=sha256:b07fcbca3e819296979d82fac3d8b44f0d5ced57b9a04dffcfd194da99c8eb2d \ - --hash=sha256:b2948566003a1030e47507755fe1f446995e8671c0c67571091539e01faf94cc \ - --hash=sha256:e11de4b4d107ca2f35000eb08e9c4c4621c153103b400f48a9ea95b96d8c7e0b \ - --hash=sha256:fb33dc1ab27557bccd64ad4bf81e68c8b0d780fe937b1e2c0814558798137229 \ +gevent==20.12.1 \ + --hash=sha256:0f9fa230c5878704b9e286ad5038bac3b70d293bf10e9efa8b2ae1d7d80e7e08 \ + --hash=sha256:19bd3fe60dec45fe6420b7772496950215f1b36701905876ba1644b6b2064163 \ + --hash=sha256:2d05f38a5ef1ebb7ceb692897674b11ba603914524765b989c65c020c7b08360 \ + --hash=sha256:4b0a5626c4e534d184cdf00d66f06de3885beafaaa5f7b98d47186ea175629a1 \ + --hash=sha256:4baecba0fd614e14dc1f3f8c35616cb248cdb893de576150ed1fc7fc66b8ba3d \ + --hash=sha256:60799fd7dcbb622f8435eb12436d48a8d27f8e7b3d23631e32ccc04ddd2097c2 \ + --hash=sha256:69ddc1767a02f68e71d5e0d3215aa4d28872187715627f71ff0eadd7b7a5e7f4 \ + --hash=sha256:7a808c63f065a303bbbe87c5c0754e06abb1e23e18752f418dce1eb3189cb43d \ + --hash=sha256:81e38ed46e21e0b00b930efce1a1ff46c7722ad83d84052f71a757f23cbed1c0 \ + --hash=sha256:895c76a89907d9d37fdfaf5321cb0fff0cba396f003bedb4f5fc13836da6f250 \ + --hash=sha256:89c583744f91052ae987356660f5ed0b8fc59a1230b051d6ccc10d37a155fe01 \ + --hash=sha256:99b68765767bb3e2244a66b012883899a6f17c23b6dc1cd80b793df341e15f08 \ + --hash=sha256:9d001fc899db6e140110ae7484e58cd74b0dfa5cee021a0347f00bb441ac78bd \ + --hash=sha256:b57586ad3fedf13d351d2559b70d6fe593c50400315d52bb3c072285da60fa37 \ + --hash=sha256:ba244028225ff8d3a58f344fcd16ab05b0e3642b34d81f51f7fa3c70761f6c34 \ + --hash=sha256:bf946a99e364ebcc95b82c794d5d1a67f13115adbefab7b9e12791f13184cfd5 \ + --hash=sha256:c3706a620e167c4bd007f16f113928324c4e07a7bae11d6d18d65f82abcd7a58 \ + --hash=sha256:c570a2e3100f758a5c2f9b993ecf870ee784390e44e1a292c361d6b32fb3ad4c \ + --hash=sha256:caec00914e8f21b2c77a29bbc2ef3abfeadf7515656e5451dfb14c2064733998 \ + --hash=sha256:e233ae153b586b61e492806d4cd1be2217de7441922c02053b67de14800bce96 \ + --hash=sha256:f020bfb34d57caa10029111be776524c378a4aac8417bc6fb1154b05e00fc220 \ + --hash=sha256:f3faf1834464f1b0731aa6346cd9f41029fa9e208d6ecbce4a736c19562c86aa \ + --hash=sha256:f857adbe1bf41e620d86173a53100f4ec328eba3089069a4815b3d9f4229dee8 \ + --hash=sha256:ffa1be13963db6aa55c50d2fd4a656c82f53a03a47e37aaa69e79a488123538d \ # via -r requirements.in greenlet==0.4.17 \ --hash=sha256:1023d7b43ca11264ab7052cb09f5635d4afdb43df55e0854498fc63070a0b206 \ diff --git a/src/rinseoff/README.md b/src/rinseoff/README.md index e501cae8..49aa8374 100644 --- a/src/rinseoff/README.md +++ b/src/rinseoff/README.md @@ -41,6 +41,7 @@ Then input the data to store through stdin. `$ rinseoffcli load /path/to/stored/data /path/to/key` If the key is valid, the plaintext will be outputted through stdout. +if data path is "stdin" it will be read from pipe according ## Securely erase data diff --git a/src/rinseoff/rinseoffcli/RinseOffCLI.cs b/src/rinseoff/rinseoffcli/RinseOffCLI.cs index 91e62fc6..adb64a71 100644 --- a/src/rinseoff/rinseoffcli/RinseOffCLI.cs +++ b/src/rinseoff/rinseoffcli/RinseOffCLI.cs @@ -24,7 +24,7 @@ namespace rinseoffcli { class Program { - public static string version = "1.0.0"; + public static string version = "2.0.0"; enum ErrorCode : byte { // Exit error codes indexed from 1 @@ -59,9 +59,26 @@ namespace rinseoffcli stderrStream.WriteLine(msg); stderrStream.Flush(); } + + static byte[] readUntilClose(){ + // Read binary from STDIN until close + var readData = new List(); + Stream inputStream = Console.OpenStandardInput(); + int inp; + while(true){ + inp = inputStream.ReadByte(); + if (inp != -1){ + readData.Add((byte) inp); + } + else{ + return readData.ToArray(); + } + } + } static void loadData(string filepath, string keypath){ // Load in an encrypted file and use a key file to decrypt it, then log bytes back to stdout byte[] plaintext = {}; + byte[] ciphertext = {}; byte[] readBytes(string file){ // Read bytes in from a file, exit with error message if not possible byte[] bytesToRead = {}; @@ -83,10 +100,17 @@ namespace rinseoffcli return bytesToRead; } var stdout = Console.OpenStandardOutput(); + + if (filepath.Equals("stdin")){ + ciphertext = readUntilClose(); + } + else{ + ciphertext = readBytes(filepath); + } try{ // Decrypt a file using a key file plaintext = RinseOff.decrypt_secret_bytes( - readBytes(filepath), + ciphertext, readBytes(keypath) ); } @@ -98,6 +122,7 @@ namespace rinseoffcli stderrWrite("Could not decrypt " + filepath + " with " + keypath); Environment.Exit((int)ErrorCode.InvalidKeyFile); } + ciphertext = null; // print the plaintext and exit foreach(byte b in plaintext){ stdout.WriteByte(b); @@ -116,21 +141,6 @@ namespace rinseoffcli stdout.Flush(); } - byte[] readUntilClose(){ - // Read binary from STDIN until close - var readData = new List(); - Stream inputStream = Console.OpenStandardInput(); - int inp; - while(true){ - inp = inputStream.ReadByte(); - if (inp != -1){ - readData.Add((byte) inp); - } - else{ - return readData.ToArray(); - } - } - } // Encrypt stdin with keyfile data then write out to output file try{ encryptedInput = RinseOff.encrypt_secret_bytes(readUntilClose(), File.ReadAllBytes(keypath)); From 9e01c65c0f7fa24f1b53b015491ba5eeb58c514b Mon Sep 17 00:00:00 2001 From: Kevin Froman Date: Wed, 30 Dec 2020 07:48:19 +0000 Subject: [PATCH 03/14] added work on faster and safer database for blocks and general KV --- src/safedb/securestring/__init__.py | 29 +++++++++++++++++++++++----- tests/test_secure_string.py | 30 ++++++++++++++++++++++++++--- 2 files changed, 51 insertions(+), 8 deletions(-) diff --git a/src/safedb/securestring/__init__.py b/src/safedb/securestring/__init__.py index 55cd753b..a78b2900 100644 --- a/src/safedb/securestring/__init__.py +++ b/src/safedb/securestring/__init__.py @@ -11,7 +11,7 @@ _rinseoff = f"{app_root}/src/rinseoff/rinseoffcli" -def generate_secure_string_key_file(): +def generate_key_file(): if os.path.exists(secure_erase_key_file): raise FileExistsError @@ -34,7 +34,7 @@ def generate_secure_string_key_file(): -def secure_string_create(plaintext: Union[bytes, bytearray, str]) -> bytes: +def protect_string(plaintext: Union[bytes, bytearray, str]) -> bytes: """Create a "secure" string. Dont really rely on this, and dont use for comms This is just to make forensics a little harder""" @@ -43,7 +43,6 @@ def secure_string_create(plaintext: Union[bytes, bytearray, str]) -> bytes: except AttributeError: pass - process = subprocess.Popen( ["dotnet", "run", "--project", _rinseoff, @@ -56,7 +55,27 @@ def secure_string_create(plaintext: Union[bytes, bytearray, str]) -> bytes: if res[0] and not res[1]: return res[0] else: - logger.warn("Error when encrypting plaintext", terminal=True) + logger.warn("Error when protecting string for database", terminal=True) for line in res[1].decode('utf-8').split('\n'): logger.error(line, terminal=True) - raise subprocess.CalledProcessError \ No newline at end of file + raise subprocess.CalledProcessError + + +def unprotect_string(ciphertext: Union[bytes, bytearray]) -> bytes: + process = subprocess.Popen( + ["dotnet", "run", + "--project", _rinseoff, + "load", "stdin", f"{secure_erase_key_file}"], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + stdin=subprocess.PIPE) + res = process.communicate(ciphertext) + + if res[0] and not res[1]: + return res[0] + else: + logger.warn( + "Error when decrypting ciphertext from database", terminal=True) + for line in res[1].decode('utf-8').split('\n'): + logger.error(line, terminal=True) + raise subprocess.CalledProcessError diff --git a/tests/test_secure_string.py b/tests/test_secure_string.py index 2bd2b61d..9fa6d191 100644 --- a/tests/test_secure_string.py +++ b/tests/test_secure_string.py @@ -11,23 +11,47 @@ import unittest, json from utils import identifyhome, createdirs from onionrsetup import setup_config from safedb import securestring +import subprocess +from nacl.secret import SecretBox import filepaths createdirs.create_dirs() setup_config() + +_rinseoff = f"{filepaths.app_root}/src/rinseoff/rinseoffcli" + class TestSecureString(unittest.TestCase): def test_keyfile_gen(self): assert not os.path.exists(filepaths.secure_erase_key_file) - securestring.generate_secure_string_key_file() + securestring.generate_key_file() assert os.path.exists(filepaths.secure_erase_key_file) - def test_secure_string_encrypt(self): + def test_protect_string(self): with open(filepaths.secure_erase_key_file, 'wb') as ef: ef.write(os.urandom(32)) pt = "hello world" - enc = securestring.secure_string_create(pt) + enc = securestring.protect_string(pt) self.assertTrue(len(enc) > len(pt)) + def test_unprotect_string(self): + key = os.urandom(32) + with open(filepaths.secure_erase_key_file, 'wb') as ef: + ef.write(key) + msg = b"test hello world" + box = SecretBox(key) + enc = box.encrypt(msg) + nonce = enc.nonce + enc = nonce + enc.ciphertext + p = subprocess.Popen( + ["dotnet", "run", + "--project", _rinseoff, + "load", "stdin", f"{filepaths.secure_erase_key_file}"], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + stdin=subprocess.PIPE) + res = p.communicate(enc) + self.assertTrue(res[0] == msg) + unittest.main() From 153d530f38f8733328290dda1f9c9e0d5b985193 Mon Sep 17 00:00:00 2001 From: Kevin Froman Date: Thu, 31 Dec 2020 03:25:05 +0000 Subject: [PATCH 04/14] added put/get from db --- src/safedb/__init__.py | 47 ++++++++++++++++++----- src/safedb/securestring/__init__.py | 39 +++++++++---------- tests/test_safedb.py | 59 +++++++++++++++++++++++++++++ 3 files changed, 114 insertions(+), 31 deletions(-) create mode 100644 tests/test_safedb.py diff --git a/src/safedb/__init__.py b/src/safedb/__init__.py index dd1f02f1..e7275ae2 100644 --- a/src/safedb/__init__.py +++ b/src/safedb/__init__.py @@ -1,22 +1,51 @@ from typing import Union from enum import Enum, auto - import dbm +from .securestring import generate_key_file, protect_string, unprotect_string + class SafeDB: - def safe_get(key: Union[str, bytes]) -> bytes: - return + """Wrapper around dbm to optionally encrypt db values.""" - def __enter__(self): - self.db = dbm.open(self.db_path, "c") - return self.db + def get(self, key: Union[str, bytes, bytearray]) -> bytes: + if self.protected: + return self.db_conn[key] + return unprotect_string(self.db_conn[key]) - def __exit__(self): - self.db.close() + def put( + self, key: [str, bytes, bytearray], value: [bytes, bytearray]): + if self.protected: + self.db_conn[key] = protect_string(value) + else: + self.db_conn[key] = value - def __init__(self, db_path: str, use_): + def close(self): + self.db_conn.close() + + def __init__(self, db_path: str, protected=True): self.db_path = db_path + self.db_conn = dbm.open(db_path, "c") + + try: + existing_protected_mode = self.db_conn['enc'] + if protected and existing_protected_mode != b'1': + raise ValueError( + "Cannot open unencrypted database with protected=True") + elif not protected and existing_protected_mode != b'0': + raise ValueError( + "Cannot open encrypted database in protected=False") + except KeyError: + if protected: + self.db_conn['enc'] = b'1' + else: + self.db_conn['enc'] = b'0' + try: + generate_key_file() + except FileExistsError: + pass + + self.protected = protected diff --git a/src/safedb/securestring/__init__.py b/src/safedb/securestring/__init__.py index a78b2900..0a6c7101 100644 --- a/src/safedb/securestring/__init__.py +++ b/src/safedb/securestring/__init__.py @@ -1,3 +1,12 @@ +"""Wrap RinseOff, a c# CLI tool for secure data erasure via a keyfile. + +Intended for encrypting database entries. + +It is quite slow since it spawns an external process, +but an ext process is necessary to keep the key out +of memory as much as possible +""" + import os from typing import Union @@ -9,29 +18,13 @@ import logger _rinseoff = f"{app_root}/src/rinseoff/rinseoffcli" - - def generate_key_file(): if os.path.exists(secure_erase_key_file): - raise FileExistsError - - process = subprocess.Popen( - ["dotnet", "run", - "--project", _rinseoff, - "keygen", f"{secure_erase_key_file}"], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE) - res = process.communicate() - - if res[0]: - for line in res[0].decode('utf-8').split('\n'): - logger.info(line, terminal=True) - if res[1]: - logger.warn("Error when generating database encryption keyfile") - for line in res[1].decode('utf-8').split('\n'): - logger.error(line, terminal=True) - raise subprocess.CalledProcessError + raise FileExistsError( + "Key file for rinseoff secure erase already exists") + with open(secure_erase_key_file, 'wb') as f: + f.write(os.urandom(32)) def protect_string(plaintext: Union[bytes, bytearray, str]) -> bytes: @@ -58,7 +51,8 @@ def protect_string(plaintext: Union[bytes, bytearray, str]) -> bytes: logger.warn("Error when protecting string for database", terminal=True) for line in res[1].decode('utf-8').split('\n'): logger.error(line, terminal=True) - raise subprocess.CalledProcessError + raise subprocess.CalledProcessError( + "Error protecting string") def unprotect_string(ciphertext: Union[bytes, bytearray]) -> bytes: @@ -78,4 +72,5 @@ def unprotect_string(ciphertext: Union[bytes, bytearray]) -> bytes: "Error when decrypting ciphertext from database", terminal=True) for line in res[1].decode('utf-8').split('\n'): logger.error(line, terminal=True) - raise subprocess.CalledProcessError + raise subprocess.CalledProcessError( + "Error unprotecting string") diff --git a/tests/test_safedb.py b/tests/test_safedb.py new file mode 100644 index 00000000..b54b867a --- /dev/null +++ b/tests/test_safedb.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +import sys, os +sys.path.append(".") +sys.path.append("src/") +import uuid +TEST_DIR = 'testdata/%s-%s' % (uuid.uuid4(), os.path.basename(__file__)) + '/' +print("Test directory:", TEST_DIR) +os.environ["ONIONR_HOME"] = TEST_DIR +import unittest, json +import dbm + +from utils import identifyhome, createdirs +from onionrsetup import setup_config +createdirs.create_dirs() +setup_config() +import safedb + +db_path = identifyhome.identify_home() + "test.db" + +def _remove_db(): + try: + os.remove(db_path) + except FileNotFoundError: + pass + +class TestSafeDB(unittest.TestCase): + def test_db_create_unprotected(self): + _remove_db() + db = safedb.SafeDB(db_path, protected=False) + db.close() + with dbm.open(db_path) as db: + self.assertEqual(db['enc'], b'0') + + def test_db_create_proteced(self): + _remove_db() + db = safedb.SafeDB(db_path, protected=True) + db.close() + with dbm.open(db_path) as db: + self.assertEqual(db['enc'], b'1') + + def test_db_open_protected(self): + _remove_db() + with dbm.open(db_path, 'c') as db: + db['enc'] = b'1' + db = safedb.SafeDB(db_path, protected=True) + db.close() + self.assertRaises(ValueError, safedb.SafeDB, db_path, protected=False) + + def test_db_open_unproteced(self): + _remove_db() + with dbm.open(db_path, 'c') as db: + db['enc'] = b'0' + db = safedb.SafeDB(db_path, protected=False) + db.close() + self.assertRaises(ValueError, safedb.SafeDB, db_path, protected=True) + + + +unittest.main() From 7ab330a7103c7f221a937cd85d109d2cebe6c146 Mon Sep 17 00:00:00 2001 From: Kevin Froman Date: Thu, 31 Dec 2020 03:59:26 +0000 Subject: [PATCH 05/14] added work on faster and safer database for blocks and general KV --- src/filepaths/__init__.py | 2 ++ src/safedb/__init__.py | 2 ++ src/safedb/securestring/__init__.py | 20 ++++++++++++++++++-- src/utils/createdirs.py | 3 ++- 4 files changed, 24 insertions(+), 3 deletions(-) diff --git a/src/filepaths/__init__.py b/src/filepaths/__init__.py index 32330f6d..e37270ed 100644 --- a/src/filepaths/__init__.py +++ b/src/filepaths/__init__.py @@ -38,3 +38,5 @@ ephemeral_services_file = home + 'ephemeral-services.list' restarting_indicator = home + "is-restarting" secure_erase_key_file = home + "erase-key" + +master_db_location = home + "database/" diff --git a/src/safedb/__init__.py b/src/safedb/__init__.py index e7275ae2..37cade5e 100644 --- a/src/safedb/__init__.py +++ b/src/safedb/__init__.py @@ -2,6 +2,8 @@ from typing import Union from enum import Enum, auto import dbm +from filenuke import nuke + from .securestring import generate_key_file, protect_string, unprotect_string diff --git a/src/safedb/securestring/__init__.py b/src/safedb/securestring/__init__.py index 0a6c7101..01731dde 100644 --- a/src/safedb/securestring/__init__.py +++ b/src/safedb/securestring/__init__.py @@ -1,4 +1,6 @@ -"""Wrap RinseOff, a c# CLI tool for secure data erasure via a keyfile. +"""Onionr - Private P2P Communication + +Wrap RinseOff, a c# CLI tool for secure data erasure via a keyfile. Intended for encrypting database entries. @@ -6,7 +8,6 @@ It is quite slow since it spawns an external process, but an ext process is necessary to keep the key out of memory as much as possible """ - import os from typing import Union @@ -14,6 +15,21 @@ import subprocess from filepaths import secure_erase_key_file, app_root import logger +""" +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +""" + _rinseoff = f"{app_root}/src/rinseoff/rinseoffcli" diff --git a/src/utils/createdirs.py b/src/utils/createdirs.py index d0590bf4..f819800b 100644 --- a/src/utils/createdirs.py +++ b/src/utils/createdirs.py @@ -36,7 +36,8 @@ def create_dirs(): order of the hardcoded list below, then trigger creation of DBs""" gen_dirs = [home, filepaths.block_data_location, - filepaths.contacts_location, filepaths.export_location] + filepaths.contacts_location, filepaths.export_location, + filepaths.master_db_location] for path in gen_dirs: if not os.path.exists(path): os.makedirs(path) From 8ddc38515d36166eed887eb0767282bb33b24fed Mon Sep 17 00:00:00 2001 From: Kevin Froman Date: Sat, 2 Jan 2021 01:29:14 +0000 Subject: [PATCH 06/14] added license boilerplate to safedb --- src/safedb/__init__.py | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/safedb/__init__.py b/src/safedb/__init__.py index 37cade5e..9e7b2157 100644 --- a/src/safedb/__init__.py +++ b/src/safedb/__init__.py @@ -1,11 +1,25 @@ +"""Onionr - Private P2P Communication. + +Create required Onionr directories +""" from typing import Union -from enum import Enum, auto import dbm -from filenuke import nuke - from .securestring import generate_key_file, protect_string, unprotect_string +""" +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +""" class SafeDB: From db641341c5d4fea33825d7a5c07a2a0570ede589 Mon Sep 17 00:00:00 2001 From: Kevin Froman Date: Sat, 16 Jan 2021 20:24:23 +0000 Subject: [PATCH 07/14] added blockio module directory --- src/blockio/__init__.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 src/blockio/__init__.py diff --git a/src/blockio/__init__.py b/src/blockio/__init__.py new file mode 100644 index 00000000..e69de29b From dc51c26b1325c4ce895c03538d0eb852f7caf518 Mon Sep 17 00:00:00 2001 From: Kevin Froman Date: Sun, 17 Jan 2021 00:39:32 +0000 Subject: [PATCH 08/14] added blockio doc for db keys --- docs/dev/blockio-keys.txt | 6 ++++++ src/blockio/store/__init__.py | 26 ++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 docs/dev/blockio-keys.txt create mode 100644 src/blockio/store/__init__.py diff --git a/docs/dev/blockio-keys.txt b/docs/dev/blockio-keys.txt new file mode 100644 index 00000000..46dd0a5e --- /dev/null +++ b/docs/dev/blockio-keys.txt @@ -0,0 +1,6 @@ +Blockio wraps safedb, the new key value database module + +This is how the keys are setup and what they are for: + +bl-{type}: list of hashes for blocks for every stored block type +{block hash}: block data diff --git a/src/blockio/store/__init__.py b/src/blockio/store/__init__.py new file mode 100644 index 00000000..101a8bc9 --- /dev/null +++ b/src/blockio/store/__init__.py @@ -0,0 +1,26 @@ +"""Onionr - Private P2P Communication. + +Store blocks and cache meta info such as block type +""" +import safedb +""" +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +""" + + +def store_block(block_data): + + # If Onionr daemon is running, we should use the client + # API server to store blocks, if not we can + From 9ed17f4fb65191d284fdddf8557a1457cdb9f35c Mon Sep 17 00:00:00 2001 From: Kevin Froman Date: Sun, 17 Jan 2021 00:40:04 +0000 Subject: [PATCH 09/14] work on removing communicator --- requirements.in | 3 +- requirements.txt | 78 +++++++++-------- src/apiservers/private/__init__.py | 22 ++--- src/blockio/__init__.py | 18 ++++ src/communicator/__init__.py | 85 +------------------ .../daemonlaunch/spawndaemonthreads.py | 55 ++++++++++++ src/safedb/__init__.py | 2 +- 7 files changed, 132 insertions(+), 131 deletions(-) diff --git a/requirements.in b/requirements.in index a4809cdf..ca6fd48a 100644 --- a/requirements.in +++ b/requirements.in @@ -14,4 +14,5 @@ psutil==5.8.0 filenuke==0.0.0 watchdog==1.0.2 ujson==4.0.1 -cffi==1.14.4 \ No newline at end of file +cffi==1.14.4 +onionrblocks==0.0.0 diff --git a/requirements.txt b/requirements.txt index 951e212a..447b8fbe 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,11 +2,11 @@ # This file is autogenerated by pip-compile # To update, run: # -# pip-compile --generate-hashes requirements.in +# pip-compile --generate-hashes --output-file=requirements.txt requirements.in # certifi==2018.11.29 \ --hash=sha256:47f9c83ef4c0c621eaef743f133f09fa8a74a9b75f037e8624f83bd1b6626cb7 \ - --hash=sha256:993f830721089fef441cdfeb4b2c8c9df86f0c63239f06bd025a76a7daddb033 \ + --hash=sha256:993f830721089fef441cdfeb4b2c8c9df86f0c63239f06bd025a76a7daddb033 # via requests cffi==1.14.4 \ --hash=sha256:00a1ba5e2e95684448de9b89888ccd02c98d512064b4cb987d48f4b40aa0421e \ @@ -44,27 +44,29 @@ cffi==1.14.4 \ --hash=sha256:ec80dc47f54e6e9a78181ce05feb71a0353854cc26999db963695f950b5fb375 \ --hash=sha256:f032b34669220030f905152045dfa27741ce1a6db3324a5bc0b96b6c7420c87b \ --hash=sha256:f60567825f791c6f8a592f3c6e3bd93dd2934e3f9dac189308426bd76b00ef3b \ - --hash=sha256:f803eaa94c2fcda012c047e62bc7a51b0bdabda1cad7a92a522694ea2d76e49f \ - # via -r requirements.in, pynacl + --hash=sha256:f803eaa94c2fcda012c047e62bc7a51b0bdabda1cad7a92a522694ea2d76e49f + # via + # -r requirements.in + # pynacl chardet==3.0.4 \ --hash=sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae \ - --hash=sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691 \ + --hash=sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691 # via requests click==7.0 \ --hash=sha256:2335065e6395b9e67ca716de5f7526736bfa6ceead690adf616d925bdc622b13 \ - --hash=sha256:5b94b49521f6456670fdb30cd82a4eca9412788a93fa6dd6df72c94d5a8ff2d7 \ + --hash=sha256:5b94b49521f6456670fdb30cd82a4eca9412788a93fa6dd6df72c94d5a8ff2d7 # via flask deadsimplekv==0.3.2 \ --hash=sha256:a725f4a9d1156ebb66b7535ac150006881e0365b715e34e3709214827b8b0c4c \ - --hash=sha256:df00262d26c3dcfecb710425a7413059480d8cf026216042d7cbffb8514818b2 \ + --hash=sha256:df00262d26c3dcfecb710425a7413059480d8cf026216042d7cbffb8514818b2 # via -r requirements.in filenuke==0.0.0 \ --hash=sha256:147011c0125121469cae0a8a7f4df399f470e54aa29a08f2d2c099bf0118dcee \ - --hash=sha256:c55535dcecfdb27c5f4ce664d46e115950b5429763b5db75c198053646177f8f \ + --hash=sha256:c55535dcecfdb27c5f4ce664d46e115950b5429763b5db75c198053646177f8f # via -r requirements.in flask==1.1.2 \ --hash=sha256:4efa1ae2d7c9865af48986de8aeb8504bf32c7f3d6fdc9353d34b21f4b127060 \ - --hash=sha256:8a4fdd8936eba2512e9c85df320a37e694c93945b33ef33c89946a340a238557 \ + --hash=sha256:8a4fdd8936eba2512e9c85df320a37e694c93945b33ef33c89946a340a238557 # via -r requirements.in gevent==20.12.1 \ --hash=sha256:0f9fa230c5878704b9e286ad5038bac3b70d293bf10e9efa8b2ae1d7d80e7e08 \ @@ -90,7 +92,7 @@ gevent==20.12.1 \ --hash=sha256:f020bfb34d57caa10029111be776524c378a4aac8417bc6fb1154b05e00fc220 \ --hash=sha256:f3faf1834464f1b0731aa6346cd9f41029fa9e208d6ecbce4a736c19562c86aa \ --hash=sha256:f857adbe1bf41e620d86173a53100f4ec328eba3089069a4815b3d9f4229dee8 \ - --hash=sha256:ffa1be13963db6aa55c50d2fd4a656c82f53a03a47e37aaa69e79a488123538d \ + --hash=sha256:ffa1be13963db6aa55c50d2fd4a656c82f53a03a47e37aaa69e79a488123538d # via -r requirements.in greenlet==0.4.17 \ --hash=sha256:1023d7b43ca11264ab7052cb09f5635d4afdb43df55e0854498fc63070a0b206 \ @@ -110,19 +112,19 @@ greenlet==0.4.17 \ --hash=sha256:ccd62f09f90b2730150d82f2f2ffc34d73c6ce7eac234aed04d15dc8a3023994 \ --hash=sha256:d3436110ca66fe3981031cc6aff8cc7a40d8411d173dde73ddaa5b8445385e2d \ --hash=sha256:e495096e3e2e8f7192afb6aaeba19babc4fb2bdf543d7b7fed59e00c1df7f170 \ - --hash=sha256:e66a824f44892bc4ec66c58601a413419cafa9cec895e63d8da889c8a1a4fa4a \ + --hash=sha256:e66a824f44892bc4ec66c58601a413419cafa9cec895e63d8da889c8a1a4fa4a # via gevent idna==2.7 \ --hash=sha256:156a6814fb5ac1fc6850fb002e0852d56c0c8d2531923a51032d1b70760e186e \ - --hash=sha256:684a38a6f903c1d71d6d5fac066b58d7768af4de2b832e426ec79c30daa94a16 \ + --hash=sha256:684a38a6f903c1d71d6d5fac066b58d7768af4de2b832e426ec79c30daa94a16 # via requests itsdangerous==1.1.0 \ --hash=sha256:321b033d07f2a4136d3ec762eac9f16a10ccd60f53c0c91af90217ace7ba1f19 \ - --hash=sha256:b12271b2047cb23eeb98c8b5622e2e5c5e9abd9784a153e9d8ef9cb4dd09d749 \ + --hash=sha256:b12271b2047cb23eeb98c8b5622e2e5c5e9abd9784a153e9d8ef9cb4dd09d749 # via flask jinja2==2.11.1 \ --hash=sha256:93187ffbc7808079673ef52771baa950426fd664d3aad1d0fa3e95644360e250 \ - --hash=sha256:b0eaf100007721b5c16c1fc1eecb87409464edc10469ddc9a22a27a99123be49 \ + --hash=sha256:b0eaf100007721b5c16c1fc1eecb87409464edc10469ddc9a22a27a99123be49 # via flask markupsafe==1.1.1 \ --hash=sha256:00bc623926325b26bb9605ae9eae8a215691f33cae5df11ca5424f06f2d1f473 \ @@ -157,11 +159,15 @@ markupsafe==1.1.1 \ --hash=sha256:cd5df75523866410809ca100dc9681e301e3c27567cf498077e8551b6d20e42f \ --hash=sha256:cdb132fc825c38e1aeec2c8aa9338310d29d337bebbd7baa06889d09a60a1fa2 \ --hash=sha256:e249096428b3ae81b08327a63a485ad0878de3fb939049038579ac0ef61e17e7 \ - --hash=sha256:e8313f01ba26fbbe36c7be1966a7b7424942f670f38e666995b88d012765b9be \ + --hash=sha256:e8313f01ba26fbbe36c7be1966a7b7424942f670f38e666995b88d012765b9be # via jinja2 niceware==0.2.1 \ --hash=sha256:0f8b192f2a1e800e068474f6e208be9c7e2857664b33a96f4045340de4e5c69c \ - --hash=sha256:cf2dc0e1567d36d067c61b32fed0f1b9c4534ed511f9eeead4ba548d03b5c9eb \ + --hash=sha256:cf2dc0e1567d36d067c61b32fed0f1b9c4534ed511f9eeead4ba548d03b5c9eb + # via -r requirements.in +onionrblocks==0.0.0 \ + --hash=sha256:0ad300c1f033b474f8c93ffc89f59ad4075073b45798f0992fdc6f27f4874db5 \ + --hash=sha256:8bab88b62e52b2c2a77589ca6e106483508f1d15c78928f343c9cf030403dc09 # via -r requirements.in psutil==5.8.0 \ --hash=sha256:0066a82f7b1b37d334e68697faba68e5ad5e858279fd6351c8ca6024e8d6ba64 \ @@ -191,10 +197,10 @@ psutil==5.8.0 \ --hash=sha256:ea313bb02e5e25224e518e4352af4bf5e062755160f77e4b1767dd5ccb65f876 \ --hash=sha256:ea372bcc129394485824ae3e3ddabe67dc0b118d262c568b4d2602a7070afdb0 \ --hash=sha256:f4634b033faf0d968bb9220dd1c793b897ab7f1189956e1aa9eae752527127d3 \ - --hash=sha256:fcc01e900c1d7bee2a37e5d6e4f9194760a93597c97fee89c4ae51701de03563 \ + --hash=sha256:fcc01e900c1d7bee2a37e5d6e4f9194760a93597c97fee89c4ae51701de03563 # via -r requirements.in pycparser==2.19 \ - --hash=sha256:a988718abfad80b6b157acce7bf130a30876d27603738ac39f140993246b25b3 \ + --hash=sha256:a988718abfad80b6b157acce7bf130a30876d27603738ac39f140993246b25b3 # via cffi pynacl==1.4.0 \ --hash=sha256:06cbb4d9b2c4bd3c8dc0d267416aaed79906e7b33f114ddbf0911969794b1cc4 \ @@ -212,30 +218,32 @@ pynacl==1.4.0 \ --hash=sha256:cd401ccbc2a249a47a3a1724c2918fcd04be1f7b54eb2a5a71ff915db0ac51c6 \ --hash=sha256:d452a6746f0a7e11121e64625109bc4468fc3100452817001dbe018bb8b08514 \ --hash=sha256:ea6841bc3a76fa4942ce00f3bda7d436fda21e2d91602b9e21b7ca9ecab8f3ff \ - --hash=sha256:f8851ab9041756003119368c1e6cd0b9c631f46d686b3904b18c0139f4419f80 \ + --hash=sha256:f8851ab9041756003119368c1e6cd0b9c631f46d686b3904b18c0139f4419f80 # via -r requirements.in pysocks==1.7.1 \ --hash=sha256:08e69f092cc6dbe92a0fdd16eeb9b9ffbc13cadfe5ca4c7bd92ffb078b293299 \ --hash=sha256:2725bd0a9925919b9b51739eea5f9e2bae91e83288108a9ad338b2e3a4435ee5 \ - --hash=sha256:3f8804571ebe159c380ac6de37643bb4685970655d3bba243530d6558b799aa0 \ + --hash=sha256:3f8804571ebe159c380ac6de37643bb4685970655d3bba243530d6558b799aa0 # via -r requirements.in requests==2.25.1 \ --hash=sha256:27973dd4a904a4f13b263a19c866c13b92a39ed1c964655f025f3f8d3d75b804 \ - --hash=sha256:c210084e36a42ae6b9219e00e48287def368a26d03a048ddad7bfee44f75871e \ - # via -r requirements.in, streamedrequests + --hash=sha256:c210084e36a42ae6b9219e00e48287def368a26d03a048ddad7bfee44f75871e + # via + # -r requirements.in + # streamedrequests six==1.12.0 \ --hash=sha256:3350809f0555b11f552448330d0b52d5f24c91a322ea4a15ef22629740f3761c \ - --hash=sha256:d16a0141ec1a18405cd4ce8b4613101da75da0e9a7aec5bdd4fa804d0e0eba73 \ + --hash=sha256:d16a0141ec1a18405cd4ce8b4613101da75da0e9a7aec5bdd4fa804d0e0eba73 # via pynacl stem==1.8.0 \ - --hash=sha256:a0b48ea6224e95f22aa34c0bc3415f0eb4667ddeae3dfb5e32a6920c185568c2 \ + --hash=sha256:a0b48ea6224e95f22aa34c0bc3415f0eb4667ddeae3dfb5e32a6920c185568c2 # via -r requirements.in streamedrequests==1.0.3 \ --hash=sha256:4388ffc0ee94dda719dafc4324b8ddd108cb2231ec59871de79e2592bf4eef0a \ - --hash=sha256:ee68417a1522e75c35b1b2d5f3b6f7e76a3a1a6c0ef5e0c573d08307910079d8 \ + --hash=sha256:ee68417a1522e75c35b1b2d5f3b6f7e76a3a1a6c0ef5e0c573d08307910079d8 # via -r requirements.in toomanyobjs==1.1.0 \ - --hash=sha256:99e27468f9dad19127be9e2fb086b42acd69aed9ad7e63cef74d6e4389be0534 \ + --hash=sha256:99e27468f9dad19127be9e2fb086b42acd69aed9ad7e63cef74d6e4389be0534 # via -r requirements.in ujson==4.0.1 \ --hash=sha256:078808c385036cba73cad96f498310c61e9b5ae5ac9ea01e7c3996ece544b556 \ @@ -258,16 +266,18 @@ ujson==4.0.1 \ --hash=sha256:c354c1617b0a4378b6279d0cd511b769500cf3fa7c42e8e004cbbbb6b4c2a875 \ --hash=sha256:c604024bd853b5df6be7d933e934da8dd139e6159564db7c55b92a9937678093 \ --hash=sha256:e7ab24942b2d57920d75b817b8eead293026db003247e26f99506bdad86c61b4 \ - --hash=sha256:f8a60928737a9a47e692fcd661ef2b5d75ba22c7c930025bd95e338f2a6e15bc \ + --hash=sha256:f8a60928737a9a47e692fcd661ef2b5d75ba22c7c930025bd95e338f2a6e15bc # via -r requirements.in unpaddedbase32==0.2.0 \ --hash=sha256:4aacee75f8fd6c8cf129842ecba45ca59c11bfb13dae19d86f32b48fa3715403 \ - --hash=sha256:b7b780c31d27d55e66abf6c221216a35690ee8892c2daacff7f2528e229bd9c3 \ + --hash=sha256:b7b780c31d27d55e66abf6c221216a35690ee8892c2daacff7f2528e229bd9c3 # via -r requirements.in urllib3==1.25.11 \ --hash=sha256:8d7eaa5a82a1cac232164990f04874c594c9453ec55eef02eab885aa02fc17a2 \ - --hash=sha256:f5321fbe4bf3fefa0efd0bfe7fb14e90909eb62a48ccda331726b4319897dd5e \ - # via -r requirements.in, requests + --hash=sha256:f5321fbe4bf3fefa0efd0bfe7fb14e90909eb62a48ccda331726b4319897dd5e + # via + # -r requirements.in + # requests watchdog==1.0.2 \ --hash=sha256:016b01495b9c55b5d4126ed8ae75d93ea0d99377084107c33162df52887cee18 \ --hash=sha256:101532b8db506559e52a9b5d75a308729b3f68264d930670e6155c976d0e52a0 \ @@ -285,15 +295,15 @@ watchdog==1.0.2 \ --hash=sha256:e7c73edef48f4ceeebb987317a67e0080e5c9228601ff67b3c4062fa020403c7 \ --hash=sha256:ee21aeebe6b3e51e4ba64564c94cee8dbe7438b9cb60f0bb350c4fa70d1b52c2 \ --hash=sha256:f1d0e878fd69129d0d68b87cee5d9543f20d8018e82998efb79f7e412d42154a \ - --hash=sha256:f84146f7864339c8addf2c2b9903271df21d18d2c721e9a77f779493234a82b5 \ + --hash=sha256:f84146f7864339c8addf2c2b9903271df21d18d2c721e9a77f779493234a82b5 # via -r requirements.in werkzeug==0.15.5 \ --hash=sha256:87ae4e5b5366da2347eb3116c0e6c681a0e939a33b2805e2c0cbd282664932c4 \ - --hash=sha256:a13b74dd3c45f758d4ebdb224be8f1ab8ef58b3c0ffc1783a8c7d9f4f50227e6 \ + --hash=sha256:a13b74dd3c45f758d4ebdb224be8f1ab8ef58b3c0ffc1783a8c7d9f4f50227e6 # via flask zope.event==4.4 \ --hash=sha256:69c27debad9bdacd9ce9b735dad382142281ac770c4a432b533d6d65c4614bcf \ - --hash=sha256:d8e97d165fd5a0997b45f5303ae11ea3338becfe68c401dd88ffd2113fe5cae7 \ + --hash=sha256:d8e97d165fd5a0997b45f5303ae11ea3338becfe68c401dd88ffd2113fe5cae7 # via gevent zope.interface==5.1.0 \ --hash=sha256:0103cba5ed09f27d2e3de7e48bb320338592e2fabc5ce1432cf33808eb2dfd8b \ @@ -335,7 +345,7 @@ zope.interface==5.1.0 \ --hash=sha256:ef739fe89e7f43fb6494a43b1878a36273e5924869ba1d866f752c5812ae8d58 \ --hash=sha256:f40db0e02a8157d2b90857c24d89b6310f9b6c3642369852cdc3b5ac49b92afc \ --hash=sha256:f68bf937f113b88c866d090fea0bc52a098695173fc613b055a17ff0cf9683b6 \ - --hash=sha256:fb55c182a3f7b84c1a2d6de5fa7b1a05d4660d866b91dbf8d74549c57a1499e8 \ + --hash=sha256:fb55c182a3f7b84c1a2d6de5fa7b1a05d4660d866b91dbf8d74549c57a1499e8 # via gevent # WARNING: The following packages were not pinned, but pip requires them to be diff --git a/src/apiservers/private/__init__.py b/src/apiservers/private/__init__.py index 657c30b7..8c0571a4 100644 --- a/src/apiservers/private/__init__.py +++ b/src/apiservers/private/__init__.py @@ -18,18 +18,18 @@ from . import register_private_blueprints import config from .. import public """ - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program. If not, see . +You should have received a copy of the GNU General Public License +along with this program. If not, see . """ @@ -50,7 +50,7 @@ class PrivateAPI: self.startTime = epoch.get_epoch() app = flask.Flask(__name__) - + bind_port = int(config.get('client.client.port', 59496)) self.bindPort = bind_port diff --git a/src/blockio/__init__.py b/src/blockio/__init__.py index e69de29b..72940344 100644 --- a/src/blockio/__init__.py +++ b/src/blockio/__init__.py @@ -0,0 +1,18 @@ +"""Onionr - Private P2P Communication. + +Wrap safedb for storing and fetching blocks +""" +""" +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +""" \ No newline at end of file diff --git a/src/communicator/__init__.py b/src/communicator/__init__.py index 9a84cc8b..43122111 100755 --- a/src/communicator/__init__.py +++ b/src/communicator/__init__.py @@ -8,19 +8,9 @@ import time import config import logger -import onionrpeers import onionrplugins as plugins -from . import onlinepeers -from . import uploadqueue -from communicatorutils import downloadblocks -from communicatorutils import lookupblocks -from communicatorutils import lookupadders -from communicatorutils import connectnewpeers from communicatorutils import uploadblocks -from communicatorutils import announcenode, deniableinserts -from communicatorutils import cooldownpeer -from communicatorutils import housekeeping -from communicatorutils import netcheck +from . import uploadqueue from onionrthreads import add_onionr_thread from onionrcommands.openwebinterface import get_url from netcontroller import NetController @@ -80,61 +70,6 @@ class OnionrCommunicatorDaemon: # extends our upload list and saves our list when Onionr exits uploadqueue.UploadQueue(self) - add_onionr_thread( - lookupblocks.lookup_blocks_from_communicator, - [self.shared_state], 25, 3) - - add_onionr_thread( - downloadblocks.download_blocks_from_communicator, - [self.shared_state], - config.get('timers.getBlocks', 10), 1) - - add_onionr_thread(onlinepeers.clear_offline_peer, [self.kv], 58) - - add_onionr_thread( - housekeeping.clean_old_blocks, [self.shared_state], 10, 1) - - # Discover new peers - add_onionr_thread( - lookupadders.lookup_new_peer_transports_with_communicator, - [shared_state], 60, 3) - - # Timer for adjusting which peers - # we actively communicate to at any given time, - # to avoid over-using peers - add_onionr_thread( - cooldownpeer.cooldown_peer, [self.shared_state], 30, 60) - - # Timer to read the upload queue and upload the entries to peers - add_onionr_thread( - uploadblocks.upload_blocks_from_communicator, - [self.shared_state], 5, 1) - - # This timer creates deniable blocks, - # in an attempt to further obfuscate block insertion metadata - if config.get('general.insert_deniable_blocks', True): - add_onionr_thread( - deniableinserts.insert_deniable_block, [], 180, 10) - - if config.get('transports.tor', True): - # Timer to check for connectivity, - # through Tor to various high-profile onion services - add_onionr_thread(netcheck.net_check, [shared_state], 500, 60) - - # Announce the public API server transport address - # to other nodes if security level allows - if config.get('general.security_level', 1) == 0 \ - and config.get('general.announce_node', True): - # Default to high security level incase config breaks - add_onionr_thread( - announcenode.announce_node, [self.shared_state], 600, 60) - else: - logger.debug('Will not announce node.') - - add_onionr_thread(onionrpeers.peer_cleanup, [], 300, 300) - - add_onionr_thread(housekeeping.clean_keys, [], 15, 1) - if config.get('general.use_bootstrap_list', True): bootstrappeers.add_bootstrap_list_to_peer_list( self.kv, [], db_only=True) @@ -169,24 +104,6 @@ class OnionrCommunicatorDaemon: logger.info( 'Goodbye. (Onionr is cleaning up, and will exit)', terminal=True) - def decrementThreadCount(self, threadName): - """Decrement amount of a thread name if more than zero. - - called when a function meant to be run in a thread ends - """ - try: - if self.threadCounts[threadName] > 0: - self.threadCounts[threadName] -= 1 - except KeyError: - pass - - def peerCleanup(self): - """This just calls onionrpeers.cleanupPeers. - - Remove dead or bad peers (offline too long, too slow)""" - onionrpeers.peer_cleanup() - self.decrementThreadCount('peerCleanup') - def getPeerProfileInstance(self, peer): """Gets a peer profile instance from the list of profiles""" for i in self.kv.get('peerProfiles'): diff --git a/src/onionrcommands/daemonlaunch/spawndaemonthreads.py b/src/onionrcommands/daemonlaunch/spawndaemonthreads.py index b186419b..09b6213d 100644 --- a/src/onionrcommands/daemonlaunch/spawndaemonthreads.py +++ b/src/onionrcommands/daemonlaunch/spawndaemonthreads.py @@ -2,6 +2,17 @@ from typing import TYPE_CHECKING from onionrthreads import add_onionr_thread from communicator.onlinepeers import get_online_peers +from communicatorutils import lookupblocks +from communicatorutils import downloadblocks +from communicator import onlinepeers +from communicatorutils import housekeeping +from communicatorutils import lookupadders +from communicatorutils import cooldownpeer +from communicatorutils import uploadblocks +from communicatorutils import announcenode, deniableinserts +from communicatorutils import netcheck +import onionrpeers +import config if TYPE_CHECKING: from deadsimplekv import DeadSimpleKV @@ -12,3 +23,47 @@ if TYPE_CHECKING: def spawn_client_threads(shared_state: 'TooMany'): kv: 'DeadSimpleKV' = shared_state.get_by_string('DeadSimpleKV') add_onionr_thread(get_online_peers, (shared_state,), 3, 1) + + add_onionr_thread( + lookupblocks.lookup_blocks_from_communicator, + [shared_state], 25, 3) + add_onionr_thread( + downloadblocks.download_blocks_from_communicator, + [shared_state], + config.get('timers.getBlocks', 10), 1) + add_onionr_thread(onlinepeers.clear_offline_peer, [kv], 58) + add_onionr_thread( + housekeeping.clean_old_blocks, [shared_state], 10, 1) + add_onionr_thread(housekeeping.clean_keys, [], 15, 1) + # Discover new peers + add_onionr_thread( + lookupadders.lookup_new_peer_transports_with_communicator, + [shared_state], 60, 3) + # Thread for adjusting which peers + # we actively communicate to at any given time, + # to avoid over-using peers + add_onionr_thread( + cooldownpeer.cooldown_peer, [shared_state], 30, 60) + # Thread to read the upload queue and upload the entries to peers + add_onionr_thread( + uploadblocks.upload_blocks_from_communicator, + [shared_state], 5, 1) + # This Thread creates deniable blocks, + # in an attempt to further obfuscate block insertion metadata + if config.get('general.insert_deniable_blocks', True): + add_onionr_thread( + deniableinserts.insert_deniable_block, [], 180, 10) + + if config.get('transports.tor', True): + # Timer to check for connectivity, + # through Tor to various high-profile onion services + add_onionr_thread(netcheck.net_check, [shared_state], 500, 60) + + # Announce the public API server transport address + # to other nodes if security level allows + if config.get('general.security_level', 1) == 0 \ + and config.get('general.announce_node', True): + # Default to high security level incase config breaks + add_onionr_thread( + announcenode.announce_node, [shared_state], 600, 60) + add_onionr_thread(onionrpeers.peer_cleanup, [], 300, 300) diff --git a/src/safedb/__init__.py b/src/safedb/__init__.py index 9e7b2157..ed23e126 100644 --- a/src/safedb/__init__.py +++ b/src/safedb/__init__.py @@ -40,7 +40,7 @@ class SafeDB: def close(self): self.db_conn.close() - def __init__(self, db_path: str, protected=True): + def __init__(self, db_path: str, protected=False): self.db_path = db_path self.db_conn = dbm.open(db_path, "c") From f5dfd16408cf9924ddc9c4db147313795178995b Mon Sep 17 00:00:00 2001 From: Kevin Froman Date: Sun, 17 Jan 2021 03:59:41 +0000 Subject: [PATCH 10/14] bump onionrblocks for missing kasten dependency --- requirements.in | 2 +- requirements.txt | 44 +++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/requirements.in b/requirements.in index ca6fd48a..1b32efe2 100644 --- a/requirements.in +++ b/requirements.in @@ -15,4 +15,4 @@ filenuke==0.0.0 watchdog==1.0.2 ujson==4.0.1 cffi==1.14.4 -onionrblocks==0.0.0 +onionrblocks==0.0.1 diff --git a/requirements.txt b/requirements.txt index 447b8fbe..394b808c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -126,6 +126,10 @@ jinja2==2.11.1 \ --hash=sha256:93187ffbc7808079673ef52771baa950426fd664d3aad1d0fa3e95644360e250 \ --hash=sha256:b0eaf100007721b5c16c1fc1eecb87409464edc10469ddc9a22a27a99123be49 # via flask +kasten==2.0.0 \ + --hash=sha256:14e2f3b271c0186f4d31c7438f2b9e9406cadf73549ba7003a3fd452604c35e8 \ + --hash=sha256:64cf38521fd5faf89abd71839a3dde8f687536c56c699d7adb3aa31af8c9c97c + # via onionrblocks markupsafe==1.1.1 \ --hash=sha256:00bc623926325b26bb9605ae9eae8a215691f33cae5df11ca5424f06f2d1f473 \ --hash=sha256:09027a7803a62ca78792ad89403b1b7a73a01c8cb65909cd876f7fcebd79b161 \ @@ -161,13 +165,47 @@ markupsafe==1.1.1 \ --hash=sha256:e249096428b3ae81b08327a63a485ad0878de3fb939049038579ac0ef61e17e7 \ --hash=sha256:e8313f01ba26fbbe36c7be1966a7b7424942f670f38e666995b88d012765b9be # via jinja2 +mimcvdf==1.1.0 \ + --hash=sha256:97a4ccdebb58352c64c268d2e57ef8817c9fe4ac3dcc922410bfcc72033f344a \ + --hash=sha256:ae47c79bfd6b7b76077c8ce3301a48a7c10a609d8a882e7bd785e2ef851ecd28 + # via kasten +msgpack==1.0.2 \ + --hash=sha256:0cb94ee48675a45d3b86e61d13c1e6f1696f0183f0715544976356ff86f741d9 \ + --hash=sha256:1026dcc10537d27dd2d26c327e552f05ce148977e9d7b9f1718748281b38c841 \ + --hash=sha256:26a1759f1a88df5f1d0b393eb582ec022326994e311ba9c5818adc5374736439 \ + --hash=sha256:2a5866bdc88d77f6e1370f82f2371c9bc6fc92fe898fa2dec0c5d4f5435a2694 \ + --hash=sha256:31c17bbf2ae5e29e48d794c693b7ca7a0c73bd4280976d408c53df421e838d2a \ + --hash=sha256:497d2c12426adcd27ab83144057a705efb6acc7e85957a51d43cdcf7f258900f \ + --hash=sha256:5a9ee2540c78659a1dd0b110f73773533ee3108d4e1219b5a15a8d635b7aca0e \ + --hash=sha256:8521e5be9e3b93d4d5e07cb80b7e32353264d143c1f072309e1863174c6aadb1 \ + --hash=sha256:87869ba567fe371c4555d2e11e4948778ab6b59d6cc9d8460d543e4cfbbddd1c \ + --hash=sha256:8ffb24a3b7518e843cd83538cf859e026d24ec41ac5721c18ed0c55101f9775b \ + --hash=sha256:92be4b12de4806d3c36810b0fe2aeedd8d493db39e2eb90742b9c09299eb5759 \ + --hash=sha256:9ea52fff0473f9f3000987f313310208c879493491ef3ccf66268eff8d5a0326 \ + --hash=sha256:a4355d2193106c7aa77c98fc955252a737d8550320ecdb2e9ac701e15e2943bc \ + --hash=sha256:a99b144475230982aee16b3d249170f1cccebf27fb0a08e9f603b69637a62192 \ + --hash=sha256:ac25f3e0513f6673e8b405c3a80500eb7be1cf8f57584be524c4fa78fe8e0c83 \ + --hash=sha256:b28c0876cce1466d7c2195d7658cf50e4730667196e2f1355c4209444717ee06 \ + --hash=sha256:b55f7db883530b74c857e50e149126b91bb75d35c08b28db12dcb0346f15e46e \ + --hash=sha256:b6d9e2dae081aa35c44af9c4298de4ee72991305503442a5c74656d82b581fe9 \ + --hash=sha256:c747c0cc08bd6d72a586310bda6ea72eeb28e7505990f342552315b229a19b33 \ + --hash=sha256:d6c64601af8f3893d17ec233237030e3110f11b8a962cb66720bf70c0141aa54 \ + --hash=sha256:d8167b84af26654c1124857d71650404336f4eb5cc06900667a493fc619ddd9f \ + --hash=sha256:de6bd7990a2c2dabe926b7e62a92886ccbf809425c347ae7de277067f97c2887 \ + --hash=sha256:e36a812ef4705a291cdb4a2fd352f013134f26c6ff63477f20235138d1d21009 \ + --hash=sha256:e89ec55871ed5473a041c0495b7b4e6099f6263438e0bd04ccd8418f92d5d7f2 \ + --hash=sha256:f3e6aaf217ac1c7ce1563cf52a2f4f5d5b1f64e8729d794165db71da57257f0c \ + --hash=sha256:f484cd2dca68502de3704f056fa9b318c94b1539ed17a4c784266df5d6978c87 \ + --hash=sha256:fae04496f5bc150eefad4e9571d1a76c55d021325dcd484ce45065ebbdd00984 \ + --hash=sha256:fe07bc6735d08e492a327f496b7850e98cb4d112c56df69b0c844dbebcbb47f6 + # via kasten niceware==0.2.1 \ --hash=sha256:0f8b192f2a1e800e068474f6e208be9c7e2857664b33a96f4045340de4e5c69c \ --hash=sha256:cf2dc0e1567d36d067c61b32fed0f1b9c4534ed511f9eeead4ba548d03b5c9eb # via -r requirements.in -onionrblocks==0.0.0 \ - --hash=sha256:0ad300c1f033b474f8c93ffc89f59ad4075073b45798f0992fdc6f27f4874db5 \ - --hash=sha256:8bab88b62e52b2c2a77589ca6e106483508f1d15c78928f343c9cf030403dc09 +onionrblocks==0.0.1 \ + --hash=sha256:719b83770e0afa3b165ad103c8e1234f9ec0274bffae5e8438dc26e66dce474d \ + --hash=sha256:972f91a8d21f76f4ab659bdc13b022d4bb46fa18a01298d4d8a6791228a006be # via -r requirements.in psutil==5.8.0 \ --hash=sha256:0066a82f7b1b37d334e68697faba68e5ad5e858279fd6351c8ca6024e8d6ba64 \ From ca37f6df9d8cfc24fb89b2348868ec10afa12c11 Mon Sep 17 00:00:00 2001 From: Kevin Froman Date: Sun, 17 Jan 2021 04:58:28 +0000 Subject: [PATCH 11/14] renamed old block api due to namespace conflict fix onboarding not using optimize cpu option --- docs/dev/blockio-keys.txt | 2 +- scripts/block-spammer.py | 6 +++--- scripts/show-blocks.py | 2 +- scripts/testblock.py | 4 ++-- src/__init__.py | 2 +- src/blockio/store/__init__.py | 15 +++++++++++---- src/communicatorutils/deniableinserts.py | 4 ++-- src/communicatorutils/downloadblocks/__init__.py | 6 +++--- .../downloadblocks/shoulddownload.py | 2 +- src/communicatorutils/housekeeping.py | 6 +++--- src/communicatorutils/lookupblocks.py | 4 ++-- src/communicatorutils/uploadblocks/__init__.py | 4 ++-- .../uploadblocks/mixmate/__init__.py | 2 +- src/coredb/blockmetadb/add.py | 2 +- src/httpapi/apiutils/getblockdata.py | 2 +- src/httpapi/insertblock.py | 4 ++-- src/httpapi/miscclientapi/getblocks.py | 2 +- src/httpapi/miscclientapi/motd/__init__.py | 4 ++-- src/httpapi/miscpublicapi/getblocks.py | 4 ++-- src/httpapi/miscpublicapi/upload.py | 2 +- src/httpapi/onionrsitesapi/__init__.py | 2 +- src/httpapi/onionrsitesapi/findsite.py | 2 +- src/httpapi/onionrsitesapi/sitefiles.py | 4 ++-- src/httpapi/sse/private/__init__.py | 2 +- src/lan/client/__init__.py | 2 +- src/lan/server/__init__.py | 2 +- src/{onionrblocks => oldblocks}/__init__.py | 0 src/{onionrblocks => oldblocks}/blockdecrypt.py | 0 src/{onionrblocks => oldblocks}/blockimporter.py | 2 +- src/{onionrblocks => oldblocks}/blocklist.py | 0 .../blockmetadata/__init__.py | 0 .../blockmetadata/fromdata.py | 0 .../blockmetadata/hasblock.py | 0 .../blockmetadata/process.py | 2 +- .../deleteplaintext.py | 0 .../insert/__init__.py | 0 src/{onionrblocks => oldblocks}/insert/main.py | 0 .../insert/timeinsert.py | 0 .../onionrblacklist.py | 0 src/{onionrblocks => oldblocks}/onionrblockapi.py | 4 ++-- src/{onionrblocks => oldblocks}/storagecounter.py | 0 src/onionrcommands/banblocks.py | 2 +- .../daemonlaunch/spawndaemonthreads.py | 1 + src/onionrcommands/filecommands.py | 4 ++-- src/onionrcommands/listsites.py | 2 +- src/onionrcommands/motdcreator.py | 4 ++-- src/onionrcommands/onionrstatistics.py | 2 +- src/onionrpeers/peercleanup.py | 4 ++-- src/onionrpeers/peerprofiles.py | 10 +++++----- src/onionrproofs/__init__.py | 2 +- src/onionrstorage/removeblock.py | 2 +- src/onionrstorage/setdata.py | 2 +- src/onionrutils/importnewblocks.py | 2 +- src/runtests/housekeeping.py | 2 +- src/runtests/inserttest.py | 4 ++-- src/runtests/lanservertest.py | 2 +- src/runtests/sneakernettest.py | 2 +- src/runtests/stresstest.py | 4 ++-- src/safedb/__init__.py | 11 ++++++++--- src/sneakernet/__init__.py | 2 +- src/utils/networkmerger.py | 2 +- static-data/default-plugins/circles/main.py | 8 ++++---- static-data/default-plugins/pms/loadinbox.py | 2 +- static-data/www/onboarding/onboarding.js | 1 + tests/test_blocklist_class.py | 2 +- tests/test_blocks.py | 8 ++++---- tests/test_default_config_json.py | 2 +- tests/test_safedb.py | 12 ++++++++++-- tests/test_storagecounter.py | 8 ++++---- tests/test_timeinsert.py | 4 ++-- 70 files changed, 118 insertions(+), 96 deletions(-) rename src/{onionrblocks => oldblocks}/__init__.py (100%) rename src/{onionrblocks => oldblocks}/blockdecrypt.py (100%) rename src/{onionrblocks => oldblocks}/blockimporter.py (98%) rename src/{onionrblocks => oldblocks}/blocklist.py (100%) rename src/{onionrblocks => oldblocks}/blockmetadata/__init__.py (100%) rename src/{onionrblocks => oldblocks}/blockmetadata/fromdata.py (100%) rename src/{onionrblocks => oldblocks}/blockmetadata/hasblock.py (100%) rename src/{onionrblocks => oldblocks}/blockmetadata/process.py (98%) rename src/{onionrblocks => oldblocks}/deleteplaintext.py (100%) rename src/{onionrblocks => oldblocks}/insert/__init__.py (100%) rename src/{onionrblocks => oldblocks}/insert/main.py (100%) rename src/{onionrblocks => oldblocks}/insert/timeinsert.py (100%) rename src/{onionrblocks => oldblocks}/onionrblacklist.py (100%) rename src/{onionrblocks => oldblocks}/onionrblockapi.py (99%) rename src/{onionrblocks => oldblocks}/storagecounter.py (100%) diff --git a/docs/dev/blockio-keys.txt b/docs/dev/blockio-keys.txt index 46dd0a5e..86ea16de 100644 --- a/docs/dev/blockio-keys.txt +++ b/docs/dev/blockio-keys.txt @@ -2,5 +2,5 @@ Blockio wraps safedb, the new key value database module This is how the keys are setup and what they are for: -bl-{type}: list of hashes for blocks for every stored block type +bl-{type}: bytes of hashes for each block type {block hash}: block data diff --git a/scripts/block-spammer.py b/scripts/block-spammer.py index 51ae6b37..629b3805 100755 --- a/scripts/block-spammer.py +++ b/scripts/block-spammer.py @@ -11,7 +11,7 @@ import os if not os.path.exists('onionr.sh'): os.chdir('../') sys.path.append("src/") -import onionrblocks +import oldblocks amount = int(input("Number of blocks:")) @@ -24,8 +24,8 @@ else: for i in range(amount): if expire: - print(onionrblocks.insert(data=os.urandom(32), expire=expire)) + print(oldblocks.insert(data=os.urandom(32), expire=expire)) else: - print(onionrblocks.insert(data=os.urandom(32))) + print(oldblocks.insert(data=os.urandom(32))) print(i, "done") diff --git a/scripts/show-blocks.py b/scripts/show-blocks.py index cfb3f5e3..e93ce2d4 100644 --- a/scripts/show-blocks.py +++ b/scripts/show-blocks.py @@ -6,7 +6,7 @@ if not os.path.exists('onionr.sh'): os.chdir('../') sys.path.append("src/") from coredb.blockmetadb import get_block_list -from onionrblocks.onionrblockapi import Block +from oldblocks.onionrblockapi import Block for bl in get_block_list(): bl_obj = Block(bl, decrypt=False) diff --git a/scripts/testblock.py b/scripts/testblock.py index f0085641..9967409b 100755 --- a/scripts/testblock.py +++ b/scripts/testblock.py @@ -5,8 +5,8 @@ import os if not os.path.exists('onionr.sh'): os.chdir('../') sys.path.append("src/") -import onionrblocks +import oldblocks expire = 600 -print(onionrblocks.insert(data=os.urandom(32), expire=expire)) +print(oldblocks.insert(data=os.urandom(32), expire=expire)) diff --git a/src/__init__.py b/src/__init__.py index 7ee2fd0e..c78a7478 100755 --- a/src/__init__.py +++ b/src/__init__.py @@ -70,7 +70,7 @@ createdirs.create_dirs() import bigbrother # noqa from onionrcommands import parser # noqa from onionrplugins import onionrevents as events # noqa -from onionrblocks.deleteplaintext import delete_plaintext_no_blacklist # noqa +from oldblocks.deleteplaintext import delete_plaintext_no_blacklist # noqa setup.setup_config() diff --git a/src/blockio/store/__init__.py b/src/blockio/store/__init__.py index 101a8bc9..251b361e 100644 --- a/src/blockio/store/__init__.py +++ b/src/blockio/store/__init__.py @@ -2,7 +2,13 @@ Store blocks and cache meta info such as block type """ -import safedb +from typing import TYPE_CHECKING, Union, NewType + +from safedb import DBProtectionOpeningModeError + +if TYPE_CHECKING: + from kasten import Kasten + from safedb import SafeDB """ 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 @@ -18,9 +24,10 @@ You should have received a copy of the GNU General Public License along with this program. If not, see . """ +RawBlock = NewType('RawBlock', bytes) -def store_block(block_data): - # If Onionr daemon is running, we should use the client - # API server to store blocks, if not we can +def store_block(block: Kasten, safe_db: SafeDB): + + safe_db.put(block.id, block.get_packed()) diff --git a/src/communicatorutils/deniableinserts.py b/src/communicatorutils/deniableinserts.py index 26c34163..aff6e2b2 100755 --- a/src/communicatorutils/deniableinserts.py +++ b/src/communicatorutils/deniableinserts.py @@ -5,7 +5,7 @@ Use the communicator to insert fake mail messages import secrets from etc import onionrvalues -import onionrblocks +import oldblocks """ 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 @@ -30,6 +30,6 @@ def insert_deniable_block(): # This assumes on the libsodium primitives to have key-privacy fakePeer = onionrvalues.DENIABLE_PEER_ADDRESS data = secrets.token_hex(secrets.randbelow(5120) + 1) - onionrblocks.insert(data, header='pm', encryptType='asym', + oldblocks.insert(data, header='pm', encryptType='asym', asymPeer=fakePeer, disableForward=True, meta={'subject': 'foo'}) diff --git a/src/communicatorutils/downloadblocks/__init__.py b/src/communicatorutils/downloadblocks/__init__.py index 08cf9a1e..9be16770 100755 --- a/src/communicatorutils/downloadblocks/__init__.py +++ b/src/communicatorutils/downloadblocks/__init__.py @@ -17,14 +17,14 @@ import onionrpeers from communicator import peeraction from communicator import onlinepeers -from onionrblocks import blockmetadata +from oldblocks import blockmetadata from onionrutils import validatemetadata from coredb import blockmetadb from onionrutils.localcommand import local_command import onionrcrypto import onionrstorage -from onionrblocks import onionrblacklist -from onionrblocks import storagecounter +from oldblocks import onionrblacklist +from oldblocks import storagecounter from . import shoulddownload """ This program is free software: you can redistribute it and/or modify diff --git a/src/communicatorutils/downloadblocks/shoulddownload.py b/src/communicatorutils/downloadblocks/shoulddownload.py index ddf11624..cd1282de 100644 --- a/src/communicatorutils/downloadblocks/shoulddownload.py +++ b/src/communicatorutils/downloadblocks/shoulddownload.py @@ -4,7 +4,7 @@ Check if a block should be downloaded (if we already have it or its blacklisted or not) """ from coredb import blockmetadb -from onionrblocks import onionrblacklist +from oldblocks import onionrblacklist """ 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 diff --git a/src/communicatorutils/housekeeping.py b/src/communicatorutils/housekeeping.py index a36f8556..212ca259 100755 --- a/src/communicatorutils/housekeeping.py +++ b/src/communicatorutils/housekeeping.py @@ -15,8 +15,8 @@ from onionrutils import epoch from coredb import blockmetadb, dbfiles import onionrstorage from onionrstorage import removeblock -from onionrblocks import onionrblacklist -from onionrblocks.storagecounter import StorageCounter +from oldblocks import onionrblacklist +from oldblocks.storagecounter import StorageCounter from etc.onionrvalues import DATABASE_LOCK_TIMEOUT from onionrproofs import hashMeetsDifficulty """ @@ -103,6 +103,6 @@ def clean_blocks_not_meeting_pow(shared_state): for block in block_list: if not hashMeetsDifficulty(block): logger.warn( - f"Deleting block {block} because it was stored" + + f"Deleting block {block} because it was stored" + "with a POW level smaller than current.", terminal=True) __purge_block(shared_state, block) diff --git a/src/communicatorutils/lookupblocks.py b/src/communicatorutils/lookupblocks.py index 99574b89..d8f73635 100755 --- a/src/communicatorutils/lookupblocks.py +++ b/src/communicatorutils/lookupblocks.py @@ -15,11 +15,11 @@ from onionrutils import stringvalidators, epoch from communicator import peeraction, onlinepeers from coredb.blockmetadb import get_block_list from utils import reconstructhash -from onionrblocks import onionrblacklist +from oldblocks import onionrblacklist import onionrexceptions import config from etc import onionrvalues -from onionrblocks.storagecounter import StorageCounter +from oldblocks.storagecounter import StorageCounter """ 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 diff --git a/src/communicatorutils/uploadblocks/__init__.py b/src/communicatorutils/uploadblocks/__init__.py index 8bf23be6..31db2955 100755 --- a/src/communicatorutils/uploadblocks/__init__.py +++ b/src/communicatorutils/uploadblocks/__init__.py @@ -13,8 +13,8 @@ from onionrtypes import UserID import logger from communicatorutils import proxypicker import onionrexceptions -from onionrblocks import onionrblockapi as block -from onionrblocks.blockmetadata.fromdata import get_block_metadata_from_data +from oldblocks import onionrblockapi as block +from oldblocks.blockmetadata.fromdata import get_block_metadata_from_data from onionrutils import stringvalidators, basicrequests from onionrutils.validatemetadata import validate_metadata from communicator import onlinepeers diff --git a/src/communicatorutils/uploadblocks/mixmate/__init__.py b/src/communicatorutils/uploadblocks/mixmate/__init__.py index 3e63ea99..9b235455 100644 --- a/src/communicatorutils/uploadblocks/mixmate/__init__.py +++ b/src/communicatorutils/uploadblocks/mixmate/__init__.py @@ -6,7 +6,7 @@ import time from typing import List import onionrtypes -from onionrblocks import onionrblockapi +from oldblocks import onionrblockapi from .pool import UploadPool from .pool import PoolFullException diff --git a/src/coredb/blockmetadb/add.py b/src/coredb/blockmetadb/add.py index ec1ab861..71194b4b 100644 --- a/src/coredb/blockmetadb/add.py +++ b/src/coredb/blockmetadb/add.py @@ -5,7 +5,7 @@ Add an entry to the block metadata database import sqlite3 import secrets from onionrutils import epoch -from onionrblocks import blockmetadata +from oldblocks import blockmetadata from etc import onionrvalues from .. import dbfiles from onionrexceptions import BlockMetaEntryExists diff --git a/src/httpapi/apiutils/getblockdata.py b/src/httpapi/apiutils/getblockdata.py index 9da1ee59..74988138 100644 --- a/src/httpapi/apiutils/getblockdata.py +++ b/src/httpapi/apiutils/getblockdata.py @@ -1,6 +1,6 @@ import ujson as json -from onionrblocks import onionrblockapi +from oldblocks import onionrblockapi from onionrutils import bytesconverter, stringvalidators import onionrexceptions class GetBlockData: diff --git a/src/httpapi/insertblock.py b/src/httpapi/insertblock.py index bafe41e1..db12d6ee 100644 --- a/src/httpapi/insertblock.py +++ b/src/httpapi/insertblock.py @@ -11,7 +11,7 @@ from flask import Blueprint, Response, request, g if TYPE_CHECKING: from deadsimplekv import DeadSimpleKV -import onionrblocks +import oldblocks from onionrcrypto import hashers from onionrutils import bytesconverter from onionrutils import mnemonickeys @@ -84,7 +84,7 @@ def client_api_insert_block(): disable_forward_secrecy = False threading.Thread( - target=onionrblocks.insert, args=(message,), + target=oldblocks.insert, args=(message,), kwargs={'header': bType, 'encryptType': encrypt_type, 'sign': sign, 'asymPeer': to, 'meta': meta, 'disableForward': disable_forward_secrecy}).start() diff --git a/src/httpapi/miscclientapi/getblocks.py b/src/httpapi/miscclientapi/getblocks.py index 4e7fd58e..18f4fc9f 100644 --- a/src/httpapi/miscclientapi/getblocks.py +++ b/src/httpapi/miscclientapi/getblocks.py @@ -18,7 +18,7 @@ along with this program. If not, see . ''' from flask import Blueprint, Response, abort -from onionrblocks import onionrblockapi +from oldblocks import onionrblockapi from .. import apiutils from onionrutils import stringvalidators from coredb import blockmetadb diff --git a/src/httpapi/miscclientapi/motd/__init__.py b/src/httpapi/miscclientapi/motd/__init__.py index ad57b91a..c467d097 100644 --- a/src/httpapi/miscclientapi/motd/__init__.py +++ b/src/httpapi/miscclientapi/motd/__init__.py @@ -3,7 +3,7 @@ from flask import Response import unpaddedbase32 from coredb import blockmetadb -import onionrblocks +import oldblocks from etc import onionrvalues import config from onionrutils import bytesconverter @@ -18,7 +18,7 @@ def get_motd()->Response: newest_time = 0 message = "No MOTD currently present." for x in motds: - bl = onionrblocks.onionrblockapi.Block(x) + bl = oldblocks.onionrblockapi.Block(x) if not bl.verifySig() or bl.signer != bytesconverter.bytes_to_str(unpaddedbase32.repad(bytesconverter.str_to_bytes(signer))): continue if not bl.isSigner(signer): continue if bl.claimedTime > newest_time: diff --git a/src/httpapi/miscpublicapi/getblocks.py b/src/httpapi/miscpublicapi/getblocks.py index cc64e6c9..95efc34f 100755 --- a/src/httpapi/miscpublicapi/getblocks.py +++ b/src/httpapi/miscpublicapi/getblocks.py @@ -8,8 +8,8 @@ import config from onionrutils import bytesconverter, stringvalidators from coredb import blockmetadb from utils import reconstructhash -from onionrblocks import BlockList -from onionrblocks.onionrblockapi import Block +from oldblocks import BlockList +from oldblocks.onionrblockapi import Block from .. import apiutils """ This program is free software: you can redistribute it and/or modify diff --git a/src/httpapi/miscpublicapi/upload.py b/src/httpapi/miscpublicapi/upload.py index 9e57f1e4..6535d624 100755 --- a/src/httpapi/miscpublicapi/upload.py +++ b/src/httpapi/miscpublicapi/upload.py @@ -10,7 +10,7 @@ from flask import abort from flask import g from onionrutils import localcommand -from onionrblocks import blockimporter +from oldblocks import blockimporter import onionrexceptions import logger import config diff --git a/src/httpapi/onionrsitesapi/__init__.py b/src/httpapi/onionrsitesapi/__init__.py index 9526aa76..2b431ce6 100644 --- a/src/httpapi/onionrsitesapi/__init__.py +++ b/src/httpapi/onionrsitesapi/__init__.py @@ -10,7 +10,7 @@ import unpaddedbase32 from flask import Blueprint, Response, request, abort -from onionrblocks import onionrblockapi +from oldblocks import onionrblockapi import onionrexceptions from onionrutils import stringvalidators from onionrutils import mnemonickeys diff --git a/src/httpapi/onionrsitesapi/findsite.py b/src/httpapi/onionrsitesapi/findsite.py index 6811ae4c..454d0131 100644 --- a/src/httpapi/onionrsitesapi/findsite.py +++ b/src/httpapi/onionrsitesapi/findsite.py @@ -10,7 +10,7 @@ import onionrexceptions from onionrutils import mnemonickeys from onionrutils import stringvalidators from coredb import blockmetadb -from onionrblocks.onionrblockapi import Block +from oldblocks.onionrblockapi import Block from onionrtypes import BlockHash """ diff --git a/src/httpapi/onionrsitesapi/sitefiles.py b/src/httpapi/onionrsitesapi/sitefiles.py index f9171926..c43fd897 100644 --- a/src/httpapi/onionrsitesapi/sitefiles.py +++ b/src/httpapi/onionrsitesapi/sitefiles.py @@ -10,8 +10,8 @@ import os import unpaddedbase32 from coredb import blockmetadb -from onionrblocks import onionrblockapi -from onionrblocks import insert +from oldblocks import onionrblockapi +from oldblocks import insert # Import types. Just for type hiting from onionrtypes import UserID, DeterministicKeyPassphrase, BlockHash diff --git a/src/httpapi/sse/private/__init__.py b/src/httpapi/sse/private/__init__.py index 4213fd4f..625ec89f 100644 --- a/src/httpapi/sse/private/__init__.py +++ b/src/httpapi/sse/private/__init__.py @@ -9,7 +9,7 @@ from gevent import sleep import gevent import ujson -from onionrblocks.onionrblockapi import Block +from oldblocks.onionrblockapi import Block from coredb.dbfiles import block_meta_db from coredb.blockmetadb import get_block_list from onionrutils.epoch import get_epoch diff --git a/src/lan/client/__init__.py b/src/lan/client/__init__.py index 6b1dab66..48bc8609 100644 --- a/src/lan/client/__init__.py +++ b/src/lan/client/__init__.py @@ -9,7 +9,7 @@ from typing import Set from onionrtypes import LANIP import logger from coredb.blockmetadb import get_block_list -from onionrblocks.blockimporter import import_block_from_data +from oldblocks.blockimporter import import_block_from_data import onionrexceptions from ..server import ports from onionrproofs import hashMeetsDifficulty diff --git a/src/lan/server/__init__.py b/src/lan/server/__init__.py index ce52a8c2..acbb183c 100644 --- a/src/lan/server/__init__.py +++ b/src/lan/server/__init__.py @@ -12,7 +12,7 @@ from flask import Response from flask import request from flask import abort -from onionrblocks.onionrblockapi import Block +from oldblocks.onionrblockapi import Block from httpapi.fdsafehandler import FDSafeHandler from netcontroller import get_open_port import config diff --git a/src/onionrblocks/__init__.py b/src/oldblocks/__init__.py similarity index 100% rename from src/onionrblocks/__init__.py rename to src/oldblocks/__init__.py diff --git a/src/onionrblocks/blockdecrypt.py b/src/oldblocks/blockdecrypt.py similarity index 100% rename from src/onionrblocks/blockdecrypt.py rename to src/oldblocks/blockdecrypt.py diff --git a/src/onionrblocks/blockimporter.py b/src/oldblocks/blockimporter.py similarity index 98% rename from src/onionrblocks/blockimporter.py rename to src/oldblocks/blockimporter.py index 29fde84f..9c8b3b74 100755 --- a/src/onionrblocks/blockimporter.py +++ b/src/oldblocks/blockimporter.py @@ -10,7 +10,7 @@ import logger from onionrutils import validatemetadata from onionrutils import bytesconverter from coredb import blockmetadb -from onionrblocks import blockmetadata +from oldblocks import blockmetadata import onionrstorage import onionrcrypto as crypto from . import onionrblacklist diff --git a/src/onionrblocks/blocklist.py b/src/oldblocks/blocklist.py similarity index 100% rename from src/onionrblocks/blocklist.py rename to src/oldblocks/blocklist.py diff --git a/src/onionrblocks/blockmetadata/__init__.py b/src/oldblocks/blockmetadata/__init__.py similarity index 100% rename from src/onionrblocks/blockmetadata/__init__.py rename to src/oldblocks/blockmetadata/__init__.py diff --git a/src/onionrblocks/blockmetadata/fromdata.py b/src/oldblocks/blockmetadata/fromdata.py similarity index 100% rename from src/onionrblocks/blockmetadata/fromdata.py rename to src/oldblocks/blockmetadata/fromdata.py diff --git a/src/onionrblocks/blockmetadata/hasblock.py b/src/oldblocks/blockmetadata/hasblock.py similarity index 100% rename from src/onionrblocks/blockmetadata/hasblock.py rename to src/oldblocks/blockmetadata/hasblock.py diff --git a/src/onionrblocks/blockmetadata/process.py b/src/oldblocks/blockmetadata/process.py similarity index 98% rename from src/onionrblocks/blockmetadata/process.py rename to src/oldblocks/blockmetadata/process.py index fe094977..8018f099 100644 --- a/src/onionrblocks/blockmetadata/process.py +++ b/src/oldblocks/blockmetadata/process.py @@ -3,7 +3,7 @@ Process block metadata with relevant actions """ from etc import onionrvalues -from onionrblocks import onionrblockapi +from oldblocks import onionrblockapi from onionrutils import epoch, bytesconverter from coredb import blockmetadb import logger diff --git a/src/onionrblocks/deleteplaintext.py b/src/oldblocks/deleteplaintext.py similarity index 100% rename from src/onionrblocks/deleteplaintext.py rename to src/oldblocks/deleteplaintext.py diff --git a/src/onionrblocks/insert/__init__.py b/src/oldblocks/insert/__init__.py similarity index 100% rename from src/onionrblocks/insert/__init__.py rename to src/oldblocks/insert/__init__.py diff --git a/src/onionrblocks/insert/main.py b/src/oldblocks/insert/main.py similarity index 100% rename from src/onionrblocks/insert/main.py rename to src/oldblocks/insert/main.py diff --git a/src/onionrblocks/insert/timeinsert.py b/src/oldblocks/insert/timeinsert.py similarity index 100% rename from src/onionrblocks/insert/timeinsert.py rename to src/oldblocks/insert/timeinsert.py diff --git a/src/onionrblocks/onionrblacklist.py b/src/oldblocks/onionrblacklist.py similarity index 100% rename from src/onionrblocks/onionrblacklist.py rename to src/oldblocks/onionrblacklist.py diff --git a/src/onionrblocks/onionrblockapi.py b/src/oldblocks/onionrblockapi.py similarity index 99% rename from src/onionrblocks/onionrblockapi.py rename to src/oldblocks/onionrblockapi.py index 875d8faf..741347ad 100755 --- a/src/onionrblocks/onionrblockapi.py +++ b/src/oldblocks/onionrblockapi.py @@ -1,6 +1,6 @@ """Onionr - P2P Anonymous Storage Network. -OnionrBlocks class for abstraction of blocks +oldblocks class for abstraction of blocks """ import datetime import onionrstorage @@ -15,7 +15,7 @@ from onionrusers import onionrusers from onionrutils import stringvalidators, epoch from coredb import blockmetadb from onionrutils import bytesconverter -import onionrblocks +import oldblocks from onionrcrypto import encryption, cryptoutils as cryptoutils, signing """ This program is free software: you can redistribute it and/or modify diff --git a/src/onionrblocks/storagecounter.py b/src/oldblocks/storagecounter.py similarity index 100% rename from src/onionrblocks/storagecounter.py rename to src/oldblocks/storagecounter.py diff --git a/src/onionrcommands/banblocks.py b/src/onionrcommands/banblocks.py index 49fa21f8..0a91bdb5 100755 --- a/src/onionrcommands/banblocks.py +++ b/src/onionrcommands/banblocks.py @@ -7,7 +7,7 @@ import logger from onionrutils import stringvalidators from onionrstorage import removeblock from onionrstorage import deleteBlock -from onionrblocks import onionrblacklist +from oldblocks import onionrblacklist from utils import reconstructhash """ This program is free software: you can redistribute it and/or modify diff --git a/src/onionrcommands/daemonlaunch/spawndaemonthreads.py b/src/onionrcommands/daemonlaunch/spawndaemonthreads.py index 09b6213d..a19f2542 100644 --- a/src/onionrcommands/daemonlaunch/spawndaemonthreads.py +++ b/src/onionrcommands/daemonlaunch/spawndaemonthreads.py @@ -12,6 +12,7 @@ from communicatorutils import uploadblocks from communicatorutils import announcenode, deniableinserts from communicatorutils import netcheck import onionrpeers + import config if TYPE_CHECKING: diff --git a/src/onionrcommands/filecommands.py b/src/onionrcommands/filecommands.py index 315441df..131de0a9 100755 --- a/src/onionrcommands/filecommands.py +++ b/src/onionrcommands/filecommands.py @@ -6,11 +6,11 @@ and getting files from the Onionr network import sys import os import logger -from onionrblocks.onionrblockapi import Block +from oldblocks.onionrblockapi import Block import onionrexceptions from onionrutils import stringvalidators from etc import onionrvalues -from onionrblocks import insert +from oldblocks import insert """ 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 diff --git a/src/onionrcommands/listsites.py b/src/onionrcommands/listsites.py index 3f874cfe..0e67235a 100644 --- a/src/onionrcommands/listsites.py +++ b/src/onionrcommands/listsites.py @@ -3,7 +3,7 @@ Dumb listing of Onionr sites """ from coredb.blockmetadb import get_blocks_by_type -from onionrblocks.onionrblockapi import Block +from oldblocks.onionrblockapi import Block import logger """ This program is free software: you can redistribute it and/or modify diff --git a/src/onionrcommands/motdcreator.py b/src/onionrcommands/motdcreator.py index 85e69e8c..47cb1e07 100644 --- a/src/onionrcommands/motdcreator.py +++ b/src/onionrcommands/motdcreator.py @@ -3,7 +3,7 @@ Command to make new network-wide MOTD message. Only network admin can do this The key is set in onionrvalues """ -import onionrblocks +import oldblocks """ 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 @@ -29,7 +29,7 @@ def motd_creator(): new = input() # nosec B323 if new != 'quit': motd += new - bl = onionrblocks.insert(motd, header='motd', sign=True) + bl = oldblocks.insert(motd, header='motd', sign=True) print(f"inserted in {bl}") diff --git a/src/onionrcommands/onionrstatistics.py b/src/onionrcommands/onionrstatistics.py index 78ad638d..09bd2480 100755 --- a/src/onionrcommands/onionrstatistics.py +++ b/src/onionrcommands/onionrstatistics.py @@ -4,7 +4,7 @@ This module defines commands to show stats/details about the local node """ import os import logger -from onionrblocks import onionrblacklist +from oldblocks import onionrblacklist from onionrutils import mnemonickeys from utils import sizeutils, gethostname, getconsolewidth, identifyhome from coredb import blockmetadb, keydb diff --git a/src/onionrpeers/peercleanup.py b/src/onionrpeers/peercleanup.py index 6173a041..8c61e732 100644 --- a/src/onionrpeers/peercleanup.py +++ b/src/onionrpeers/peercleanup.py @@ -21,7 +21,7 @@ import sqlite3 import logger from onionrutils import epoch from . import scoresortedpeerlist, peerprofiles -from onionrblocks import onionrblacklist +from oldblocks import onionrblacklist import config from coredb import keydb def peer_cleanup(): @@ -30,7 +30,7 @@ def peer_cleanup(): blacklist = onionrblacklist.OnionrBlackList() adders = scoresortedpeerlist.get_score_sorted_peer_list() adders.reverse() - + if len(adders) > 1: min_score = int(config.get('peers.minimum_score', -100)) diff --git a/src/onionrpeers/peerprofiles.py b/src/onionrpeers/peerprofiles.py index 000e9c4d..d18f0776 100644 --- a/src/onionrpeers/peerprofiles.py +++ b/src/onionrpeers/peerprofiles.py @@ -20,7 +20,7 @@ from coredb import keydb from onionrutils import epoch from onionrutils import stringvalidators -from onionrblocks import onionrblacklist +from oldblocks import onionrblacklist import onionrexceptions UPDATE_DELAY = 300 @@ -42,7 +42,7 @@ class PeerProfiles: self.getConnectTime() self.last_updated = {'connect_time': UPDATE_DELAY, 'score': UPDATE_DELAY} # Last time a given value was updated - + if not address in keydb.listkeys.list_adders() and not onionrblacklist.OnionrBlackList().inBlacklist(address): keydb.addkeys.add_address(address) @@ -53,7 +53,7 @@ class PeerProfiles: except (TypeError, ValueError) as e: self.success = 0 self.score = self.success - + def getConnectTime(self): """set the connectTime variable for when we last connected to them, using the db value""" try: @@ -62,12 +62,12 @@ class PeerProfiles: pass else: return self.connectTime - + def update_connect_time(self): if epoch.get_epoch() - self.last_updated['connect_time'] >= UPDATE_DELAY: self.last_updated['connect_time'] = epoch.get_epoch() keydb.transportinfo.set_address_info(self.address, 'lastConnect', epoch.get_epoch()) - + def saveScore(self): '''Save the node's score to the database''' if epoch.get_epoch() - self.last_updated['score'] >= UPDATE_DELAY: diff --git a/src/onionrproofs/__init__.py b/src/onionrproofs/__init__.py index e0f4a956..b02be8c5 100755 --- a/src/onionrproofs/__init__.py +++ b/src/onionrproofs/__init__.py @@ -7,7 +7,7 @@ import nacl.encoding, nacl.hash, nacl.utils import config import logger -from onionrblocks import onionrblockapi +from oldblocks import onionrblockapi from onionrutils import bytesconverter from onionrcrypto import hashers diff --git a/src/onionrstorage/removeblock.py b/src/onionrstorage/removeblock.py index 6b9452ea..32dc5d5a 100644 --- a/src/onionrstorage/removeblock.py +++ b/src/onionrstorage/removeblock.py @@ -9,7 +9,7 @@ import onionrexceptions import onionrstorage from onionrutils import stringvalidators from coredb import dbfiles -from onionrblocks import storagecounter +from oldblocks import storagecounter from etc.onionrvalues import DATABASE_LOCK_TIMEOUT """ This program is free software: you can redistribute it and/or modify diff --git a/src/onionrstorage/setdata.py b/src/onionrstorage/setdata.py index 456276f5..c471ad7e 100644 --- a/src/onionrstorage/setdata.py +++ b/src/onionrstorage/setdata.py @@ -9,7 +9,7 @@ import onionrstorage import onionrexceptions import onionrcrypto as crypto import filepaths -from onionrblocks import storagecounter, blockmetadata +from oldblocks import storagecounter, blockmetadata from coredb import dbfiles from onionrutils import bytesconverter from etc.onionrvalues import DATABASE_LOCK_TIMEOUT diff --git a/src/onionrutils/importnewblocks.py b/src/onionrutils/importnewblocks.py index 11ae89c5..e45e3528 100644 --- a/src/onionrutils/importnewblocks.py +++ b/src/onionrutils/importnewblocks.py @@ -5,7 +5,7 @@ import new blocks from disk, providing transport agnosticism import glob import logger -from onionrblocks import blockmetadata +from oldblocks import blockmetadata from coredb import blockmetadb import filepaths import onionrcrypto as crypto diff --git a/src/runtests/housekeeping.py b/src/runtests/housekeeping.py index ccc46b9f..94b9076c 100644 --- a/src/runtests/housekeeping.py +++ b/src/runtests/housekeeping.py @@ -2,7 +2,7 @@ import os from gevent import sleep -from onionrblocks import insert +from oldblocks import insert import logger from coredb.blockmetadb import get_block_list from onionrutils import epoch diff --git a/src/runtests/inserttest.py b/src/runtests/inserttest.py index ea43fd44..c800cc30 100644 --- a/src/runtests/inserttest.py +++ b/src/runtests/inserttest.py @@ -1,7 +1,7 @@ import os import time -import onionrblocks +import oldblocks import logger import coredb from communicator import peeraction @@ -11,7 +11,7 @@ def _check_remote_node(testmanager): def insert_bin_test(testmanager): data = os.urandom(32) - b_hash = onionrblocks.insert(data) + b_hash = oldblocks.insert(data) time.sleep(0.3) if b_hash not in testmanager._too_many.get_by_string("PublicAPI").hideBlocks: raise ValueError("Block not hidden") diff --git a/src/runtests/lanservertest.py b/src/runtests/lanservertest.py index 42f71861..66fdd305 100644 --- a/src/runtests/lanservertest.py +++ b/src/runtests/lanservertest.py @@ -2,7 +2,7 @@ import requests from lan.getip import best_ip -from onionrblocks import insert, onionrblockapi +from oldblocks import insert, onionrblockapi from gevent import sleep from coredb import blockmetadb from onionrutils.epoch import get_epoch diff --git a/src/runtests/sneakernettest.py b/src/runtests/sneakernettest.py index ac48ad30..4af036fa 100644 --- a/src/runtests/sneakernettest.py +++ b/src/runtests/sneakernettest.py @@ -1,7 +1,7 @@ import os from shutil import move -from onionrblocks import insert +from oldblocks import insert from onionrstorage import deleteBlock from onionrcommands.exportblocks import export_block from filepaths import export_location, block_data_location, data_nonce_file diff --git a/src/runtests/stresstest.py b/src/runtests/stresstest.py index 35a9967c..92ef1dff 100644 --- a/src/runtests/stresstest.py +++ b/src/runtests/stresstest.py @@ -1,6 +1,6 @@ import os -import onionrblocks +import oldblocks import logger import coredb from onionrutils import epoch @@ -10,7 +10,7 @@ def stress_test_block_insert(testmanager): start = epoch.get_epoch() count = 100 max_insert_speed = 120 - for x in range(count): onionrblocks.insert(os.urandom(32)) + for x in range(count): oldblocks.insert(os.urandom(32)) speed = epoch.get_epoch() - start if speed < max_insert_speed: raise ValueError(f'{count} blocks inserted too fast, {max_insert_speed}, got {speed}') diff --git a/src/safedb/__init__.py b/src/safedb/__init__.py index ed23e126..f1cea2f0 100644 --- a/src/safedb/__init__.py +++ b/src/safedb/__init__.py @@ -22,6 +22,10 @@ along with this program. If not, see . """ +class DBProtectionOpeningModeError(Exception): + pass + + class SafeDB: """Wrapper around dbm to optionally encrypt db values.""" @@ -31,7 +35,8 @@ class SafeDB: return unprotect_string(self.db_conn[key]) def put( - self, key: [str, bytes, bytearray], value: [bytes, bytearray]): + self, + key: Union[str, bytes, bytearray], value: Union[bytes, bytearray]): if self.protected: self.db_conn[key] = protect_string(value) else: @@ -47,10 +52,10 @@ class SafeDB: try: existing_protected_mode = self.db_conn['enc'] if protected and existing_protected_mode != b'1': - raise ValueError( + raise DBProtectionOpeningModeError( "Cannot open unencrypted database with protected=True") elif not protected and existing_protected_mode != b'0': - raise ValueError( + raise DBProtectionOpeningModeError( "Cannot open encrypted database in protected=False") except KeyError: if protected: diff --git a/src/sneakernet/__init__.py b/src/sneakernet/__init__.py index 6b4002a8..8f6c7787 100644 --- a/src/sneakernet/__init__.py +++ b/src/sneakernet/__init__.py @@ -10,7 +10,7 @@ from watchdog.events import FileSystemEventHandler import config from filepaths import block_data_location from etc.onionrvalues import BLOCK_EXPORT_FILE_EXT -from onionrblocks.blockimporter import import_block_from_data +from oldblocks.blockimporter import import_block_from_data import onionrexceptions """ This program is free software: you can redistribute it and/or modify diff --git a/src/utils/networkmerger.py b/src/utils/networkmerger.py index 8e7293a9..0e80ee04 100755 --- a/src/utils/networkmerger.py +++ b/src/utils/networkmerger.py @@ -20,7 +20,7 @@ import logger from coredb import keydb import config -from onionrblocks import onionrblacklist +from oldblocks import onionrblacklist from utils import gettransports def mergeAdders(newAdderList): ''' diff --git a/static-data/default-plugins/circles/main.py b/static-data/default-plugins/circles/main.py index 51e7815a..7515173f 100755 --- a/static-data/default-plugins/circles/main.py +++ b/static-data/default-plugins/circles/main.py @@ -11,9 +11,9 @@ from coredb import blockmetadb import threading import time import locale -from onionrblocks.onionrblockapi import Block +from oldblocks.onionrblockapi import Block import logger -import onionrblocks +import oldblocks from onionrutils import escapeansi, epoch, bytesconverter locale.setlocale(locale.LC_ALL, '') @@ -79,7 +79,7 @@ class OnionrFlow: expireTime = epoch.get_epoch() + EXPIRE_TIME if len(message) > 0: logger.info('Inserting message as block...', terminal=True) - onionrblocks.insert(message, header='brd', + oldblocks.insert(message, header='brd', expire=expireTime, meta = { 'ch': self.channel}) @@ -132,7 +132,7 @@ def on_circlesend_cmd(api, data=None): except IndexError: logger.error(err_msg, terminal=True) - bl = onionrblocks.insert(sys.argv[3], header='brd', + bl = oldblocks.insert(sys.argv[3], header='brd', expire=(EXPIRE_TIME + epoch.get_epoch()), meta={'ch': sys.argv[2]}) print(bl) diff --git a/static-data/default-plugins/pms/loadinbox.py b/static-data/default-plugins/pms/loadinbox.py index 6a215f71..4b31c1b6 100755 --- a/static-data/default-plugins/pms/loadinbox.py +++ b/static-data/default-plugins/pms/loadinbox.py @@ -2,7 +2,7 @@ Load the user's inbox and return it as a list """ -from onionrblocks import onionrblockapi +from oldblocks import onionrblockapi from coredb import blockmetadb from utils import reconstructhash, identifyhome import deadsimplekv as simplekv diff --git a/static-data/www/onboarding/onboarding.js b/static-data/www/onboarding/onboarding.js index f431d13a..b4375fcc 100644 --- a/static-data/www/onboarding/onboarding.js +++ b/static-data/www/onboarding/onboarding.js @@ -56,6 +56,7 @@ document.getElementById('onboardingForm').onsubmit = function(e){ submitInfo.mail = getCheckValue('useMail') submitInfo.circles = getCheckValue('useCircles') submitInfo.useDark = getCheckValue('useDarkTheme') + submitInfo.optimize = getCheckValue('optimize') if (submitInfo.donate){ openDonateModal(submitInfo) diff --git a/tests/test_blocklist_class.py b/tests/test_blocklist_class.py index 5f591b77..52c00950 100644 --- a/tests/test_blocklist_class.py +++ b/tests/test_blocklist_class.py @@ -19,7 +19,7 @@ import config config.set("general.minimum_block_pow", 2) config.set('general.minimum_send_pow', 2) config.save() -from onionrblocks import BlockList, insert +from oldblocks import BlockList, insert class TestBlockList(unittest.TestCase): diff --git a/tests/test_blocks.py b/tests/test_blocks.py index c8a4d7aa..3e0e925b 100644 --- a/tests/test_blocks.py +++ b/tests/test_blocks.py @@ -14,7 +14,7 @@ createdirs.create_dirs() import onionrstorage from onionrutils import bytesconverter import onionrcrypto -from onionrblocks import onionrblockapi +from oldblocks import onionrblockapi from onionrsetup import setup_config, setup_default_plugins @@ -25,20 +25,20 @@ import config config.set("general.minimum_block_pow", 2) config.set('general.minimum_send_pow', 2) config.save() -import onionrblocks +import oldblocks class OnionrBlockTests(unittest.TestCase): def test_plaintext_insert(self): message = 'hello world' - bl = onionrblocks.insert(message) + bl = oldblocks.insert(message) self.assertTrue(bl.startswith('0')) self.assertIn(bytesconverter.str_to_bytes(message), onionrstorage.getData(bl)) def test_encrypted_insert(self): message = 'hello world2' - bl = onionrblocks.insert(message, asymPeer=onionrcrypto.pub_key) + bl = oldblocks.insert(message, asymPeer=onionrcrypto.pub_key) self.assertIn(bytesconverter.str_to_bytes(message), onionrblockapi.Block(bl, decrypt=True).bcontent) unittest.main() diff --git a/tests/test_default_config_json.py b/tests/test_default_config_json.py index 76ec3e65..e2c8f9a2 100644 --- a/tests/test_default_config_json.py +++ b/tests/test_default_config_json.py @@ -10,7 +10,7 @@ createdirs.create_dirs() from onionrcrypto import getourkeypair getourkeypair.get_keypair() from utils import readstatic -import onionrblocks +import oldblocks class OnionrConfig(unittest.TestCase): def test_default_file(self): json.loads(readstatic.read_static('default_config.json')) diff --git a/tests/test_safedb.py b/tests/test_safedb.py index b54b867a..1e709bdf 100644 --- a/tests/test_safedb.py +++ b/tests/test_safedb.py @@ -31,7 +31,7 @@ class TestSafeDB(unittest.TestCase): with dbm.open(db_path) as db: self.assertEqual(db['enc'], b'0') - def test_db_create_proteced(self): + def test_db_create_protected(self): _remove_db() db = safedb.SafeDB(db_path, protected=True) db.close() @@ -46,7 +46,7 @@ class TestSafeDB(unittest.TestCase): db.close() self.assertRaises(ValueError, safedb.SafeDB, db_path, protected=False) - def test_db_open_unproteced(self): + def test_db_open_unprotected(self): _remove_db() with dbm.open(db_path, 'c') as db: db['enc'] = b'0' @@ -54,6 +54,14 @@ class TestSafeDB(unittest.TestCase): db.close() self.assertRaises(ValueError, safedb.SafeDB, db_path, protected=True) + def test_db_put_unprotected(self): + _remove_db() + db = safedb.SafeDB(db_path, protected=False) + db.put("test", b"Test") + db.close() + with dbm.open(db_path, 'c') as db: + self.assertEqual(db['test', b"Test"]) + unittest.main() diff --git a/tests/test_storagecounter.py b/tests/test_storagecounter.py index 4b720018..e37389f1 100644 --- a/tests/test_storagecounter.py +++ b/tests/test_storagecounter.py @@ -25,9 +25,9 @@ import config config.set("general.minimum_block_pow", 2) config.set('general.minimum_send_pow', 2) config.save() -import onionrblocks +import oldblocks -from onionrblocks import storagecounter +from oldblocks import storagecounter import onionrstorage def _test_setup(): @@ -47,13 +47,13 @@ class TestStorageCounter(unittest.TestCase): def test_insert_too_much(self): _test_setup() config.set('allocations.disk', 1000) - self.assertRaises(onionrexceptions.DiskAllocationReached, onionrblocks.insert, "test") + self.assertRaises(onionrexceptions.DiskAllocationReached, oldblocks.insert, "test") def test_count(self): _test_setup() counter = storagecounter.StorageCounter() start_value = counter.amount - b_hash = onionrblocks.insert("test") + b_hash = oldblocks.insert("test") sleep(0.1) self.assertGreater(counter.amount, start_value) onionrstorage.removeblock.remove_block(b_hash) diff --git a/tests/test_timeinsert.py b/tests/test_timeinsert.py index a3adef75..9eab20ec 100644 --- a/tests/test_timeinsert.py +++ b/tests/test_timeinsert.py @@ -10,8 +10,8 @@ from utils import createdirs createdirs.create_dirs() from onionrcrypto import getourkeypair getourkeypair.get_keypair() -from onionrblocks import time_insert -from onionrblocks import onionrblockapi +from oldblocks import time_insert +from oldblocks import onionrblockapi from onionrsetup import setup_config, setup_default_plugins setup_config() From 30b73c7f7c7740fe57e749826a33b7292705fa69 Mon Sep 17 00:00:00 2001 From: Kevin Froman Date: Sun, 17 Jan 2021 19:44:00 +0000 Subject: [PATCH 12/14] bump onionrblocks for missing generator module --- requirements.in | 2 +- requirements.txt | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/requirements.in b/requirements.in index 1b32efe2..568d553d 100644 --- a/requirements.in +++ b/requirements.in @@ -15,4 +15,4 @@ filenuke==0.0.0 watchdog==1.0.2 ujson==4.0.1 cffi==1.14.4 -onionrblocks==0.0.1 +onionrblocks==0.0.2 diff --git a/requirements.txt b/requirements.txt index 394b808c..52741d22 100644 --- a/requirements.txt +++ b/requirements.txt @@ -203,9 +203,9 @@ niceware==0.2.1 \ --hash=sha256:0f8b192f2a1e800e068474f6e208be9c7e2857664b33a96f4045340de4e5c69c \ --hash=sha256:cf2dc0e1567d36d067c61b32fed0f1b9c4534ed511f9eeead4ba548d03b5c9eb # via -r requirements.in -onionrblocks==0.0.1 \ - --hash=sha256:719b83770e0afa3b165ad103c8e1234f9ec0274bffae5e8438dc26e66dce474d \ - --hash=sha256:972f91a8d21f76f4ab659bdc13b022d4bb46fa18a01298d4d8a6791228a006be +onionrblocks==0.0.2 \ + --hash=sha256:24ec41e56627a901566a35ddae50431976282e8eba0530406d8a853b6230d593 \ + --hash=sha256:725100dfbc778aa2d41708a85605c20ca9b49748f6aac58da0cdc7178c32b44f # via -r requirements.in psutil==5.8.0 \ --hash=sha256:0066a82f7b1b37d334e68697faba68e5ad5e858279fd6351c8ca6024e8d6ba64 \ From b6bb350b65ee0e64131b3ed5696cb312ad67b1e7 Mon Sep 17 00:00:00 2001 From: Kevin Froman Date: Sun, 17 Jan 2021 19:44:24 +0000 Subject: [PATCH 13/14] fix broken non protected safedb get --- src/safedb/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/safedb/__init__.py b/src/safedb/__init__.py index f1cea2f0..504e40b4 100644 --- a/src/safedb/__init__.py +++ b/src/safedb/__init__.py @@ -30,7 +30,7 @@ class SafeDB: """Wrapper around dbm to optionally encrypt db values.""" def get(self, key: Union[str, bytes, bytearray]) -> bytes: - if self.protected: + if not self.protected: return self.db_conn[key] return unprotect_string(self.db_conn[key]) From f44ca60c6ef6140873aa5668cd7a1c9489bd1d54 Mon Sep 17 00:00:00 2001 From: Kevin Froman Date: Sun, 17 Jan 2021 19:44:57 +0000 Subject: [PATCH 14/14] implemented fetch block in blockio --- src/blockio/__init__.py | 3 +- src/blockio/store/__init__.py | 20 ++++++++++---- tests/test_blockio.py | 52 +++++++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 7 deletions(-) create mode 100644 tests/test_blockio.py diff --git a/src/blockio/__init__.py b/src/blockio/__init__.py index 72940344..f88116e2 100644 --- a/src/blockio/__init__.py +++ b/src/blockio/__init__.py @@ -2,6 +2,7 @@ Wrap safedb for storing and fetching blocks """ +from .store import store_block """ 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 @@ -15,4 +16,4 @@ GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . -""" \ No newline at end of file +""" diff --git a/src/blockio/store/__init__.py b/src/blockio/store/__init__.py index 251b361e..9e01af1a 100644 --- a/src/blockio/store/__init__.py +++ b/src/blockio/store/__init__.py @@ -2,9 +2,7 @@ Store blocks and cache meta info such as block type """ -from typing import TYPE_CHECKING, Union, NewType - -from safedb import DBProtectionOpeningModeError +from typing import TYPE_CHECKING if TYPE_CHECKING: from kasten import Kasten @@ -24,10 +22,20 @@ You should have received a copy of the GNU General Public License along with this program. If not, see . """ -RawBlock = NewType('RawBlock', bytes) +def store_block(block: 'Kasten', safe_db: 'SafeDB'): + + block_type = block.get_data_type() + try: + block_list_for_type = safe_db.get(f'bl-{block_type}') + if block.id in block_list_for_type: + raise ValueError("Cannot store duplicate block") + except KeyError: + block_list_for_type = b'' -def store_block(block: Kasten, safe_db: SafeDB): - safe_db.put(block.id, block.get_packed()) + # Append the block to the list of blocks for this given type + block_list_for_type += block.id + safe_db.put(f'bl-{block_type}', block_list_for_type) + diff --git a/tests/test_blockio.py b/tests/test_blockio.py new file mode 100644 index 00000000..8a61a0ee --- /dev/null +++ b/tests/test_blockio.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +import sys, os +sys.path.append(".") +sys.path.append("src/") +import uuid +TEST_DIR = 'testdata/%s-%s' % (uuid.uuid4(), os.path.basename(__file__)) + '/' +print("Test directory:", TEST_DIR) +os.environ["ONIONR_HOME"] = TEST_DIR +import unittest +from utils import identifyhome, createdirs, bettersleep +from onionrsetup import setup_config, setup_default_plugins + +createdirs.create_dirs() +setup_config() +setup_default_plugins() + +import kasten +from onionrblocks.generators import anonvdf +from utils import identifyhome + +import safedb +import blockio + +def _remove_db(path): + try: + os.remove(path) + except FileNotFoundError: + pass + +class TestBlockIO(unittest.TestCase): + def test_store_block(self): + packed = kasten.generator.pack.pack(b"test", "tst") + bl: kasten.Kasten = anonvdf.AnonVDFGenerator.generate(packed, rounds=1000) + db_file = identifyhome.identify_home() + 'test.db' + db = safedb.SafeDB(db_file) + blockio.store_block(bl, db) + db.close() + _remove_db(db_file) + + def test_store_dupe(self): + packed = kasten.generator.pack.pack(b"test", "tst") + bl: kasten.Kasten = anonvdf.AnonVDFGenerator.generate(packed, rounds=1000) + db_file = identifyhome.identify_home() + 'test.db' + db = safedb.SafeDB(db_file) + blockio.store_block(bl, db) + self.assertRaises(ValueError, blockio.store_block, bl, db) + db.close() + _remove_db(db_file) + + + +unittest.main()