Compare commits

..

No commits in common. "91b3ae0daba549b2762790432a4d8abfa4c397b5" and "a0704ef2404140361d5a1d5c276447e895a94b25" have entirely different histories.

9 changed files with 194 additions and 431 deletions

View File

@ -26,7 +26,6 @@ project_set_alternate_linker()
add_executable(swsf_bruteforce add_executable(swsf_bruteforce
src/asio_impl.cpp src/asio_impl.cpp
src/main.cpp src/main.cpp
src/worker.cpp
) )
target_compile_definitions(swsf_bruteforce PRIVATE target_compile_definitions(swsf_bruteforce PRIVATE

View File

@ -1,7 +0,0 @@
Copyright 2023 Lily Tsuru <lily.modeco80@protonmail.ch>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -1,36 +0,0 @@
# swsf_bruteforce
A performant, multithreaded, brute-forcer for scrambled cheat codes in Star Wars: Starfighter (JP) and Star Wars: Jedi Starfighter, written in modern C++20.
# Building
You need:
- A C++20 compiler (MSVC 2022, Clang, GCC)
- Boost (I tested with 1.81, should work fine with 1.82 onwards)
- CMake
## Windows
```
cmake -Bbuild -GNinja -DCMAKE_BUILD_TYPE=Release
cmake --build build
```
## Linux
```
$ cmake -Bbuild -GNinja -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_CXX_FLAGS="-march=native -mtune=native"
$ cmake --build build
`
# Usage
`./swsf_bruteforce -s [START_LENGTH] -l [LENGTH] -e 0xABCDABCD`
where:
`-s [START_LENGTH]` is the guessed start bound (greater than 2, less than end bound)
`-l [LENGTH]` is the guessed end bound (less than or equal to 8)
`0xABCDABCD` is the hash to use

View File

@ -1,28 +0,0 @@
#include <cstdint>
#include <format>
#include <string_view>
// see https://bisqwit.iki.fi/jutut/kuvat/programming_examples/cpp_thread_tutorial/ver05.cc
// this version of the code doesn't even need to worry about synchronization
namespace swbf::ansi {
inline std::uint32_t ln = 1;
inline auto Color(int n) {
return std::format("\33[38;5;{}m", n);
}
inline std::string_view Reset() {
return "\33[m";
}
inline auto Line(int l) {
int m = l - ln;
ln = l;
return "\r" + (m < 0 ? "\33[" + std::to_string(-m) + 'A' : std::string(m, '\n'));
}
inline std::string_view ResetLine() {
return "\33[2K";
}
} // namespace swbf::ansi

View File

@ -1,35 +0,0 @@
#pragma once
#include <iterator>
#include <cstdint>
#include <cstdio>
#include <format>
namespace swbf {
struct FputcIterator {
using iterator_category = std::output_iterator_tag;
using value_type = void;
using difference_type = std::ptrdiff_t;
using pointer = void;
using reference = void;
FputcIterator(std::FILE* file) : file(file) {}
FputcIterator& operator*() { return *this; }
FputcIterator& operator++() { return *this; }
FputcIterator& operator++(int) { return *this; }
FputcIterator& operator=(const char& val) {
std::fputc(val, file);
return *this;
}
private:
std::FILE* file;
};
/// Poor Man's C++23
template<class ...Args>
inline void fprint(std::FILE* file, std::string_view format, Args&&... args) {
std::vformat_to(FputcIterator(file), format, std::make_format_args(args...));
}
} // namespace swbf

View File

@ -1,133 +1,215 @@
#include "fprint.hpp" #include <boost/asio/io_context.hpp>
#include "worker.hpp" #include <boost/asio/post.hpp>
#include <boost/asio/thread_pool.hpp>
#include <format>
#include <thread>
struct Arguments { namespace asio = boost::asio;
bool exact { false };
std::uint32_t startLength = 2;
std::uint32_t endLength = 8;
std::uint32_t targetHash; constexpr static auto MAX_CODE_LENGTH = 8;
constexpr static auto THREAD_COUNT = 26; // this is a-z
/// Parse arguments from the main() argc/argv. /// This is a constexpr-safe zero-allocation version of the algorithm
static Arguments FromArgv(int argc, char** argv) { /// the "Scramble" ConsoleScript hash algorithm.
Arguments args; constexpr std::uint32_t SwsfScramble(std::string_view code) {
args.progname = argv[0]; std::uint32_t tally {};
// no options provided auto cycle = [&tally](char c) { tally = c + (tally * 5); };
if(argc == 1) {
args.DispHelp();
std::exit(1);
}
// non-pepper getopt(). I'm too lazy to make it any better though cycle('c');
for(int i = 1; i < argc; ++i) { cycle('o');
if(argv[i][0] == '-' && argv[i][1] != '\0') { cycle('d');
char sw = argv[i][1]; cycle('e');
cycle('_');
// hacky. VERY hacky. for(auto* p = code.data(); *p; ++p)
auto cheap_atoi = [](char c) { return c - '0'; }; cycle(tolower(*p));
return tally;
}
switch(sw) { struct FputcIterator {
// flag options using iterator_category = std::output_iterator_tag;
using value_type = void;
using difference_type = std::ptrdiff_t;
using pointer = void;
using reference = void;
case 'X': // eXact FputcIterator(std::FILE* file) : file(file) {}
args.exact = true; FputcIterator& operator*() { return *this; }
break; FputcIterator& operator++() { return *this; }
FputcIterator& operator++(int) { return *this; }
// value options FputcIterator& operator=(const char& val) {
fputc(val, file);
case 's': // start length return *this;
if(argv[i + 1] == nullptr || argv[i + 1][0] == '-') {
swbf::fprint(stdout, "Invalid value passed to -s\n");
std::exit(1);
}
args.startLength = cheap_atoi(*argv[i + 1]);
i++;
break;
case 'e': // end length
if(argv[i + 1] == nullptr || argv[i + 1][0] == '-') {
swbf::fprint(stdout, "Invalid value passed to -e\n");
std::exit(1);
}
args.endLength = cheap_atoi(*argv[i + 1]);
i++;
break;
// terminals
case '?':
case 'h': {
args.DispHelp();
std::exit(0);
}
default:
swbf::fprint(stdout, "Unknown command-line switch '-{}'\n", sw);
args.DispHelp();
std::exit(1);
}
} else {
// Assume any non-positional argument is the hash value
// (also, this will take *any* base, not just hex, but hex is the most useful)
args.targetHash = strtol(argv[i], nullptr, 0);
}
}
return args;
}
bool Validate() const {
if(!targetHash) {
swbf::fprint(stdout, "No hash provided\n");
DispHelp();
return false;
}
if((startLength < 2) || (startLength > endLength)) {
swbf::fprint(stdout, "Invalid start/exact length\n");
DispHelp();
return false;
}
// omit checking for -e validity if we don't really need it
if(!exact) {
if((endLength > 8) || (endLength < startLength)) {
swbf::fprint(stdout, "Invalid end length\n");
DispHelp();
return false;
}
}
return true;
} }
private: private:
char* progname {}; std::FILE* file;
};
void DispHelp() const { bool NextCode(std::string& buffer, size_t start) {
swbf::fprint(stdout, size_t len = buffer.length();
// clang-format off for(size_t i = len - 1; i >= start; --i) {
"SWSF Bruteforcer, (C) 2023 Lily Tsuru under the MIT License\n" char c = buffer[i];
"Usage: {} [-?/-h] [-X] [-s START_LENGTH] [-e END_LENGTH] <hash to crack, in hexadecimal>\n" if(c < 'z') {
" -X Test exact length. Uses value of -s; -e is ignored in this mode.\n" ++buffer[i];
" -s Start length to check. Must be greater than or equal to 2 and less than the end size (default 2)\n" return true;
" -e End length to check. Must be greater than the start size, and less than or equal to 8 (default 8)\n" }
" -?/-h Show this help message (and exit)\n", buffer[i] = 'a';
progname }
// clang-format on return false;
); }
// see https://bisqwit.iki.fi/jutut/kuvat/programming_examples/cpp_thread_tutorial/ver05.cc
// this version of the code doesn't even need to worry about synchronization
namespace {
unsigned ln = 1;
auto Color(int n) {
return std::format("\33[38;5;{}m", n);
}
std::string_view Reset() {
return "\33[m";
}
auto Line(int l) {
int m = l - ln;
ln = l;
return "\r" + (m < 0 ? "\33[" + std::to_string(-m) + 'A' : std::string(m, '\n'));
}
std::string_view ResetLine() {
return "\33[2K";
}
} // namespace
/// This class implements the display of progress
struct ThreadInfoData {
ThreadInfoData() { codeString.resize(MAX_CODE_LENGTH); }
std::uint32_t threadIndex;
std::string codeString;
std::uint32_t codeHash;
bool done = false;
void DisplayProgress() {
if(!done)
std::format_to(FputcIterator(stdout), "{}Thread {:2}: Trying code {}{} {}({:08x}){}", Line(threadIndex), threadIndex, Color(172),
codeString, Color(166), codeHash, Reset());
else {
std::format_to(FputcIterator(stdout), "{}{}Thread {:2}: {}Finished!{}", Line(threadIndex), ResetLine(), threadIndex, Color(172), Reset());
}
std::fflush(stdout);
} }
}; };
int main(int argc, char** argv) { std::vector<ThreadInfoData> infoData(THREAD_COUNT);
auto args = Arguments::FromArgv(argc, argv);
if(!args.Validate()) {
return 1;
}
swbf::BruteforceWorker::Options options { /// This class actually implements the brunt of the logic
.targetHash = args.targetHash, .exact = args.exact, .startLength = args.startLength, .endLength = args.endLength struct BruteforceWorker {
/// Options for the worker.
struct Options {
/// The target hash to find matches for.
std::uint32_t targetHash;
/// If `startLength` should be treated as the code length.
bool exact;
std::uint32_t startLength;
std::uint32_t endLength;
}; };
BruteMain(options); constexpr BruteforceWorker(unsigned tid, const Options& options) : options(options), threadIndex(tid) {}
/// Public-facing driver function - the thread pool runs this.
void Bruteforce(char prefix) {
if(options.exact) {
BruteforceForLength(prefix, options.startLength);
} else {
for(std::uint32_t i = options.startLength; i <= options.endLength; ++i)
BruteforceForLength(prefix, i);
}
DisplayData().done = true;
}
private:
void BruteforceForLength(char prefix, std::uint32_t length) {
DisplayData().codeString.resize(length);
test_buffer.resize(length, 'a');
test_buffer[0] = prefix;
// test all possible combinations
while(true) {
hash = SwsfScramble(test_buffer);
// There was a match!
if(hash == options.targetHash)
std::format_to(FputcIterator(stderr), "match: {} ({:08x})\n", test_buffer, hash);
CopyDisplayData();
if(!NextCode(test_buffer, 1))
break;
}
}
void CopyDisplayData() {
memcpy(DisplayData().codeString.data(), test_buffer.data(), test_buffer.length());
DisplayData().codeHash = hash;
}
constexpr ThreadInfoData& DisplayData() { return infoData[threadIndex]; }
Options options;
unsigned threadIndex;
std::string test_buffer;
std::uint32_t hash;
};
int main() {
asio::io_context ioc;
asio::thread_pool pool(THREAD_COUNT);
auto threadIndex = 0u;
BruteforceWorker::Options options {
.targetHash = 0x2c73af55,
.exact = true,
.startLength = 8
};
// post worker threads to run onto the thread pool & wait for them to complete
for(int i = 0; i < THREAD_COUNT; ++i)
asio::post(pool, [&, tid = threadIndex++]() {
BruteforceWorker state(tid, options);
infoData[tid].threadIndex = tid;
state.Bruteforce('a' + tid);
});
bool done = false;
while(!done) {
int doneIndex = 0;
for(auto& d : infoData) {
if(d.done)
doneIndex++;
d.DisplayProgress();
}
if(doneIndex == THREAD_COUNT)
done = true;
std::this_thread::sleep_for(std::chrono::milliseconds(66));
}
pool.join(); // just in case!
return 0; return 0;
} }

View File

@ -1,25 +0,0 @@
#include <cctype>
#include <cstdint>
#include <string_view>
namespace swbf {
/// This is a constexpr-safe zero-allocation version of the algorithm
/// the "Scramble" ConsoleScript hash uses.
constexpr std::uint32_t SwsfScramble(std::string_view code) {
std::uint32_t tally {};
auto cycle = [&tally](char c) { tally = c + (tally * 5); };
// "code_" is prepended and cycled to the input string
cycle('c');
cycle('o');
cycle('d');
cycle('e');
cycle('_');
// the input string is also made lowercase
for(auto c : code)
cycle(std::tolower(c));
return tally;
}
} // namespace swbf

View File

@ -1,137 +0,0 @@
#include "worker.hpp"
#include <boost/asio/io_context.hpp>
#include <boost/asio/post.hpp>
#include <boost/asio/thread_pool.hpp>
#include <cstring>
#include <vector>
#include <thread>
#include "ansi.hpp"
#include "fprint.hpp"
#include "scramble.hpp"
namespace asio = boost::asio;
namespace swbf {
/// This class implements the display of progress
struct ThreadInfoData {
ThreadInfoData() { codeString.resize(MAX_CODE_LENGTH); }
std::uint32_t threadIndex;
std::string codeString;
std::uint32_t codeHash;
bool done = false;
void DisplayProgress() {
if(!done)
swbf::fprint(stdout, "{}Thread {:2}: Trying code {}{} {}({:08x}){}", swbf::ansi::Line(threadIndex), threadIndex,
swbf::ansi::Color(172), codeString, swbf::ansi::Color(166), codeHash, swbf::ansi::Reset());
else {
swbf::fprint(stdout, "{}{}Thread {:2}: {}Finished!{}", swbf::ansi::Line(threadIndex), swbf::ansi::ResetLine(), threadIndex,
swbf::ansi::Color(172), swbf::ansi::Reset());
}
std::fflush(stdout);
}
};
namespace {
std::vector<ThreadInfoData> infoData(THREAD_COUNT);
bool NextCode(std::string& buffer, size_t start) {
size_t len = buffer.length();
for(size_t i = len - 1; i >= start; --i) {
char c = buffer[i];
if(c < 'z') {
++buffer[i];
return true;
}
buffer[i] = 'a';
}
return false;
}
} // namespace
bool DisplayThreadInfo() {
int doneIndex = 0;
for(auto& d : infoData) {
if(d.done)
doneIndex++;
d.DisplayProgress();
}
if(doneIndex == THREAD_COUNT)
return true;
else
return false;
}
BruteforceWorker::BruteforceWorker(unsigned tid, const Options& options) : options(options), threadIndex(tid) {
DisplayData().threadIndex = tid;
}
/// Public-facing driver function - the thread pool runs this.
void BruteforceWorker::Bruteforce(char prefix) {
if(options.exact) {
BruteforceForLength(prefix, options.startLength);
} else {
for(std::uint32_t i = options.startLength; i < options.endLength; ++i)
BruteforceForLength(prefix, i);
}
DisplayData().done = true;
}
void BruteforceWorker::BruteforceForLength(char prefix, std::uint32_t length) {
DisplayData().codeString.resize(length);
test_buffer.resize(length, 'a');
test_buffer[0] = prefix;
// test all possible combinations
while(true) {
hash = swbf::SwsfScramble(test_buffer);
// There was a match!
if(hash == options.targetHash)
swbf::fprint(stderr, "match: {} ({:08x})\n", test_buffer, hash);
CopyDisplayData();
if(!NextCode(test_buffer, 1))
break;
}
}
void BruteforceWorker::CopyDisplayData() {
std::memcpy(DisplayData().codeString.data(), test_buffer.data(), test_buffer.length());
DisplayData().codeHash = hash;
}
ThreadInfoData& BruteforceWorker::DisplayData() {
return infoData[threadIndex];
}
void BruteMain(const swbf::BruteforceWorker::Options& options) {
asio::thread_pool pool(swbf::THREAD_COUNT);
auto threadIndex = 0u;
// post worker threads to run onto the thread pool & wait for them to complete
for(int i = 0; i < swbf::THREAD_COUNT; ++i)
asio::post(pool, [&, tid = threadIndex++]() {
swbf::BruteforceWorker state(tid, options);
state.Bruteforce('a' + tid);
});
bool done = false;
while(!done) {
done = swbf::DisplayThreadInfo();
std::this_thread::sleep_for(std::chrono::milliseconds(66));
}
pool.join(); // just in case!
}
} // namespace swbf

View File

@ -1,50 +0,0 @@
#pragma once
#include <cstdint>
#include <string>
namespace swbf {
constexpr static auto MAX_CODE_LENGTH = 8;
constexpr static auto THREAD_COUNT = 26; // this is a-z
/// private structure
struct ThreadInfoData;
/// Per-thread worker for brute-forcing
struct BruteforceWorker {
/// Options for the worker.
struct Options {
/// The target hash to find matches for.
std::uint32_t targetHash;
/// If `startLength` should be treated as the code length.
bool exact;
std::uint32_t startLength;
std::uint32_t endLength;
};
BruteforceWorker(unsigned tid, const Options& options);
/// Public-facing driver function - the thread pool runs this.
void Bruteforce(char prefix);
private:
void BruteforceForLength(char prefix, std::uint32_t length);
void CopyDisplayData();
ThreadInfoData& DisplayData();
Options options;
unsigned threadIndex;
std::string test_buffer;
std::uint32_t hash;
};
/// returns true when all threads finished
bool DisplayThreadInfo();
void BruteMain(const swbf::BruteforceWorker::Options& options);
} // namespace swbf