Basic U2FDevice implementation.

This commit is contained in:
2019-08-23 13:00:22 +01:00
parent 2987cbe26e
commit 0606772cc3
5 changed files with 68 additions and 74 deletions

109
IO.cpp
View File

@@ -23,25 +23,35 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <sys/types.h> #include <sys/types.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <fcntl.h> #include <fcntl.h>
#include <time.h> #include <ctime>
#include <chrono> #include <chrono>
#include <ratio> #include <ratio>
#include <array>
#include <string>
#include <stdexcept>
#include <memory>
#include <cstdio>
#include <android/log.h>
#include "u2f.hpp" #include "u2f.hpp"
#include "Macro.hpp" #include "Macro.hpp"
#include "U2FDevice.hpp" #include "U2FDevice.hpp"
#include <array>
using namespace std; using namespace std;
bool bytesAvailable(const size_t count); bool bytesAvailable(size_t count);
vector<uint8_t>& getBuffer(); vector<uint8_t>& getBuffer();
string binaryDirectory{};
string cacheDirectory{ DEBUG_STREAMS };
// Thanks to https://stackoverflow.com/a/478960
vector<uint8_t> execOutput(const string &cmd);
void execInput(const string &cmd, const vector<uint8_t> &stdinData);
vector<uint8_t> readNonBlock(const size_t count) vector<uint8_t> readNonBlock(const size_t count)
{ {
if (!bytesAvailable(count)) if (!bytesAvailable(count))
{
return vector<uint8_t>{}; return vector<uint8_t>{};
}
auto &buffer = getBuffer(); auto &buffer = getBuffer();
auto buffStart = buffer.begin(), buffEnd = buffer.begin() + count; auto buffStart = buffer.begin(), buffEnd = buffer.begin() + count;
@@ -53,33 +63,20 @@ vector<uint8_t> readNonBlock(const size_t count)
return bytes; return bytes;
} }
void write(const uint8_t* bytes, const size_t count) void write(const vector<uint8_t> &bytes)
{ {
size_t totalBytes = 0; __android_log_print(ANDROID_LOG_DEBUG, "U2FAndroid", "Writing %zu bytes", bytes.size());
auto hostDescriptor = *getHostDescriptor(); execInput("su -c \"" + binaryDirectory + "/U2FAndroid_Write\"", bytes);
while (totalBytes < count)
{
auto writtenBytes = write(hostDescriptor, bytes + totalBytes, count - totalBytes);
if (writtenBytes > 0)
totalBytes += writtenBytes;
else if (errno != 0 && errno != EAGAIN && errno != EWOULDBLOCK) //Expect file blocking behaviour
ERR();
}
errno = 0;
} }
bool bytesAvailable(const size_t count) bool bytesAvailable(const size_t count)
{ {
auto startTime = std::chrono::high_resolution_clock::now(); auto startTime = std::chrono::high_resolution_clock::now();
const timespec iterDelay{ 0, 1000 }; const timespec iterDelay{ 0, 10000000 };
chrono::duration<double, milli> delay{ 0 }; chrono::duration<double, milli> delay{ 0 };
while (delay.count() < U2FHID_TRANS_TIMEOUT && contProc) while (delay.count() < U2FHID_TRANS_TIMEOUT)
{ {
delay = chrono::high_resolution_clock::now() - startTime;
if (getBuffer().size() >= count) { if (getBuffer().size() >= count) {
#ifdef DEBUG_MSGS #ifdef DEBUG_MSGS
clog << "Requested " << count << " bytes" << endl; clog << "Requested " << count << " bytes" << endl;
@@ -87,6 +84,7 @@ bool bytesAvailable(const size_t count)
return true; return true;
} }
nanosleep(&iterDelay, nullptr); nanosleep(&iterDelay, nullptr);
delay = chrono::high_resolution_clock::now() - startTime;
} }
#ifdef DEBUG_MSGS #ifdef DEBUG_MSGS
@@ -105,44 +103,45 @@ vector<uint8_t>& bufferVar()
vector<uint8_t>& getBuffer() vector<uint8_t>& getBuffer()
{ {
auto &buff = bufferVar(); auto &buff = bufferVar();
array<uint8_t, HID_RPT_SIZE> bytes{}; vector<uint8_t> bytes = execOutput("su -c \"" + binaryDirectory + "/U2FAndroid_Read\"");
auto hostDescriptor = *getHostDescriptor();
while (true) if (!bytes.empty())
{ {
auto readByteCount = read(hostDescriptor, bytes.data(), HID_RPT_SIZE); __android_log_print(ANDROID_LOG_DEBUG, "U2FAndroid", "Reading bytes: got %zu", bytes.size());
buff.insert(buff.end(), bytes.begin(), bytes.end());
if (readByteCount > 0 && readByteCount != HID_RPT_SIZE)
{
//Failed to copy an entire packet in, so log this packet
#ifdef DEBUG_MSGS
cerr << "Only retrieved " << readByteCount << " bytes from expected full packet." << endl;
#endif
}
if (readByteCount > 0)
{
copy(bytes.begin(), bytes.begin() + readByteCount, back_inserter(buff));
#ifdef DEBUG_STREAMS #ifdef DEBUG_STREAMS
fwrite(bytes.data(), 1, readByteCount, getComHostStream().get()); fwrite(bytes.data(), 1, bytes.size(), getComHostStream().get());
#endif #endif
}
else if (errno != EAGAIN && errno != EWOULDBLOCK) //Expect read would block
{
ERR();
#ifdef DEBUG_MSGS
cerr << "Unknown stream error: " << errno << endl;
#endif
break;
}
else
{
errno = 0;
break; //Escape loop if blocking would occur
}
} }
return buff; return buff;
} }
vector<uint8_t> execOutput(const string &cmd)
{
// NOLINT(hicpp-member-init)
array<char, HID_RPT_SIZE> buffer;
vector<uint8_t> result{};
unique_ptr<FILE, decltype(&pclose)> pipe{ popen(cmd.c_str(), "rb"), pclose };
if (!pipe)
throw std::runtime_error("popen() failed!");
while (size_t readBytes = fread(buffer.data(), 1, buffer.size(), pipe.get()))
copy(buffer.begin(), buffer.begin() + readBytes, back_inserter(result));
return result;
}
void execInput(const string &cmd, const vector<uint8_t> &stdinData)
{
assert(stdinData.size() % HID_RPT_SIZE == 0);
size_t writtenBytes = 0;
unique_ptr<FILE, decltype(&pclose)> pipe{ popen(cmd.c_str(), "wb"), pclose };
if (!pipe)
throw std::runtime_error("popen() failed!");
while (writtenBytes < stdinData.size())
writtenBytes += fwrite(stdinData.data(), 1, HID_RPT_SIZE, pipe.get());
}

5
IO.hpp
View File

@@ -21,9 +21,12 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <cstdint> #include <cstdint>
#include <vector> #include <vector>
extern std::string binaryDirectory;
extern std::string cacheDirectory;
//Returns either the number of bytes specified, //Returns either the number of bytes specified,
//or returns empty vector without discarding bytes from HID stream //or returns empty vector without discarding bytes from HID stream
std::vector<uint8_t> readNonBlock(const size_t count); std::vector<uint8_t> readNonBlock(const size_t count);
//Blocking write to HID stream - shouldn't block for too long //Blocking write to HID stream - shouldn't block for too long
void write(const uint8_t* bytes, const size_t count); void write(const std::vector<uint8_t>& data);

View File

@@ -243,7 +243,7 @@ void InitPacket::writePacket()
memcpy(this->buf + 5, &bcnth, 1); memcpy(this->buf + 5, &bcnth, 1);
memcpy(this->buf + 6, &bcntl, 1); memcpy(this->buf + 6, &bcntl, 1);
memcpy(this->buf + 7, data.data(), data.size()); memcpy(this->buf + 7, data.data(), data.size());
write(this->buf, sizeof(this->buf)); write(vector<uint8_t>{ this->buf, this->buf + sizeof(this->buf) });
#ifdef DEBUG_STREAMS #ifdef DEBUG_STREAMS
fwrite(this->buf, 1, sizeof(this->buf), devStream); fwrite(this->buf, 1, sizeof(this->buf), devStream);
@@ -288,7 +288,7 @@ void ContPacket::writePacket()
memcpy(this->buf + 4, &seq, 1); memcpy(this->buf + 4, &seq, 1);
memcpy(this->buf + 5, data.data(), data.size()); memcpy(this->buf + 5, data.data(), data.size());
write(this->buf, HID_RPT_SIZE); write(vector<uint8_t>{this->buf, this->buf + HID_RPT_SIZE });
#ifdef DEBUG_STREAMS #ifdef DEBUG_STREAMS
fwrite(this->buf, HID_RPT_SIZE, 1, devStream); fwrite(this->buf, HID_RPT_SIZE, 1, devStream);

View File

@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
#include "Streams.hpp" #include "Streams.hpp"
#include "IO.hpp"
#include <iostream> #include <iostream>
#include <sys/types.h> #include <sys/types.h>
#include <sys/stat.h> #include <sys/stat.h>
@@ -49,7 +50,7 @@ shared_ptr<int> getHostDescriptor()
#ifdef DEBUG_STREAMS #ifdef DEBUG_STREAMS
shared_ptr<FILE> getComHostStream() shared_ptr<FILE> getComHostStream()
{ {
static shared_ptr<FILE> stream{ fopen(DEBUG_STREAMS "comhost.txt", "wb"), [](FILE *f){ static shared_ptr<FILE> stream{ fopen((cacheDirectory + "comhost.txt").c_str(), "wb"), [](FILE *f){
clog << "Closing comhost stream" << endl; clog << "Closing comhost stream" << endl;
fclose(f); fclose(f);
} }; } };
@@ -62,7 +63,7 @@ shared_ptr<FILE> getComHostStream()
shared_ptr<FILE> getHostPacketStream() shared_ptr<FILE> getHostPacketStream()
{ {
static shared_ptr<FILE> stream{ initHTML(fopen(DEBUG_STREAMS "hostpackets.html", "wb"), "Host Packets"), [](FILE *f){ static shared_ptr<FILE> stream{ initHTML(fopen((cacheDirectory + "hostpackets.html").c_str(), "wb"), "Host Packets"), [](FILE *f){
clog << "Closing hostPackets stream" << endl; clog << "Closing hostPackets stream" << endl;
closeHTML(f); closeHTML(f);
} }; } };
@@ -75,7 +76,7 @@ shared_ptr<FILE> getHostPacketStream()
shared_ptr<FILE> getHostAPDUStream() shared_ptr<FILE> getHostAPDUStream()
{ {
static shared_ptr<FILE> stream{ initHTML(fopen(DEBUG_STREAMS "hostAPDU.html", "wb"), "Host APDU"), [](FILE *f){ static shared_ptr<FILE> stream{ initHTML(fopen((cacheDirectory + "hostAPDU.html").c_str(), "wb"), "Host APDU"), [](FILE *f){
clog << "Closing host APDU stream" << endl; clog << "Closing host APDU stream" << endl;
closeHTML(f); closeHTML(f);
} }; } };
@@ -88,7 +89,7 @@ shared_ptr<FILE> getHostAPDUStream()
shared_ptr<FILE> getComDevStream() shared_ptr<FILE> getComDevStream()
{ {
static shared_ptr<FILE> stream{ fopen(DEBUG_STREAMS "comdev.txt", "wb"), [](FILE *f){ static shared_ptr<FILE> stream{ fopen((cacheDirectory + "comdev.txt").c_str(), "wb"), [](FILE *f){
clog << "Closing comdev stream" << endl; clog << "Closing comdev stream" << endl;
fclose(f); fclose(f);
} }; } };
@@ -101,7 +102,7 @@ shared_ptr<FILE> getComDevStream()
shared_ptr<FILE> getDevPacketStream() shared_ptr<FILE> getDevPacketStream()
{ {
static shared_ptr<FILE> stream{ initHTML(fopen(DEBUG_STREAMS "devpackets.html", "wb"), "Dev Packets"), [](FILE *f){ static shared_ptr<FILE> stream{ initHTML(fopen((cacheDirectory + "devpackets.html").c_str(), "wb"), "Dev Packets"), [](FILE *f){
clog << "Closing devPackets stream" << endl; clog << "Closing devPackets stream" << endl;
closeHTML(f); closeHTML(f);
} }; } };
@@ -114,7 +115,7 @@ shared_ptr<FILE> getDevPacketStream()
shared_ptr<FILE> getDevAPDUStream() shared_ptr<FILE> getDevAPDUStream()
{ {
static shared_ptr<FILE> stream{ initHTML(fopen(DEBUG_STREAMS "devAPDU.html", "wb"), "Dev APDU"), [](FILE *f){ static shared_ptr<FILE> stream{ initHTML(fopen((cacheDirectory + "devAPDU.html").c_str(), "wb"), "Dev APDU"), [](FILE *f){
clog << "Closing dev APDU stream" << endl; clog << "Closing dev APDU stream" << endl;
closeHTML(f); closeHTML(f);
} }; } };

View File

@@ -21,7 +21,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
#include "Storage.hpp" #include "Storage.hpp"
#include "Controller.hpp" #include "Controller.hpp"
#include "LED.hpp" #include "LED.hpp"
#include <signal.h> #include <csignal>
#include <unistd.h> #include <unistd.h>
using namespace std; using namespace std;
@@ -40,9 +40,6 @@ bool initialiseLights(const string& prog) {
{ {
cerr << e.what() << endl; cerr << e.what() << endl;
if (getuid() != 0)
cerr << "Try running as root, using \'sudo " << prog << "\'" << endl;
return false; return false;
} }
@@ -65,9 +62,6 @@ int handleTransactions(const string& prog, const string& privKeyDir)
{ {
cerr << e.what() << endl; cerr << e.what() << endl;
if (getuid() != 0)
cerr << "Try running as root, using \'sudo " << prog << "\'" << endl;
raise(SIGINT); raise(SIGINT);
return EXIT_FAILURE; return EXIT_FAILURE;
} }
@@ -88,9 +82,6 @@ bool deinitialiseLights(const string& prog) {
{ {
cerr << e.what() << endl; cerr << e.what() << endl;
if (getuid() != 0)
cerr << "Try running as root, using \'sudo " << prog << "\'" << endl;
return false; return false;
} }