diff options
author | Jordan Bayles <jophba@chromium.org> | 2019-07-10 14:44:58 -0700 |
---|---|---|
committer | Commit Bot <commit-bot@chromium.org> | 2019-07-10 23:11:04 +0000 |
commit | a26582d3cdec49e4fb0bd5c1da924bf7094f0f5e (patch) | |
tree | b34b7153754e0b22e1a1b416291873be07a292a7 /util | |
parent | cc47180a8b4f86bcfce44aed3d51e1d302287a22 (diff) | |
download | openscreen-a26582d3cdec49e4fb0bd5c1da924bf7094f0f5e.tar.gz |
Delete osp_base and move files to new homes
This patch is the second and major patch in the process of removing the
osp_base folder from Open Screen. Based on the design plan here:
https://docs.google.com/document/d/1LGV8tXdDeIH38MYlNF2XJNG49pec-64nWkS0jjnJNk4/edit#heading=h.ny8tc2v4ek9m
This patch moves most of the files in osp_base to new homes in platform,
excepting files that have been moved to the new util/ folder.
Change-Id: I6e5f1d13cf20806bcc41185a842eb0b293606306
Reviewed-on: https://chromium-review.googlesource.com/c/openscreen/+/1695736
Reviewed-by: Jordan Bayles <jophba@chromium.org>
Reviewed-by: mark a. foltz <mfoltz@chromium.org>
Commit-Queue: Jordan Bayles <jophba@chromium.org>
Diffstat (limited to 'util')
30 files changed, 2412 insertions, 0 deletions
diff --git a/util/BUILD.gn b/util/BUILD.gn new file mode 100644 index 00000000..65b16c62 --- /dev/null +++ b/util/BUILD.gn @@ -0,0 +1,61 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build_overrides/build.gni") + +source_set("util") { + sources = [ + "alarm.cc", + "alarm.h", + "big_endian.cc", + "big_endian.h", + "crypto/openssl_util.cc", + "crypto/openssl_util.h", + "crypto/rsa_private_key.cc", + "crypto/rsa_private_key.h", + "crypto/secure_hash.cc", + "crypto/secure_hash.h", + "crypto/sha2.cc", + "crypto/sha2.h", + "json/json_reader.cc", + "json/json_reader.h", + "json/json_writer.cc", + "json/json_writer.h", + "std_util.h", + "stringprintf.h", + ] + + deps = [ + "../third_party/abseil", + "../third_party/boringssl", + "../third_party/jsoncpp", + ] + + configs += [ "../build:allow_build_from_embedder" ] +} + +source_set("util_unittests") { + testonly = true + + sources = [ + "alarm_unittest.cc", + "big_endian_unittest.cc", + "crypto/rsa_private_key_unittest.cc", + "crypto/secure_hash_unittest.cc", + "crypto/sha2_unittest.cc", + "json/json_reader_unittest.cc", + "json/json_writer_unittest.cc", + ] + + deps = [ + ":util", + "../third_party/abseil", + "../third_party/boringssl", + "../third_party/googletest:gmock", + "../third_party/googletest:gtest", + "../third_party/jsoncpp", + ] + + configs += [ "../build:allow_build_from_embedder" ] +} diff --git a/util/DEPS b/util/DEPS new file mode 100644 index 00000000..4410d925 --- /dev/null +++ b/util/DEPS @@ -0,0 +1,7 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +include_rules = [ + '+platform/api', +] diff --git a/util/README.md b/util/README.md new file mode 100644 index 00000000..aa0670d3 --- /dev/null +++ b/util/README.md @@ -0,0 +1,8 @@ +# Utility Code + +The util/ folder is meant to house core utility classes and logic that can be +used by everything else in the Open Screen repository. Code here is permitted +to include platform/api/ -- same as the rest of the repository. Includes things +like string utils, the JSON serializer, our std_util.h header, and the alarm. +Classes that are shared by multiple features generally should not be placed +here, instead favoring the platform/ folder.
\ No newline at end of file diff --git a/util/alarm.cc b/util/alarm.cc new file mode 100644 index 00000000..abc06262 --- /dev/null +++ b/util/alarm.cc @@ -0,0 +1,124 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "util/alarm.h" + +#include "platform/api/logging.h" + +namespace openscreen { + +class Alarm::CancelableFunctor { + public: + explicit CancelableFunctor(Alarm* alarm) : alarm_(alarm) { + OSP_DCHECK(alarm_); + OSP_DCHECK(!alarm_->queued_fire_); + alarm_->queued_fire_ = this; + } + + ~CancelableFunctor() { Cancel(); } + + CancelableFunctor(CancelableFunctor&& other) : alarm_(other.alarm_) { + other.alarm_ = nullptr; + if (alarm_) { + OSP_DCHECK_EQ(alarm_->queued_fire_, &other); + alarm_->queued_fire_ = this; + } + } + + CancelableFunctor& operator=(CancelableFunctor&& other) { + Cancel(); + alarm_ = other.alarm_; + other.alarm_ = nullptr; + if (alarm_) { + OSP_DCHECK_EQ(alarm_->queued_fire_, &other); + alarm_->queued_fire_ = this; + } + return *this; + } + + void operator()() noexcept { + if (alarm_) { + OSP_DCHECK_EQ(alarm_->queued_fire_, this); + alarm_->queued_fire_ = nullptr; + alarm_->TryInvoke(); + alarm_ = nullptr; + } + } + + void Cancel() { + if (alarm_) { + OSP_DCHECK_EQ(alarm_->queued_fire_, this); + alarm_->queued_fire_ = nullptr; + alarm_ = nullptr; + } + } + + private: + Alarm* alarm_; +}; + +Alarm::Alarm(platform::ClockNowFunctionPtr now_function, + platform::TaskRunner* task_runner) + : now_function_(now_function), task_runner_(task_runner) { + OSP_DCHECK(now_function_); + OSP_DCHECK(task_runner_); +} + +Alarm::~Alarm() { + if (queued_fire_) { + queued_fire_->Cancel(); + OSP_DCHECK(!queued_fire_); + } +} + +void Alarm::Cancel() { + scheduled_task_ = platform::TaskRunner::Task(); +} + +void Alarm::ScheduleWithTask(platform::TaskRunner::Task task, + platform::Clock::time_point alarm_time) { + OSP_DCHECK(task.valid()); + + scheduled_task_ = std::move(task); + alarm_time_ = alarm_time; + + // Ensure that a later firing will occur, and not too late. + if (queued_fire_) { + if (next_fire_time_ <= alarm_time) { + return; + } + queued_fire_->Cancel(); + OSP_DCHECK(!queued_fire_); + } + InvokeLater(now_function_(), alarm_time); +} + +void Alarm::InvokeLater(platform::Clock::time_point now, + platform::Clock::time_point fire_time) { + OSP_DCHECK(!queued_fire_); + next_fire_time_ = fire_time; + // Note: Instantiating the CancelableFunctor below sets |this->queued_fire_|. + task_runner_->PostTaskWithDelay(CancelableFunctor(this), fire_time - now); +} + +void Alarm::TryInvoke() { + if (!scheduled_task_.valid()) { + return; // This Alarm was canceled in the meantime. + } + + // If this is an early firing, re-schedule for later. This happens if + // Schedule() was called again before this firing had occurred. + const platform::Clock::time_point now = now_function_(); + if (now < alarm_time_) { + InvokeLater(now, alarm_time_); + return; + } + + // Move the client Task to the stack before executing, just in case the task + // itself: a) calls any Alarm methods re-entrantly, or b) causes the + // destruction of this Alarm instance. + std::move(scheduled_task_)(); // WARNING: |this| is not valid after here! +} + +} // namespace openscreen diff --git a/util/alarm.h b/util/alarm.h new file mode 100644 index 00000000..e5e855b8 --- /dev/null +++ b/util/alarm.h @@ -0,0 +1,98 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UTIL_ALARM_H_ +#define UTIL_ALARM_H_ + +#include "platform/api/task_runner.h" +#include "platform/api/time.h" + +namespace openscreen { + +// A simple mechanism for running one Task in the future, but also allow for +// canceling the Task before it runs and/or re-scheduling a replacement Task to +// run at a different time. This mechanism is also scoped to its lifetime: if an +// Alarm is destroyed while it is scheduled, the Task is automatically canceled. +// It is safe for the client's Task to make re-entrant calls into all Alarm +// methods. +// +// Example use case: When using a TaskRunner, an object can safely schedule a +// callback into one of its instance methods (without the possibility of the +// Task executing after the object is destroyed). +// +// Design: In order to support efficient, arbitrary canceling and re-scheduling +// by the client, the Alarm posts a cancelable functor to the TaskRunner which, +// when invoked, then checks to see whether the Alarm instance still exists and, +// if so, calls its TryInvoke() method. The TryInvoke() method then determines: +// a) whether the invocation time of the client's Task has changed; and b) +// whether the Alarm was canceled in the meantime. From this, it either: a) does +// nothing; b) re-posts a new cancelable functor to the TaskRunner, to try +// running the client's Task later; or c) runs the client's Task. +class Alarm { + public: + Alarm(platform::ClockNowFunctionPtr now_function, + platform::TaskRunner* task_runner); + ~Alarm(); + + // The design requires that Alarm instances not be copied or moved. + Alarm(const Alarm&) = delete; + Alarm& operator=(const Alarm&) = delete; + Alarm(Alarm&&) = delete; + Alarm& operator=(Alarm&&) = delete; + + // Schedule the |functor| to be invoked at |alarm_time|. If this Alarm was + // already scheduled, the prior scheduling is canceled. The Functor can be any + // callable target (e.g., function, lambda-expression, std::bind result, + // etc.). + template <typename Functor> + inline void Schedule(Functor functor, + platform::Clock::time_point alarm_time) { + ScheduleWithTask(platform::TaskRunner::Task(std::move(functor)), + alarm_time); + } + + // Cancels an already-scheduled task from running, or no-op. + void Cancel(); + + // See comments for Schedule(). Generally, callers will want to call + // Schedule() instead of this, for more-convenient caller-side syntax, unless + // they already have a Task to pass-in. + void ScheduleWithTask(platform::TaskRunner::Task task, + platform::Clock::time_point alarm_time); + + private: + // A move-only functor that holds a raw pointer back to |this| and can be + // canceled before its call operator is invoked. When canceled, its call + // operator becomes a no-op. + class CancelableFunctor; + + // Posts a delayed call to TryInvoke() to the TaskRunner. + void InvokeLater(platform::Clock::time_point now, + platform::Clock::time_point fire_time); + + // Examines whether to invoke the client's Task now; or try again later; or + // just do nothing. See class-level design comments. + void TryInvoke(); + + const platform::ClockNowFunctionPtr now_function_; + platform::TaskRunner* const task_runner_; + + // This is the task the client wants to have run at a specific point-in-time. + // This is NOT the task that Alarm provides to the TaskRunner. + platform::TaskRunner::Task scheduled_task_; + platform::Clock::time_point alarm_time_{}; + + // When non-null, there is a task in the TaskRunner's queue that will call + // TryInvoke() some time in the future. This member is exclusively maintained + // by the CancelableFunctor class methods. + CancelableFunctor* queued_fire_ = nullptr; + + // When the CancelableFunctor is scheduled to run. It may possibly execute + // later than this, if the TaskRunner is falling behind. + platform::Clock::time_point next_fire_time_{}; +}; + +} // namespace openscreen + +#endif // UTIL_ALARM_H_ diff --git a/util/alarm_unittest.cc b/util/alarm_unittest.cc new file mode 100644 index 00000000..71f570a0 --- /dev/null +++ b/util/alarm_unittest.cc @@ -0,0 +1,136 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "util/alarm.h" + +#include <algorithm> + +#include "gtest/gtest.h" +#include "platform/test/fake_clock.h" +#include "platform/test/fake_task_runner.h" + +namespace openscreen { +namespace { + +class AlarmTest : public testing::Test { + public: + platform::FakeClock* clock() { return &clock_; } + platform::TaskRunner* task_runner() { return &task_runner_; } + Alarm* alarm() { return &alarm_; } + + private: + platform::FakeClock clock_{platform::Clock::now()}; + platform::FakeTaskRunner task_runner_{&clock_}; + Alarm alarm_{&platform::FakeClock::now, &task_runner_}; +}; + +TEST_F(AlarmTest, RunsTaskAsClockAdvances) { + constexpr platform::Clock::duration kDelay = std::chrono::milliseconds(20); + + const platform::Clock::time_point alarm_time = + platform::FakeClock::now() + kDelay; + platform::Clock::time_point actual_run_time{}; + alarm()->Schedule([&]() { actual_run_time = platform::FakeClock::now(); }, + alarm_time); + // Confirm the lambda did not run immediately. + ASSERT_EQ(platform::Clock::time_point{}, actual_run_time); + + // Confirm the lambda does not run until the necessary delay has elapsed. + clock()->Advance(kDelay / 2); + ASSERT_EQ(platform::Clock::time_point{}, actual_run_time); + + // Confirm the lambda is called when the necessary delay has elapsed. + clock()->Advance(kDelay / 2); + ASSERT_EQ(alarm_time, actual_run_time); + + // Confirm the lambda is only run once. + clock()->Advance(kDelay * 100); + ASSERT_EQ(alarm_time, actual_run_time); +} + +TEST_F(AlarmTest, CancelsTaskWhenGoingOutOfScope) { + constexpr platform::Clock::duration kDelay = std::chrono::milliseconds(20); + constexpr platform::Clock::time_point kNever{}; + + platform::Clock::time_point actual_run_time{}; + { + Alarm scoped_alarm(&platform::FakeClock::now, task_runner()); + const platform::Clock::time_point alarm_time = + platform::FakeClock::now() + kDelay; + scoped_alarm.Schedule( + [&]() { actual_run_time = platform::FakeClock::now(); }, alarm_time); + // |scoped_alarm| is destroyed. + } + + // Confirm the lambda has never and will never run. + ASSERT_EQ(kNever, actual_run_time); + clock()->Advance(kDelay * 100); + ASSERT_EQ(kNever, actual_run_time); +} + +TEST_F(AlarmTest, Cancels) { + constexpr platform::Clock::duration kDelay = std::chrono::milliseconds(20); + + const platform::Clock::time_point alarm_time = + platform::FakeClock::now() + kDelay; + platform::Clock::time_point actual_run_time{}; + alarm()->Schedule([&]() { actual_run_time = platform::FakeClock::now(); }, + alarm_time); + + // Advance the clock for half the delay, and confirm the lambda has not run + // yet. + clock()->Advance(kDelay / 2); + ASSERT_EQ(platform::Clock::time_point{}, actual_run_time); + + // Cancel and then advance the clock well past the delay, and confirm the + // lambda has never run. + alarm()->Cancel(); + clock()->Advance(kDelay * 100); + ASSERT_EQ(platform::Clock::time_point{}, actual_run_time); +} + +TEST_F(AlarmTest, CancelsAndRearms) { + constexpr platform::Clock::duration kShorterDelay = + std::chrono::milliseconds(10); + constexpr platform::Clock::duration kLongerDelay = + std::chrono::milliseconds(100); + + // Run the test twice: Once when scheduling first with a long delay, then a + // shorter delay; and once when scheduling first with a short delay, then a + // longer delay. This is to test Alarm's internal scheduling/firing logic. + for (int do_longer_then_shorter = 0; do_longer_then_shorter <= 1; + ++do_longer_then_shorter) { + const auto delay1 = do_longer_then_shorter ? kLongerDelay : kShorterDelay; + const auto delay2 = do_longer_then_shorter ? kShorterDelay : kLongerDelay; + + int count1 = 0; + alarm()->Schedule([&]() { ++count1; }, platform::FakeClock::now() + delay1); + + // Advance the clock for half of |delay1|, and confirm the lambda that + // increments the variable does not run. + ASSERT_EQ(0, count1); + clock()->Advance(delay1 / 2); + ASSERT_EQ(0, count1); + + // Schedule a different lambda, that increments a different variable, to run + // after |delay2|. + int count2 = 0; + alarm()->Schedule([&]() { ++count2; }, platform::FakeClock::now() + delay2); + + // Confirm the second scheduling will fire at the right moment. + clock()->Advance(delay2 / 2); + ASSERT_EQ(0, count2); + clock()->Advance(delay2 / 2); + ASSERT_EQ(1, count2); + + // Confirm the second scheduling never fires a second time, and also that + // the first one doesn't fire. + clock()->Advance(std::max(delay1, delay2) * 100); + ASSERT_EQ(0, count1); + ASSERT_EQ(1, count2); + } +} + +} // namespace +} // namespace openscreen diff --git a/util/big_endian.cc b/util/big_endian.cc new file mode 100644 index 00000000..d5658900 --- /dev/null +++ b/util/big_endian.cc @@ -0,0 +1,33 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "util/big_endian.h" + +namespace openscreen { + +BigEndianReader::BigEndianReader(const uint8_t* buffer, size_t length) + : BigEndianBuffer(buffer, length) {} + +bool BigEndianReader::Read(size_t length, void* out) { + const uint8_t* read_position = current(); + if (Skip(length)) { + memcpy(out, read_position, length); + return true; + } + return false; +} + +BigEndianWriter::BigEndianWriter(uint8_t* buffer, size_t length) + : BigEndianBuffer(buffer, length) {} + +bool BigEndianWriter::Write(const void* buffer, size_t length) { + uint8_t* write_position = current(); + if (Skip(length)) { + memcpy(write_position, buffer, length); + return true; + } + return false; +} + +} // namespace openscreen
\ No newline at end of file diff --git a/util/big_endian.h b/util/big_endian.h new file mode 100644 index 00000000..6c94ca5e --- /dev/null +++ b/util/big_endian.h @@ -0,0 +1,195 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UTIL_BIG_ENDIAN_H_ +#define UTIL_BIG_ENDIAN_H_ + +#include <stdint.h> + +#include <cstring> +#include <type_traits> + +namespace openscreen { + +//////////////////////////////////////////////////////////////////////////////// +// Note: All of the functions here are defined inline, as any half-decent +// compiler will optimize them to a single integer constant or single +// instruction on most architectures. +//////////////////////////////////////////////////////////////////////////////// + +// Returns true if this code is running on a big-endian architecture. +inline bool IsBigEndianArchitecture() { + const uint16_t kTestWord = 0x0100; + uint8_t bytes[sizeof(kTestWord)]; + memcpy(bytes, &kTestWord, sizeof(bytes)); + return !!bytes[0]; +} + +// Returns the bytes of |x| in reverse order. This is only defined for 16-, 32-, +// and 64-bit unsigned integers. +template <typename Integer> +Integer ByteSwap(Integer x); + +template <> +inline uint8_t ByteSwap(uint8_t x) { + return x; +} + +#if defined(__clang__) || defined(__GNUC__) + +template <> +inline uint64_t ByteSwap(uint64_t x) { + return __builtin_bswap64(x); +} +template <> +inline uint32_t ByteSwap(uint32_t x) { + return __builtin_bswap32(x); +} +template <> +inline uint16_t ByteSwap(uint16_t x) { + return __builtin_bswap16(x); +} + +#elif defined(_MSC_VER) + +template <> +inline uint64_t ByteSwap(uint64_t x) { + return _byteswap_uint64(x); +} +template <> +inline uint32_t ByteSwap(uint32_t x) { + return _byteswap_ulong(x); +} +template <> +inline uint16_t ByteSwap(uint16_t x) { + return _byteswap_ushort(x); +} + +#else + +#include <byteswap.h> + +template <> +inline uint64_t ByteSwap(uint64_t x) { + return bswap_64(x); +} +template <> +inline uint32_t ByteSwap(uint32_t x) { + return bswap_32(x); +} +template <> +inline uint16_t ByteSwap(uint16_t x) { + return bswap_16(x); +} + +#endif + +// Read a POD integer from |src| in big-endian byte order, returning the integer +// in native byte order. +template <typename Integer> +inline Integer ReadBigEndian(const void* src) { + Integer result; + memcpy(&result, src, sizeof(result)); + if (!IsBigEndianArchitecture()) { + result = ByteSwap<typename std::make_unsigned<Integer>::type>(result); + } + return result; +} + +// Write a POD integer |val| to |dest| in big-endian byte order. +template <typename Integer> +inline void WriteBigEndian(Integer val, void* dest) { + if (!IsBigEndianArchitecture()) { + val = ByteSwap<typename std::make_unsigned<Integer>::type>(val); + } + memcpy(dest, &val, sizeof(val)); +} + +template <class T> +class BigEndianBuffer { + public: + class Cursor { + public: + Cursor(BigEndianBuffer* buffer) + : buffer_(buffer), origin_(buffer_->current_) {} + Cursor(const Cursor& other) = delete; + Cursor(Cursor&& other) = delete; + ~Cursor() { buffer_->current_ = origin_; } + + Cursor& operator=(const Cursor& other) = delete; + Cursor& operator=(Cursor&& other) = delete; + + void Commit() { origin_ = buffer_->current_; } + + T* origin() { return origin_; } + size_t delta() { return buffer_->current_ - origin_; } + + private: + BigEndianBuffer* buffer_; + T* origin_; + }; + + bool Skip(size_t length) { + if (current_ + length > end_) { + return false; + } + current_ += length; + return true; + } + + T* begin() const { return begin_; } + T* current() const { return current_; } + T* end() const { return end_; } + size_t length() const { return end_ - begin_; } + size_t remaining() const { return end_ - current_; } + size_t offset() const { return current_ - begin_; } + + BigEndianBuffer(T* buffer, size_t length) + : begin_(buffer), current_(buffer), end_(buffer + length) {} + BigEndianBuffer(const BigEndianBuffer&) = delete; + BigEndianBuffer& operator=(const BigEndianBuffer&) = delete; + + private: + T* begin_; + T* current_; + T* end_; +}; + +class BigEndianReader : public BigEndianBuffer<const uint8_t> { + public: + BigEndianReader(const uint8_t* buffer, size_t length); + + template <typename T> + bool Read(T* out) { + const uint8_t* read_position = current(); + if (Skip(sizeof(T))) { + *out = ReadBigEndian<T>(read_position); + return true; + } + return false; + } + + bool Read(size_t length, void* out); +}; + +class BigEndianWriter : public BigEndianBuffer<uint8_t> { + public: + BigEndianWriter(uint8_t* buffer, size_t length); + + template <typename T> + bool Write(T value) { + uint8_t* write_position = current(); + if (Skip(sizeof(T))) { + WriteBigEndian<T>(value, write_position); + return true; + } + return false; + } + + bool Write(const void* buffer, size_t length); +}; + +} // namespace openscreen + +#endif // UTIL_BIG_ENDIAN_H_ diff --git a/util/big_endian_unittest.cc b/util/big_endian_unittest.cc new file mode 100644 index 00000000..99b21a1d --- /dev/null +++ b/util/big_endian_unittest.cc @@ -0,0 +1,403 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "util/big_endian.h" + +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +namespace openscreen { +namespace { + +// Tests that ReadBigEndian() correctly imports values from various offsets in +// memory. +TEST(BigEndianTest, ReadValues) { + const uint8_t kInput[] = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, + 0xb, 0xc, 0xd, 0xe, 0xf, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, + 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, + }; + + EXPECT_EQ(UINT8_C(0x05), ReadBigEndian<uint8_t>(kInput + 5)); + EXPECT_EQ(UINT8_C(0xff), ReadBigEndian<uint8_t>(kInput + 16)); + EXPECT_EQ(7, ReadBigEndian<int8_t>(kInput + 7)); + EXPECT_EQ(-1, ReadBigEndian<int8_t>(kInput + 17)); + + EXPECT_EQ(UINT16_C(0x0001), ReadBigEndian<uint16_t>(kInput)); + EXPECT_EQ(UINT16_C(0x0102), ReadBigEndian<uint16_t>(kInput + 1)); + EXPECT_EQ(UINT16_C(0x0203), ReadBigEndian<uint16_t>(kInput + 2)); + EXPECT_EQ(-1, ReadBigEndian<int16_t>(kInput + 16)); + EXPECT_EQ(-2, ReadBigEndian<int16_t>(kInput + 17)); + + EXPECT_EQ(UINT32_C(0x03040506), ReadBigEndian<uint32_t>(kInput + 3)); + EXPECT_EQ(UINT32_C(0x04050607), ReadBigEndian<uint32_t>(kInput + 4)); + EXPECT_EQ(UINT32_C(0x05060708), ReadBigEndian<uint32_t>(kInput + 5)); + EXPECT_EQ(-1, ReadBigEndian<int32_t>(kInput + 19)); + EXPECT_EQ(-2, ReadBigEndian<int32_t>(kInput + 20)); + + EXPECT_EQ(UINT64_C(0x0001020304050607), ReadBigEndian<uint64_t>(kInput)); + EXPECT_EQ(UINT64_C(0x0102030405060708), ReadBigEndian<uint64_t>(kInput + 1)); + EXPECT_EQ(UINT64_C(0x0203040506070809), ReadBigEndian<uint64_t>(kInput + 2)); + EXPECT_EQ(-1, ReadBigEndian<int64_t>(kInput + 24)); + EXPECT_EQ(-2, ReadBigEndian<int64_t>(kInput + 25)); +} + +// Tests that WriteBigEndian() correctly writes-out values to various offsets in +// memory. This test assumes ReadBigEndian() is working, using it to verify that +// WriteBigEndian() is working. +TEST(BigEndianTest, WriteValues) { + uint8_t scratch[16]; + + WriteBigEndian<uint8_t>(0x07, scratch); + EXPECT_EQ(UINT8_C(0x07), ReadBigEndian<uint8_t>(scratch)); + WriteBigEndian<uint8_t>(0xf0, scratch + 1); + EXPECT_EQ(UINT8_C(0xf0), ReadBigEndian<uint8_t>(scratch + 1)); + WriteBigEndian<int8_t>(23, scratch + 2); + EXPECT_EQ(23, ReadBigEndian<int8_t>(scratch + 2)); + WriteBigEndian<int8_t>(-25, scratch + 3); + EXPECT_EQ(-25, ReadBigEndian<int8_t>(scratch + 3)); + + WriteBigEndian<uint16_t>(0x0102, scratch); + EXPECT_EQ(UINT16_C(0x0102), ReadBigEndian<uint16_t>(scratch)); + WriteBigEndian<uint16_t>(0x0304, scratch + 1); + EXPECT_EQ(UINT16_C(0x0304), ReadBigEndian<uint16_t>(scratch + 1)); + WriteBigEndian<uint16_t>(0x0506, scratch + 2); + EXPECT_EQ(UINT16_C(0x0506), ReadBigEndian<uint16_t>(scratch + 2)); + WriteBigEndian<int16_t>(42, scratch + 3); + EXPECT_EQ(42, ReadBigEndian<int16_t>(scratch + 3)); + WriteBigEndian<int16_t>(-1, scratch + 4); + EXPECT_EQ(-1, ReadBigEndian<int16_t>(scratch + 4)); + WriteBigEndian<int16_t>(-2, scratch + 5); + EXPECT_EQ(-2, ReadBigEndian<int16_t>(scratch + 5)); + + WriteBigEndian<uint32_t>(UINT32_C(0x03040506), scratch); + EXPECT_EQ(UINT32_C(0x03040506), ReadBigEndian<uint32_t>(scratch)); + WriteBigEndian<uint32_t>(UINT32_C(0x0708090a), scratch + 1); + EXPECT_EQ(UINT32_C(0x0708090a), ReadBigEndian<uint32_t>(scratch + 1)); + WriteBigEndian<uint32_t>(UINT32_C(0x0b0c0d0e), scratch + 2); + EXPECT_EQ(UINT32_C(0x0b0c0d0e), ReadBigEndian<uint32_t>(scratch + 2)); + WriteBigEndian<int32_t>(42, scratch + 3); + EXPECT_EQ(42, ReadBigEndian<int32_t>(scratch + 3)); + WriteBigEndian<int32_t>(-1, scratch + 4); + EXPECT_EQ(-1, ReadBigEndian<int32_t>(scratch + 4)); + WriteBigEndian<int32_t>(-2, scratch + 5); + EXPECT_EQ(-2, ReadBigEndian<int32_t>(scratch + 5)); + + WriteBigEndian<uint64_t>(UINT64_C(0x0f0e0d0c0b0a0908), scratch); + EXPECT_EQ(UINT64_C(0x0f0e0d0c0b0a0908), ReadBigEndian<uint64_t>(scratch)); + WriteBigEndian<uint64_t>(UINT64_C(0x0708090a0b0c0d0e), scratch + 1); + EXPECT_EQ(UINT64_C(0x0708090a0b0c0d0e), ReadBigEndian<uint64_t>(scratch + 1)); + WriteBigEndian<uint64_t>(UINT64_C(0x99aa88bb77cc66dd), scratch + 2); + EXPECT_EQ(UINT64_C(0x99aa88bb77cc66dd), ReadBigEndian<uint64_t>(scratch + 2)); + WriteBigEndian<int64_t>(42, scratch + 3); + EXPECT_EQ(42, ReadBigEndian<int64_t>(scratch + 3)); + WriteBigEndian<int64_t>(-1, scratch + 4); + EXPECT_EQ(-1, ReadBigEndian<int64_t>(scratch + 4)); + WriteBigEndian<int64_t>(-2, scratch + 5); + EXPECT_EQ(-2, ReadBigEndian<int64_t>(scratch + 5)); +} + +TEST(BigEndianReaderTest, ConstructWithValidBuffer) { + uint8_t data[64]; + BigEndianReader reader(data, sizeof(data)); + + EXPECT_EQ(reader.begin(), data); + EXPECT_EQ(reader.current(), data); + EXPECT_EQ(reader.end(), data + 64); + EXPECT_EQ(reader.offset(), size_t(0)); + EXPECT_EQ(reader.remaining(), size_t(64)); + EXPECT_EQ(reader.length(), size_t(64)); +} + +TEST(BigEndianReaderTest, SkipLessThanRemaining) { + uint8_t data[64]; + BigEndianReader reader(data, sizeof(data)); + + EXPECT_TRUE(reader.Skip(16)); + + EXPECT_EQ(reader.begin(), data); + EXPECT_EQ(reader.current(), data + 16); + EXPECT_EQ(reader.end(), data + 64); + EXPECT_EQ(reader.offset(), size_t(16)); + EXPECT_EQ(reader.remaining(), size_t(48)); + EXPECT_EQ(reader.length(), size_t(64)); +} + +TEST(BigEndianReaderTest, SkipMoreThanRemaining) { + uint8_t data[64]; + BigEndianReader reader(data, sizeof(data)); + + EXPECT_TRUE(reader.Skip(16)); + EXPECT_FALSE(reader.Skip(64)); + + // Check that failed Skip does not modify any pointers or offsets. + EXPECT_EQ(reader.begin(), data); + EXPECT_EQ(reader.current(), data + 16); + EXPECT_EQ(reader.end(), data + 64); + EXPECT_EQ(reader.offset(), size_t(16)); + EXPECT_EQ(reader.remaining(), size_t(48)); + EXPECT_EQ(reader.length(), size_t(64)); +} + +TEST(BigEndianReaderTest, ConstructWithZeroLengthBuffer) { + uint8_t data[8]; + BigEndianReader reader(data, 0); + + EXPECT_EQ(reader.begin(), data); + EXPECT_EQ(reader.current(), data); + EXPECT_EQ(reader.end(), data); + EXPECT_EQ(reader.offset(), size_t(0)); + EXPECT_EQ(reader.remaining(), size_t(0)); + EXPECT_EQ(reader.length(), size_t(0)); + + EXPECT_FALSE(reader.Skip(1)); +} + +TEST(BigEndianReaderTest, ReadValues) { + uint8_t data[17] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, + 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF, 0x10}; + BigEndianReader reader(data, sizeof(data)); + + uint8_t buffer[2]; + EXPECT_TRUE(reader.Read(sizeof(buffer), buffer)); + EXPECT_EQ(buffer[0], UINT8_C(0x0)); + EXPECT_EQ(buffer[1], UINT8_C(0x1)); + + uint8_t u8; + EXPECT_TRUE(reader.Read<uint8_t>(&u8)); + EXPECT_EQ(u8, UINT8_C(0x2)); + + uint16_t u16; + EXPECT_TRUE(reader.Read<uint16_t>(&u16)); + EXPECT_EQ(u16, UINT16_C(0x0304)); + + uint32_t u32; + EXPECT_TRUE(reader.Read<uint32_t>(&u32)); + EXPECT_EQ(u32, UINT32_C(0x05060708)); + + uint64_t u64; + EXPECT_TRUE(reader.Read<uint64_t>(&u64)); + EXPECT_EQ(u64, UINT64_C(0x090A0B0C0D0E0F10)); + + EXPECT_EQ(reader.begin(), data); + EXPECT_EQ(reader.current(), data + 17); + EXPECT_EQ(reader.end(), data + 17); + EXPECT_EQ(reader.offset(), size_t(17)); + EXPECT_EQ(reader.remaining(), size_t(0)); + EXPECT_EQ(reader.length(), size_t(17)); +} + +TEST(BigEndianReaderTest, RespectLength) { + uint8_t data[8]; + BigEndianReader reader(data, sizeof(data)); + + // 8 left + EXPECT_FALSE(reader.Skip(9)); + EXPECT_TRUE(reader.Skip(1)); + + // 7 left + uint64_t u64; + EXPECT_FALSE(reader.Read<uint64_t>(&u64)); + EXPECT_TRUE(reader.Skip(4)); + + // 3 left + uint32_t u32; + EXPECT_FALSE(reader.Read<uint32_t>(&u32)); + EXPECT_TRUE(reader.Skip(2)); + + // 1 left + uint16_t u16; + EXPECT_FALSE(reader.Read<uint16_t>(&u16)); + + uint8_t buffer[2]; + EXPECT_FALSE(reader.Read(2, buffer)); + EXPECT_TRUE(reader.Skip(1)); + + // 0 left + uint8_t u8; + EXPECT_FALSE(reader.Read<uint8_t>(&u8)); + + EXPECT_EQ(reader.begin(), data); + EXPECT_EQ(reader.current(), data + 8); + EXPECT_EQ(reader.end(), data + 8); + EXPECT_EQ(reader.offset(), size_t(8)); + EXPECT_EQ(reader.remaining(), size_t(0)); + EXPECT_EQ(reader.length(), size_t(8)); +} + +TEST(BigEndianBufferCursorTest, CursorCommit) { + uint8_t data[16] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, + 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF}; + BigEndianReader reader(data, sizeof(data)); + + { + BigEndianReader::Cursor cursor(&reader); + + uint8_t u8; + EXPECT_TRUE(reader.Read<uint8_t>(&u8)); + EXPECT_EQ(cursor.delta(), 1); + + uint16_t u16; + EXPECT_TRUE(reader.Read<uint16_t>(&u16)); + EXPECT_EQ(cursor.delta(), 3); + + uint32_t u32; + EXPECT_TRUE(reader.Read<uint32_t>(&u32)); + EXPECT_EQ(cursor.delta(), 7); + + uint64_t u64; + EXPECT_TRUE(reader.Read<uint64_t>(&u64)); + EXPECT_EQ(cursor.delta(), 15); + + EXPECT_FALSE(reader.Skip(2)); + EXPECT_EQ(cursor.delta(), 15); + EXPECT_EQ(reader.current() - cursor.origin(), cursor.delta()); + + cursor.Commit(); + } + + EXPECT_EQ(reader.begin(), data); + EXPECT_EQ(reader.current(), data + 15); + EXPECT_EQ(reader.end(), data + 16); + EXPECT_EQ(reader.offset(), size_t(15)); + EXPECT_EQ(reader.remaining(), size_t(1)); + EXPECT_EQ(reader.length(), size_t(16)); +} + +TEST(BigEndianBufferCursorTest, CursorRollback) { + uint8_t data[16]; + BigEndianReader reader(data, sizeof(data)); + + { + BigEndianReader::Cursor cursor(&reader); + + EXPECT_TRUE(reader.Skip(4)); + EXPECT_EQ(cursor.delta(), 4); + } + + EXPECT_EQ(reader.begin(), data); + EXPECT_EQ(reader.current(), data); + EXPECT_EQ(reader.end(), data + 16); + EXPECT_EQ(reader.offset(), size_t(0)); + EXPECT_EQ(reader.remaining(), size_t(16)); + EXPECT_EQ(reader.length(), size_t(16)); +} + +TEST(BigEndianWriterTest, ConstructWithValidBuffer) { + uint8_t data[64]; + BigEndianWriter writer(data, sizeof(data)); + + EXPECT_EQ(writer.begin(), data); + EXPECT_EQ(writer.current(), data); + EXPECT_EQ(writer.end(), data + 64); + EXPECT_EQ(writer.offset(), size_t(0)); + EXPECT_EQ(writer.remaining(), size_t(64)); + EXPECT_EQ(writer.length(), size_t(64)); +} + +TEST(BigEndianWriterTest, SkipLessThanRemaining) { + uint8_t data[64]; + BigEndianWriter writer(data, sizeof(data)); + + EXPECT_TRUE(writer.Skip(16)); + + EXPECT_EQ(writer.begin(), data); + EXPECT_EQ(writer.current(), data + 16); + EXPECT_EQ(writer.end(), data + 64); + EXPECT_EQ(writer.offset(), size_t(16)); + EXPECT_EQ(writer.remaining(), size_t(48)); + EXPECT_EQ(writer.length(), size_t(64)); +} + +TEST(BigEndianWriterTest, SkipMoreThanRemaining) { + uint8_t data[64]; + BigEndianWriter writer(data, sizeof(data)); + + EXPECT_TRUE(writer.Skip(16)); + EXPECT_FALSE(writer.Skip(64)); + + // Check that failed Skip does not modify any pointers or offsets. + EXPECT_EQ(writer.begin(), data); + EXPECT_EQ(writer.current(), data + 16); + EXPECT_EQ(writer.end(), data + 64); + EXPECT_EQ(writer.offset(), size_t(16)); + EXPECT_EQ(writer.remaining(), size_t(48)); + EXPECT_EQ(writer.length(), size_t(64)); +} + +TEST(BigEndianWriterTest, ConstructWithZeroLengthBuffer) { + uint8_t data[8]; + BigEndianWriter writer(data, 0); + + EXPECT_EQ(writer.begin(), data); + EXPECT_EQ(writer.current(), data); + EXPECT_EQ(writer.end(), data); + EXPECT_EQ(writer.offset(), size_t(0)); + EXPECT_EQ(writer.remaining(), size_t(0)); + EXPECT_EQ(writer.length(), size_t(0)); + + EXPECT_FALSE(writer.Skip(1)); +} + +TEST(BigEndianWriterTest, WriteValues) { + uint8_t expected[17] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, + 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF, 0x10}; + + uint8_t data[17]; + memset(data, 0xFF, sizeof(data)); + BigEndianWriter writer(data, sizeof(data)); + + uint8_t buffer[] = {0x0, 0x1}; + EXPECT_TRUE(writer.Write(buffer, sizeof(buffer))); + EXPECT_TRUE(writer.Write<uint8_t>(UINT8_C(0x2))); + EXPECT_TRUE(writer.Write<uint16_t>(UINT16_C(0x0304))); + EXPECT_TRUE(writer.Write<uint32_t>(UINT32_C(0x05060708))); + EXPECT_TRUE(writer.Write<uint64_t>(UINT64_C(0x090A0B0C0D0E0F10))); + EXPECT_THAT(data, testing::ElementsAreArray(expected)); + + EXPECT_EQ(writer.begin(), data); + EXPECT_EQ(writer.current(), data + 17); + EXPECT_EQ(writer.end(), data + 17); + EXPECT_EQ(writer.offset(), size_t(17)); + EXPECT_EQ(writer.remaining(), size_t(0)); + EXPECT_EQ(writer.length(), size_t(17)); +} + +TEST(BigEndianWriterTest, RespectLength) { + uint8_t data[8]; + BigEndianWriter writer(data, sizeof(data)); + + // 8 left + EXPECT_FALSE(writer.Skip(9)); + EXPECT_TRUE(writer.Skip(1)); + + // 7 left + EXPECT_FALSE(writer.Write<uint64_t>(0)); + EXPECT_TRUE(writer.Skip(4)); + + // 3 left + EXPECT_FALSE(writer.Write<uint32_t>(0)); + EXPECT_TRUE(writer.Skip(2)); + + // 1 left + EXPECT_FALSE(writer.Write<uint16_t>(0)); + + uint8_t buffer[2]; + EXPECT_FALSE(writer.Write(buffer, 2)); + EXPECT_TRUE(writer.Skip(1)); + + // 0 left + EXPECT_FALSE(writer.Write<uint8_t>(0)); + EXPECT_EQ(0u, writer.remaining()); + + EXPECT_EQ(writer.begin(), data); + EXPECT_EQ(writer.current(), data + 8); + EXPECT_EQ(writer.end(), data + 8); + EXPECT_EQ(writer.offset(), size_t(8)); + EXPECT_EQ(writer.remaining(), size_t(0)); + EXPECT_EQ(writer.length(), size_t(8)); +} + +} // namespace +} // namespace openscreen diff --git a/util/crypto/DEPS b/util/crypto/DEPS new file mode 100644 index 00000000..a833577b --- /dev/null +++ b/util/crypto/DEPS @@ -0,0 +1,11 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +include_rules = [ + '+platform/api', + + # BoringSSL includes + '-third_party/boringssl', + '+openssl' +] diff --git a/util/crypto/openssl_util.cc b/util/crypto/openssl_util.cc new file mode 100644 index 00000000..92253b42 --- /dev/null +++ b/util/crypto/openssl_util.cc @@ -0,0 +1,59 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "util/crypto/openssl_util.h" + +#include <stddef.h> +#include <stdint.h> + +#include <string> + +#include "absl/strings/string_view.h" +#include "openssl/crypto.h" +#include "openssl/err.h" +#include "openssl/ssl.h" +#include "platform/api/logging.h" + +namespace openscreen { + +namespace { + +// Callback routine for OpenSSL to print error messages. |str| is a +// nullptr-terminated string of length |len| containing diagnostic information +// such as the library, function and reason for the error, the file and line +// where the error originated, plus potentially any context-specific +// information about the error. |context| contains a pointer to user-supplied +// data, which is currently unused. +// If this callback returns a value <= 0, OpenSSL will stop processing the +// error queue and return, otherwise it will continue calling this function +// until all errors have been removed from the queue. +int OpenSSLErrorCallback(const char* str, size_t len, void* context) { + OSP_DVLOG << "\t" << absl::string_view(str, len); + return 1; +} + +} // namespace + +void EnsureOpenSSLInit() { + OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, nullptr); +} + +void EnsureOpenSSLCleanup() { + EVP_cleanup(); +} + +void ClearOpenSSLERRStack(const Location& location) { + if (OSP_DCHECK_IS_ON()) { + uint32_t error_num = ERR_peek_error(); + if (error_num == 0) + return; + + OSP_DVLOG << "OpenSSL ERR_get_error stack from " << location.ToString(); + ERR_print_errors_cb(&OpenSSLErrorCallback, nullptr); + } else { + ERR_clear_error(); + } +} + +} // namespace openscreen diff --git a/util/crypto/openssl_util.h b/util/crypto/openssl_util.h new file mode 100644 index 00000000..a713b9f8 --- /dev/null +++ b/util/crypto/openssl_util.h @@ -0,0 +1,53 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UTIL_CRYPTO_OPENSSL_UTIL_H_ +#define UTIL_CRYPTO_OPENSSL_UTIL_H_ + +#include <stddef.h> + +#include <cstring> + +#include "platform/base/location.h" +#include "platform/base/macros.h" + +namespace openscreen { +// Initialize OpenSSL if it isn't already initialized. This must be called +// before any other OpenSSL functions though it is safe and cheap to call this +// multiple times. +// This function is thread-safe, and OpenSSL will only ever be initialized once. +// OpenSSL will be properly shut down on program exit. +// Multiple sequential calls to EnsureOpenSSLInit or EnsureOpenSSLCleanup are +// ignored by OpenSSL itself. +void EnsureOpenSSLInit(); +void EnsureOpenSSLCleanup(); + +// Drains the OpenSSL ERR_get_error stack. On a debug build the error codes +// are send to VLOG(1), on a release build they are disregarded. In most +// cases you should pass CURRENT_LOCATION as the |location|. +void ClearOpenSSLERRStack(const Location& location); + +// Place an instance of this class on the call stack to automatically clear +// the OpenSSL error stack on function exit. +class OpenSSLErrStackTracer { + public: + // Pass CURRENT_LOCATION as |location|, to help track the source of OpenSSL + // error messages. Note any diagnostic emitted will be tagged with the + // location of the constructor call as it's not possible to trace a + // destructor's callsite. + explicit OpenSSLErrStackTracer(const Location& location) + : location_(location) { + EnsureOpenSSLInit(); + } + ~OpenSSLErrStackTracer() { ClearOpenSSLERRStack(location_); } + + private: + const Location location_; + + OSP_DISALLOW_IMPLICIT_CONSTRUCTORS(OpenSSLErrStackTracer); +}; + +} // namespace openscreen + +#endif // UTIL_CRYPTO_OPENSSL_UTIL_H_ diff --git a/util/crypto/rsa_private_key.cc b/util/crypto/rsa_private_key.cc new file mode 100644 index 00000000..7ee12fb9 --- /dev/null +++ b/util/crypto/rsa_private_key.cc @@ -0,0 +1,114 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "util/crypto/rsa_private_key.h" + +#include <stdint.h> + +#include <algorithm> +#include <memory> +#include <utility> + +#include "openssl/bn.h" +#include "openssl/bytestring.h" +#include "openssl/evp.h" +#include "openssl/mem.h" +#include "openssl/rsa.h" +#include "platform/api/logging.h" +#include "util/crypto/openssl_util.h" + +namespace openscreen { +RSAPrivateKey::~RSAPrivateKey() = default; + +// static +std::unique_ptr<RSAPrivateKey> RSAPrivateKey::Create(uint16_t num_bits) { + OpenSSLErrStackTracer err_tracer(CURRENT_LOCATION); + + bssl::UniquePtr<RSA> rsa_key(RSA_new()); + bssl::UniquePtr<BIGNUM> exponent(BN_new()); + if (!rsa_key.get() || !exponent.get() || !BN_set_word(exponent.get(), 65537L)) + return nullptr; + + if (!RSA_generate_key_ex(rsa_key.get(), num_bits, exponent.get(), nullptr)) + return nullptr; + + std::unique_ptr<RSAPrivateKey> result(new RSAPrivateKey); + result->key_.reset(EVP_PKEY_new()); + if (!result->key_ || !EVP_PKEY_set1_RSA(result->key_.get(), rsa_key.get())) + return nullptr; + + return result; +} + +// static +std::unique_ptr<RSAPrivateKey> RSAPrivateKey::CreateFromPrivateKeyInfo( + const std::vector<uint8_t>& input) { + OpenSSLErrStackTracer err_tracer(CURRENT_LOCATION); + + CBS private_key_cbs; + CBS_init(&private_key_cbs, input.data(), input.size()); + bssl::UniquePtr<EVP_PKEY> private_key( + EVP_parse_private_key(&private_key_cbs)); + if (!private_key || CBS_len(&private_key_cbs) != 0 || + EVP_PKEY_id(private_key.get()) != EVP_PKEY_RSA) + return nullptr; + + std::unique_ptr<RSAPrivateKey> result(new RSAPrivateKey); + result->key_ = std::move(private_key); + return result; +} + +// static +std::unique_ptr<RSAPrivateKey> RSAPrivateKey::CreateFromKey(EVP_PKEY* key) { + OSP_DCHECK(key); + if (EVP_PKEY_type(key->type) != EVP_PKEY_RSA) + return nullptr; + std::unique_ptr<RSAPrivateKey> result(new RSAPrivateKey); + result->key_ = bssl::UpRef(key); + return result; +} + +std::unique_ptr<RSAPrivateKey> RSAPrivateKey::Copy() const { + std::unique_ptr<RSAPrivateKey> result(new RSAPrivateKey); + bssl::UniquePtr<RSA> rsa(EVP_PKEY_get1_RSA(key_.get())); + if (!rsa) + return nullptr; + result->key_.reset(EVP_PKEY_new()); + if (!EVP_PKEY_set1_RSA(result->key_.get(), rsa.get())) + return nullptr; + return result; +} + +bool RSAPrivateKey::ExportPrivateKey(std::vector<uint8_t>* output) const { + OpenSSLErrStackTracer err_tracer(CURRENT_LOCATION); + uint8_t* der; + size_t der_len; + bssl::ScopedCBB cbb; + if (!CBB_init(cbb.get(), 0) || + !EVP_marshal_private_key(cbb.get(), key_.get()) || + !CBB_finish(cbb.get(), &der, &der_len)) { + return false; + } + output->assign(der, der + der_len); + OPENSSL_free(der); + return true; +} + +bool RSAPrivateKey::ExportPublicKey(std::vector<uint8_t>* output) const { + OpenSSLErrStackTracer err_tracer(CURRENT_LOCATION); + uint8_t* der; + size_t der_len; + bssl::ScopedCBB cbb; + if (!CBB_init(cbb.get(), 0) || + !EVP_marshal_public_key(cbb.get(), key_.get()) || + !CBB_finish(cbb.get(), &der, &der_len)) { + return false; + } + output->assign(der, der + der_len); + OPENSSL_free(der); + return true; +} + +RSAPrivateKey::RSAPrivateKey() = default; +} // namespace openscreen diff --git a/util/crypto/rsa_private_key.h b/util/crypto/rsa_private_key.h new file mode 100644 index 00000000..5738954a --- /dev/null +++ b/util/crypto/rsa_private_key.h @@ -0,0 +1,62 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UTIL_CRYPTO_RSA_PRIVATE_KEY_H_ +#define UTIL_CRYPTO_RSA_PRIVATE_KEY_H_ + +#include <stddef.h> +#include <stdint.h> + +#include <memory> +#include <vector> + +#include "openssl/base.h" +#include "platform/base/macros.h" + +namespace openscreen { + +// Encapsulates an RSA private key. Can be used to generate new keys, export +// keys to other formats, or to extract a public key. +class RSAPrivateKey { + public: + ~RSAPrivateKey(); + + // Create a new random instance. Can return nullptr if initialization fails. + static std::unique_ptr<RSAPrivateKey> Create(uint16_t num_bits); + + // Create a new instance by importing an existing private key. The format is + // an ASN.1-encoded PrivateKeyInfo block from PKCS #8. This can return nullptr + // if initialization fails. + static std::unique_ptr<RSAPrivateKey> CreateFromPrivateKeyInfo( + const std::vector<uint8_t>& input); + + // Create a new instance from an existing EVP_PKEY, taking a + // reference to it. |key| must be an RSA key. Returns nullptr on + // failure. + static std::unique_ptr<RSAPrivateKey> CreateFromKey(EVP_PKEY* key); + + EVP_PKEY* key() { return key_.get(); } + + // Creates a copy of the object. + std::unique_ptr<RSAPrivateKey> Copy() const; + + // Exports the private key to a PKCS #8 PrivateKeyInfo block. + bool ExportPrivateKey(std::vector<uint8_t>* output) const; + + // Exports the public key to an X509 SubjectPublicKeyInfo block. + bool ExportPublicKey(std::vector<uint8_t>* output) const; + + private: + // Constructor is private. Use one of the Create*() methods above instead. + RSAPrivateKey(); + + // TODO(jophba): switch to shared pointer to allow copy. + bssl::UniquePtr<EVP_PKEY> key_; + + OSP_DISALLOW_COPY_AND_ASSIGN(RSAPrivateKey); +}; + +} // namespace openscreen + +#endif // UTIL_CRYPTO_RSA_PRIVATE_KEY_H_ diff --git a/util/crypto/rsa_private_key_unittest.cc b/util/crypto/rsa_private_key_unittest.cc new file mode 100644 index 00000000..17cc1de5 --- /dev/null +++ b/util/crypto/rsa_private_key_unittest.cc @@ -0,0 +1,375 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "util/crypto/rsa_private_key.h" + +#include <stdint.h> + +#include <cstring> +#include <memory> + +#include "gtest/gtest.h" + +namespace openscreen { +namespace { + +const uint8_t kTestPrivateKeyInfo[] = { + 0x30, 0x82, 0x02, 0x78, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a, + 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82, + 0x02, 0x62, 0x30, 0x82, 0x02, 0x5e, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81, + 0x00, 0xb8, 0x7f, 0x2b, 0x20, 0xdc, 0x7c, 0x9b, 0x0c, 0xdc, 0x51, 0x61, + 0x99, 0x0d, 0x36, 0x0f, 0xd4, 0x66, 0x88, 0x08, 0x55, 0x84, 0xd5, 0x3a, + 0xbf, 0x2b, 0xa4, 0x64, 0x85, 0x7b, 0x0c, 0x04, 0x13, 0x3f, 0x8d, 0xf4, + 0xbc, 0x38, 0x0d, 0x49, 0xfe, 0x6b, 0xc4, 0x5a, 0xb0, 0x40, 0x53, 0x3a, + 0xd7, 0x66, 0x09, 0x0f, 0x9e, 0x36, 0x74, 0x30, 0xda, 0x8a, 0x31, 0x4f, + 0x1f, 0x14, 0x50, 0xd7, 0xc7, 0x20, 0x94, 0x17, 0xde, 0x4e, 0xb9, 0x57, + 0x5e, 0x7e, 0x0a, 0xe5, 0xb2, 0x65, 0x7a, 0x89, 0x4e, 0xb6, 0x47, 0xff, + 0x1c, 0xbd, 0xb7, 0x38, 0x13, 0xaf, 0x47, 0x85, 0x84, 0x32, 0x33, 0xf3, + 0x17, 0x49, 0xbf, 0xe9, 0x96, 0xd0, 0xd6, 0x14, 0x6f, 0x13, 0x8d, 0xc5, + 0xfc, 0x2c, 0x72, 0xba, 0xac, 0xea, 0x7e, 0x18, 0x53, 0x56, 0xa6, 0x83, + 0xa2, 0xce, 0x93, 0x93, 0xe7, 0x1f, 0x0f, 0xe6, 0x0f, 0x02, 0x03, 0x01, + 0x00, 0x01, 0x02, 0x81, 0x80, 0x03, 0x61, 0x89, 0x37, 0xcb, 0xf2, 0x98, + 0xa0, 0xce, 0xb4, 0xcb, 0x16, 0x13, 0xf0, 0xe6, 0xaf, 0x5c, 0xc5, 0xa7, + 0x69, 0x71, 0xca, 0xba, 0x8d, 0xe0, 0x4d, 0xdd, 0xed, 0xb8, 0x48, 0x8b, + 0x16, 0x93, 0x36, 0x95, 0xc2, 0x91, 0x40, 0x65, 0x17, 0xbd, 0x7f, 0xd6, + 0xad, 0x9e, 0x30, 0x28, 0x46, 0xe4, 0x3e, 0xcc, 0x43, 0x78, 0xf9, 0xfe, + 0x1f, 0x33, 0x23, 0x1e, 0x31, 0x12, 0x9d, 0x3c, 0xa7, 0x08, 0x82, 0x7b, + 0x7d, 0x25, 0x4e, 0x5e, 0x19, 0xa8, 0x9b, 0xed, 0x86, 0xb2, 0xcb, 0x3c, + 0xfe, 0x4e, 0xa1, 0xfa, 0x62, 0x87, 0x3a, 0x17, 0xf7, 0x60, 0xec, 0x38, + 0x29, 0xe8, 0x4f, 0x34, 0x9f, 0x76, 0x9d, 0xee, 0xa3, 0xf6, 0x85, 0x6b, + 0x84, 0x43, 0xc9, 0x1e, 0x01, 0xff, 0xfd, 0xd0, 0x29, 0x4c, 0xfa, 0x8e, + 0x57, 0x0c, 0xc0, 0x71, 0xa5, 0xbb, 0x88, 0x46, 0x29, 0x5c, 0xc0, 0x4f, + 0x01, 0x02, 0x41, 0x00, 0xf5, 0x83, 0xa4, 0x64, 0x4a, 0xf2, 0xdd, 0x8c, + 0x2c, 0xed, 0xa8, 0xd5, 0x60, 0x5a, 0xe4, 0xc7, 0xcc, 0x61, 0xcd, 0x38, + 0x42, 0x20, 0xd3, 0x82, 0x18, 0xf2, 0x35, 0x00, 0x72, 0x2d, 0xf7, 0x89, + 0x80, 0x67, 0xb5, 0x93, 0x05, 0x5f, 0xdd, 0x42, 0xba, 0x16, 0x1a, 0xea, + 0x15, 0xc6, 0xf0, 0xb8, 0x8c, 0xbc, 0xbf, 0x54, 0x9e, 0xf1, 0xc1, 0xb2, + 0xb3, 0x8b, 0xb6, 0x26, 0x02, 0x30, 0xc4, 0x81, 0x02, 0x41, 0x00, 0xc0, + 0x60, 0x62, 0x80, 0xe1, 0x22, 0x78, 0xf6, 0x9d, 0x83, 0x18, 0xeb, 0x72, + 0x45, 0xd7, 0xc8, 0x01, 0x7f, 0xa9, 0xca, 0x8f, 0x7d, 0xd6, 0xb8, 0x31, + 0x2b, 0x84, 0x7f, 0x62, 0xd9, 0xa9, 0x22, 0x17, 0x7d, 0x06, 0x35, 0x6c, + 0xf3, 0xc1, 0x94, 0x17, 0x85, 0x5a, 0xaf, 0x9c, 0x5c, 0x09, 0x3c, 0xcf, + 0x2f, 0x44, 0x9d, 0xb6, 0x52, 0x68, 0x5f, 0xf9, 0x59, 0xc8, 0x84, 0x2b, + 0x39, 0x22, 0x8f, 0x02, 0x41, 0x00, 0xb2, 0x04, 0xe2, 0x0e, 0x56, 0xca, + 0x03, 0x1a, 0xc0, 0xf9, 0x12, 0x92, 0xa5, 0x6b, 0x42, 0xb8, 0x1c, 0xda, + 0x4d, 0x93, 0x9d, 0x5f, 0x6f, 0xfd, 0xc5, 0x58, 0xda, 0x55, 0x98, 0x74, + 0xfc, 0x28, 0x17, 0x93, 0x1b, 0x75, 0x9f, 0x50, 0x03, 0x7f, 0x7e, 0xae, + 0xc8, 0x95, 0x33, 0x75, 0x2c, 0xd6, 0xa4, 0x35, 0xb8, 0x06, 0x03, 0xba, + 0x08, 0x59, 0x2b, 0x17, 0x02, 0xdc, 0x4c, 0x7a, 0x50, 0x01, 0x02, 0x41, + 0x00, 0x9d, 0xdb, 0x39, 0x59, 0x09, 0xe4, 0x30, 0xa0, 0x24, 0xf5, 0xdb, + 0x2f, 0xf0, 0x2f, 0xf1, 0x75, 0x74, 0x0d, 0x5e, 0xb5, 0x11, 0x73, 0xb0, + 0x0a, 0xaa, 0x86, 0x4c, 0x0d, 0xff, 0x7e, 0x1d, 0xb4, 0x14, 0xd4, 0x09, + 0x91, 0x33, 0x5a, 0xfd, 0xa0, 0x58, 0x80, 0x9b, 0xbe, 0x78, 0x2e, 0x69, + 0x82, 0x15, 0x7c, 0x72, 0xf0, 0x7b, 0x18, 0x39, 0xff, 0x6e, 0xeb, 0xc6, + 0x86, 0xf5, 0xb4, 0xc7, 0x6f, 0x02, 0x41, 0x00, 0x8d, 0x1a, 0x37, 0x0f, + 0x76, 0xc4, 0x82, 0xfa, 0x5c, 0xc3, 0x79, 0x35, 0x3e, 0x70, 0x8a, 0xbf, + 0x27, 0x49, 0xb0, 0x99, 0x63, 0xcb, 0x77, 0x5f, 0xa8, 0x82, 0x65, 0xf6, + 0x03, 0x52, 0x51, 0xf1, 0xae, 0x2e, 0x05, 0xb3, 0xc6, 0xa4, 0x92, 0xd1, + 0xce, 0x6c, 0x72, 0xfb, 0x21, 0xb3, 0x02, 0x87, 0xe4, 0xfd, 0x61, 0xca, + 0x00, 0x42, 0x19, 0xf0, 0xda, 0x5a, 0x53, 0xe3, 0xb1, 0xc5, 0x15, 0xf3}; + +} // namespace + +// Generate random private keys with two different sizes. Reimport, then +// export them again. We should get back the same exact bytes. +TEST(RSAPrivateKeyUnitTest, InitRandomTest) { + std::unique_ptr<RSAPrivateKey> keypair1(RSAPrivateKey::Create(1024)); + std::unique_ptr<RSAPrivateKey> keypair2(RSAPrivateKey::Create(2048)); + ASSERT_TRUE(keypair1.get()); + ASSERT_TRUE(keypair2.get()); + + std::vector<uint8_t> privkey1; + std::vector<uint8_t> privkey2; + std::vector<uint8_t> pubkey1; + std::vector<uint8_t> pubkey2; + + ASSERT_TRUE(keypair1->ExportPrivateKey(&privkey1)); + ASSERT_TRUE(keypair2->ExportPrivateKey(&privkey2)); + ASSERT_TRUE(keypair1->ExportPublicKey(&pubkey1)); + ASSERT_TRUE(keypair2->ExportPublicKey(&pubkey2)); + + std::unique_ptr<RSAPrivateKey> keypair3( + RSAPrivateKey::CreateFromPrivateKeyInfo(privkey1)); + std::unique_ptr<RSAPrivateKey> keypair4( + RSAPrivateKey::CreateFromPrivateKeyInfo(privkey2)); + ASSERT_TRUE(keypair3.get()); + ASSERT_TRUE(keypair4.get()); + + std::vector<uint8_t> privkey3; + std::vector<uint8_t> privkey4; + ASSERT_TRUE(keypair3->ExportPrivateKey(&privkey3)); + ASSERT_TRUE(keypair4->ExportPrivateKey(&privkey4)); + + ASSERT_EQ(privkey1.size(), privkey3.size()); + ASSERT_EQ(privkey2.size(), privkey4.size()); + ASSERT_EQ(0, memcmp(&privkey1.front(), &privkey3.front(), privkey1.size())); + ASSERT_EQ(0, memcmp(&privkey2.front(), &privkey4.front(), privkey2.size())); +} + +// Test Copy() method. +TEST(RSAPrivateKeyUnitTest, CopyTest) { + std::vector<uint8_t> input(kTestPrivateKeyInfo, + kTestPrivateKeyInfo + sizeof(kTestPrivateKeyInfo)); + + std::unique_ptr<RSAPrivateKey> key( + RSAPrivateKey::CreateFromPrivateKeyInfo(input)); + + std::unique_ptr<RSAPrivateKey> key_copy(key->Copy()); + ASSERT_TRUE(key_copy.get()); + + std::vector<uint8_t> privkey_copy; + ASSERT_TRUE(key_copy->ExportPrivateKey(&privkey_copy)); + ASSERT_EQ(input, privkey_copy); +} + +// Test that CreateFromPrivateKeyInfo fails if there is extra data after the RSA +// key. +TEST(RSAPrivateKeyUnitTest, ExtraData) { + std::vector<uint8_t> input(kTestPrivateKeyInfo, + kTestPrivateKeyInfo + sizeof(kTestPrivateKeyInfo)); + input.push_back(0); + + std::unique_ptr<RSAPrivateKey> key( + RSAPrivateKey::CreateFromPrivateKeyInfo(input)); + + // Import should fail. + EXPECT_FALSE(key); +} + +TEST(RSAPrivateKeyUnitTest, NotRsaKey) { + // Defines a valid P-256 private key. + const uint8_t kTestEcPrivateKeyInfo[] = { + 0x30, 0x81, 0x87, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2A, 0x86, + 0x48, 0xCE, 0x3D, 0x02, 0x01, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, + 0x03, 0x01, 0x07, 0x04, 0x6D, 0x30, 0x6B, 0x02, 0x01, 0x01, 0x04, 0x20, + 0x1F, 0xE3, 0x39, 0x50, 0xC5, 0xF4, 0x61, 0x12, 0x4A, 0xE9, 0x92, 0xC2, + 0xBD, 0xFD, 0xF1, 0xC7, 0x3B, 0x16, 0x15, 0xF5, 0x71, 0xBD, 0x56, 0x7E, + 0x60, 0xD1, 0x9A, 0xA1, 0xF4, 0x8C, 0xDF, 0x42, 0xA1, 0x44, 0x03, 0x42, + 0x00, 0x04, 0x7C, 0x11, 0x0C, 0x66, 0xDC, 0xFD, 0xA8, 0x07, 0xF6, 0xE6, + 0x9E, 0x45, 0xDD, 0xB3, 0xC7, 0x4F, 0x69, 0xA1, 0x48, 0x4D, 0x20, 0x3E, + 0x8D, 0xC5, 0xAD, 0xA8, 0xE9, 0xA9, 0xDD, 0x7C, 0xB3, 0xC7, 0x0D, 0xF4, + 0x48, 0x98, 0x6E, 0x51, 0xBD, 0xE5, 0xD1, 0x57, 0x6F, 0x99, 0x90, 0x1F, + 0x9C, 0x2C, 0x6A, 0x80, 0x6A, 0x47, 0xFD, 0x90, 0x76, 0x43, 0xA7, 0x2B, + 0x83, 0x55, 0x97, 0xEF, 0xC8, 0xC6}; + + std::vector<uint8_t> input( + kTestEcPrivateKeyInfo, + kTestEcPrivateKeyInfo + sizeof(kTestEcPrivateKeyInfo)); + + std::unique_ptr<RSAPrivateKey> key( + RSAPrivateKey::CreateFromPrivateKeyInfo(input)); + + // Import should fail as the given PKCS8 bytes were for an EC key not RSA key. + EXPECT_FALSE(key); +} + +// Verify that generated public keys look good. This test data was generated +// with the openssl command line tool. +TEST(RSAPrivateKeyUnitTest, PublicKeyTest) { + const uint8_t expected_public_key_info[] = { + 0x30, 0x81, 0x9f, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, + 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8d, 0x00, 0x30, 0x81, + 0x89, 0x02, 0x81, 0x81, 0x00, 0xb8, 0x7f, 0x2b, 0x20, 0xdc, 0x7c, 0x9b, + 0x0c, 0xdc, 0x51, 0x61, 0x99, 0x0d, 0x36, 0x0f, 0xd4, 0x66, 0x88, 0x08, + 0x55, 0x84, 0xd5, 0x3a, 0xbf, 0x2b, 0xa4, 0x64, 0x85, 0x7b, 0x0c, 0x04, + 0x13, 0x3f, 0x8d, 0xf4, 0xbc, 0x38, 0x0d, 0x49, 0xfe, 0x6b, 0xc4, 0x5a, + 0xb0, 0x40, 0x53, 0x3a, 0xd7, 0x66, 0x09, 0x0f, 0x9e, 0x36, 0x74, 0x30, + 0xda, 0x8a, 0x31, 0x4f, 0x1f, 0x14, 0x50, 0xd7, 0xc7, 0x20, 0x94, 0x17, + 0xde, 0x4e, 0xb9, 0x57, 0x5e, 0x7e, 0x0a, 0xe5, 0xb2, 0x65, 0x7a, 0x89, + 0x4e, 0xb6, 0x47, 0xff, 0x1c, 0xbd, 0xb7, 0x38, 0x13, 0xaf, 0x47, 0x85, + 0x84, 0x32, 0x33, 0xf3, 0x17, 0x49, 0xbf, 0xe9, 0x96, 0xd0, 0xd6, 0x14, + 0x6f, 0x13, 0x8d, 0xc5, 0xfc, 0x2c, 0x72, 0xba, 0xac, 0xea, 0x7e, 0x18, + 0x53, 0x56, 0xa6, 0x83, 0xa2, 0xce, 0x93, 0x93, 0xe7, 0x1f, 0x0f, 0xe6, + 0x0f, 0x02, 0x03, 0x01, 0x00, 0x01}; + + std::vector<uint8_t> input(kTestPrivateKeyInfo, + kTestPrivateKeyInfo + sizeof(kTestPrivateKeyInfo)); + + std::unique_ptr<RSAPrivateKey> key( + RSAPrivateKey::CreateFromPrivateKeyInfo(input)); + ASSERT_TRUE(key.get()); + + std::vector<uint8_t> output; + ASSERT_TRUE(key->ExportPublicKey(&output)); + + ASSERT_EQ(0, + memcmp(expected_public_key_info, &output.front(), output.size())); +} + +// These two test keys each contain an integer that has 0x00 for its most +// significant byte. When encoded as ASN.1, this byte is dropped and there are +// two interesting sub-cases. When the sign bit of the integer is set, an extra +// null byte is added back to force the encoded value to be positive. When the +// sign bit is not set, the encoded integer is just left shorter than usual. +// See also: http://code.google.com/p/chromium/issues/detail?id=14877. +// +// Before we were handling this correctly, we would see one of two failures: +// * RSAPrivateKey::CreateFromPrivateKeyInfo would return null because the +// underlying windows API failed to import the key. +// * The import would succeed, but incorrectly interpret the data. On export, +// the key would contain different values. +// +// This test case verifies these two failures modes don't occur. +TEST(RSAPrivateKeyUnitTest, ShortIntegers) { + const uint8_t short_integer_with_high_bit[] = { + 0x30, 0x82, 0x02, 0x77, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a, + 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82, + 0x02, 0x61, 0x30, 0x82, 0x02, 0x5d, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81, + 0x00, 0x92, 0x59, 0x32, 0x7d, 0x8e, 0xaf, 0x2e, 0xd5, 0xb2, 0x5c, 0x67, + 0xc8, 0x7d, 0x48, 0xb7, 0x84, 0x12, 0xd0, 0x76, 0xda, 0xe1, 0xa3, 0x1e, + 0x40, 0x01, 0x14, 0x5c, 0xef, 0x26, 0x6e, 0x28, 0xa2, 0xf7, 0xa5, 0xb4, + 0x02, 0x37, 0xd0, 0x53, 0x10, 0xcb, 0x7c, 0x6a, 0xf4, 0x53, 0x9f, 0xb8, + 0xe0, 0x83, 0x93, 0xd1, 0x19, 0xd8, 0x28, 0xd1, 0xd1, 0xd8, 0x87, 0x8f, + 0x92, 0xfd, 0x73, 0xc0, 0x4d, 0x3e, 0x07, 0x22, 0x1f, 0xc1, 0x20, 0xb0, + 0x70, 0xb2, 0x3b, 0xea, 0xb1, 0xe5, 0x0a, 0xfd, 0x56, 0x49, 0x5e, 0x39, + 0x90, 0x91, 0xce, 0x04, 0x83, 0x29, 0xaa, 0xfd, 0x12, 0xa4, 0x42, 0x26, + 0x6c, 0x6e, 0x79, 0x70, 0x77, 0x03, 0xb2, 0x07, 0x01, 0x3d, 0x85, 0x81, + 0x95, 0x9e, 0xda, 0x5a, 0xa3, 0xf4, 0x2d, 0x38, 0x04, 0x58, 0xf5, 0x6b, + 0xc9, 0xf1, 0xb5, 0x65, 0xfe, 0x66, 0x0d, 0xa2, 0xd5, 0x02, 0x03, 0x01, + 0x00, 0x01, 0x02, 0x81, 0x80, 0x5e, 0x01, 0x5f, 0xb6, 0x59, 0x1d, 0xdc, + 0x36, 0xb6, 0x60, 0x36, 0xe6, 0x08, 0xdb, 0xd9, 0xcd, 0xc3, 0x8c, 0x16, + 0x9c, 0x98, 0x8d, 0x7f, 0xd3, 0xdb, 0x1d, 0xaa, 0x68, 0x8f, 0xc5, 0xf8, + 0xe2, 0x5d, 0xb3, 0x19, 0xc2, 0xc6, 0xf9, 0x51, 0x32, 0x1b, 0x93, 0x6a, + 0xdc, 0x50, 0x8e, 0xeb, 0x61, 0x84, 0x03, 0x42, 0x30, 0x98, 0xb1, 0xf7, + 0xbd, 0x14, 0x9a, 0x57, 0x36, 0x33, 0x09, 0xd4, 0x3e, 0x90, 0xda, 0xef, + 0x09, 0x6e, 0xef, 0x49, 0xb6, 0x60, 0x68, 0x5e, 0x54, 0x17, 0x25, 0x5b, + 0x37, 0xe3, 0x35, 0x63, 0x5b, 0x60, 0x3c, 0xbd, 0x50, 0xdf, 0x46, 0x43, + 0x08, 0xa4, 0x71, 0x21, 0xf1, 0x30, 0x71, 0xdc, 0xda, 0xd7, 0x6f, 0xd2, + 0x18, 0xbd, 0x39, 0xf1, 0xe1, 0xbe, 0xa8, 0x8d, 0x62, 0xdf, 0xa2, 0x3e, + 0xb6, 0x15, 0x26, 0xb6, 0x57, 0xbd, 0x63, 0xdb, 0xc1, 0x91, 0xec, 0xb8, + 0x01, 0x02, 0x41, 0x00, 0xc6, 0x1a, 0x06, 0x48, 0xf2, 0x12, 0x1c, 0x9f, + 0x74, 0x20, 0x5c, 0x85, 0xa2, 0xda, 0xe5, 0x62, 0x96, 0x8d, 0x22, 0x7b, + 0x78, 0x73, 0xea, 0xbb, 0x9f, 0x59, 0x42, 0x13, 0x15, 0xc8, 0x11, 0x50, + 0x6c, 0x55, 0xf6, 0xdf, 0x8b, 0xfe, 0xc7, 0xdd, 0xa8, 0xca, 0x54, 0x41, + 0xe8, 0xce, 0xbe, 0x7d, 0xbd, 0xe2, 0x13, 0x4b, 0x5b, 0x61, 0xeb, 0x69, + 0x6c, 0xb1, 0x9b, 0x28, 0x68, 0x5b, 0xd6, 0x01, 0x02, 0x41, 0x00, 0xbd, + 0x1e, 0xfe, 0x51, 0x99, 0xb6, 0xe3, 0x84, 0xfe, 0xf1, 0x9e, 0xfd, 0x9c, + 0xe7, 0x86, 0x43, 0x68, 0x7f, 0x2f, 0x6a, 0x2a, 0x4c, 0xae, 0xa6, 0x41, + 0x1c, 0xf0, 0x10, 0x37, 0x54, 0x23, 0xba, 0x05, 0x0d, 0x18, 0x27, 0x8d, + 0xb8, 0xe4, 0x8f, 0xf2, 0x25, 0x73, 0x8a, 0xd7, 0x05, 0x98, 0x6b, 0x3d, + 0x55, 0xb7, 0x6f, 0x7c, 0xec, 0x77, 0x61, 0x54, 0x7b, 0xb6, 0x6b, 0x31, + 0xec, 0x94, 0xd5, 0x02, 0x41, 0x00, 0x90, 0xa2, 0xa5, 0x9e, 0x12, 0xa7, + 0x68, 0xa0, 0x7e, 0xdf, 0xb5, 0xcd, 0x98, 0x26, 0xab, 0xbd, 0xbc, 0x5f, + 0xd5, 0x22, 0x42, 0xc2, 0x97, 0x4a, 0x5f, 0x40, 0x82, 0xfe, 0x7e, 0x33, + 0xb1, 0x78, 0x7f, 0x70, 0x90, 0x2b, 0x8d, 0x01, 0xfb, 0x18, 0xfa, 0x48, + 0xa7, 0x15, 0xec, 0x0d, 0x2e, 0x85, 0x8d, 0xe2, 0x86, 0xe5, 0xc9, 0x15, + 0x88, 0x14, 0x53, 0xd8, 0xa4, 0x88, 0xef, 0x10, 0xc6, 0x01, 0x02, 0x41, + 0x00, 0xba, 0xe4, 0xaf, 0x14, 0xfa, 0xdf, 0xf6, 0xd5, 0xce, 0x8f, 0xfe, + 0xbb, 0xc8, 0x5c, 0x30, 0x9d, 0xda, 0xdd, 0x9d, 0x80, 0xc0, 0x0e, 0x89, + 0xa5, 0xb8, 0xc1, 0x1d, 0x28, 0x19, 0x55, 0x67, 0xfd, 0x03, 0xd2, 0xdd, + 0xe4, 0xf0, 0xb4, 0x20, 0x03, 0x74, 0x9b, 0xb8, 0x24, 0x23, 0xbb, 0xde, + 0xd5, 0x53, 0x86, 0xaa, 0xc1, 0x5d, 0x65, 0xdd, 0xcf, 0xec, 0x8a, 0x59, + 0x4a, 0x73, 0xca, 0xc5, 0x85, 0x02, 0x40, 0x00, 0xc4, 0x5e, 0x8d, 0xa4, + 0xea, 0xbb, 0x6a, 0x9b, 0xe6, 0x3a, 0x4d, 0xc1, 0xdb, 0xe5, 0x52, 0x38, + 0xf9, 0x59, 0x91, 0x2d, 0x90, 0x82, 0xe3, 0x31, 0x1b, 0x48, 0xb7, 0x42, + 0xfa, 0x1d, 0x83, 0xd5, 0x3d, 0x02, 0xc2, 0x12, 0x71, 0x10, 0x3a, 0xbd, + 0x92, 0x8f, 0x9b, 0xa2, 0x6b, 0x2d, 0x21, 0xa4, 0x65, 0xe9, 0xfa, 0x8c, + 0x30, 0x2a, 0x89, 0xce, 0xd0, 0xa7, 0x67, 0xd8, 0x45, 0x84, 0xb0}; + + const uint8_t short_integer_without_high_bit[] = { + 0x30, 0x82, 0x02, 0x76, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a, + 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82, + 0x02, 0x60, 0x30, 0x82, 0x02, 0x5c, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81, + 0x00, 0xc3, 0x9e, 0x8d, 0xc4, 0x6d, 0x38, 0xe8, 0x0e, 0x9f, 0x84, 0x03, + 0x40, 0x8e, 0x81, 0x2e, 0x56, 0x67, 0x78, 0x11, 0x85, 0x27, 0x81, 0x52, + 0xf2, 0x1b, 0x3e, 0x5b, 0xf8, 0xab, 0xfc, 0xaf, 0xca, 0x5c, 0x26, 0xd5, + 0xfa, 0xd4, 0x55, 0x50, 0x38, 0xb9, 0x9d, 0x89, 0x92, 0x7e, 0x34, 0xcf, + 0x37, 0x82, 0x48, 0x2d, 0xaa, 0xc4, 0x6a, 0x0e, 0x93, 0xea, 0xad, 0x8a, + 0x33, 0xf0, 0x42, 0x23, 0xe0, 0x4c, 0x98, 0xbf, 0x01, 0x00, 0x1b, 0xfe, + 0x06, 0x15, 0xc6, 0xe3, 0x80, 0x79, 0x6d, 0xfe, 0x48, 0xcd, 0x40, 0xbb, + 0xf9, 0x58, 0xe6, 0xbf, 0xd5, 0x4c, 0x29, 0x48, 0x53, 0x78, 0x06, 0x03, + 0x0d, 0x59, 0xf5, 0x20, 0xe0, 0xe6, 0x8c, 0xb2, 0xf5, 0xd8, 0x61, 0x52, + 0x7e, 0x40, 0x83, 0xd7, 0x69, 0xae, 0xd7, 0x75, 0x02, 0x2d, 0x49, 0xd5, + 0x15, 0x5b, 0xf1, 0xd9, 0x4d, 0x60, 0x7d, 0x62, 0xa5, 0x02, 0x03, 0x01, + 0x00, 0x01, 0x02, 0x7f, 0x6d, 0x45, 0x23, 0xeb, 0x95, 0x17, 0x34, 0x88, + 0xf6, 0x91, 0xc7, 0x3f, 0x48, 0x5a, 0xe0, 0x87, 0x63, 0x44, 0xae, 0x84, + 0xb2, 0x8c, 0x8a, 0xc8, 0xb2, 0x6f, 0x22, 0xf0, 0xc5, 0x21, 0x61, 0x10, + 0xa8, 0x69, 0x09, 0x1e, 0x13, 0x7d, 0x94, 0x52, 0x1b, 0x5c, 0xe4, 0x7b, + 0xf0, 0x03, 0x8f, 0xbc, 0x72, 0x09, 0xdf, 0x78, 0x84, 0x3e, 0xb9, 0xe5, + 0xe6, 0x31, 0x0a, 0x01, 0xf9, 0x32, 0xf8, 0xd6, 0x57, 0xa3, 0x87, 0xe6, + 0xf5, 0x98, 0xbc, 0x8e, 0x41, 0xb9, 0x50, 0x17, 0x7b, 0xd3, 0x97, 0x5a, + 0x44, 0x3a, 0xee, 0xff, 0x6b, 0xb3, 0x3a, 0x52, 0xe7, 0xa4, 0x96, 0x9a, + 0xf6, 0x83, 0xc8, 0x97, 0x1c, 0x63, 0xa1, 0xd6, 0xb3, 0xa8, 0xb2, 0xc7, + 0x73, 0x25, 0x0f, 0x58, 0x36, 0xb9, 0x7a, 0x47, 0xa7, 0x4d, 0x30, 0xfe, + 0x4d, 0x74, 0x56, 0xe8, 0xfb, 0xd6, 0x50, 0xe5, 0xe0, 0x28, 0x15, 0x02, + 0x41, 0x00, 0xeb, 0x15, 0x62, 0xb6, 0x37, 0x41, 0x7c, 0xc5, 0x00, 0x22, + 0x2c, 0x5a, 0x5e, 0xe4, 0xb2, 0x11, 0x87, 0x89, 0xad, 0xf4, 0x57, 0x68, + 0x90, 0xb7, 0x9f, 0xe2, 0x79, 0x20, 0x6b, 0x98, 0x00, 0x0d, 0x3a, 0x3b, + 0xc1, 0xcd, 0x36, 0xf9, 0x27, 0xda, 0x40, 0x36, 0x1d, 0xb8, 0x5c, 0x96, + 0xeb, 0x04, 0x08, 0xe1, 0x3f, 0xfa, 0x94, 0x8b, 0x0f, 0xa0, 0xff, 0xc1, + 0x51, 0xea, 0x90, 0xad, 0x15, 0xc7, 0x02, 0x41, 0x00, 0xd5, 0x06, 0x45, + 0xd7, 0x55, 0x63, 0x1a, 0xf0, 0x89, 0x81, 0xae, 0x87, 0x23, 0xa2, 0x39, + 0xfe, 0x3d, 0x82, 0xc7, 0xcb, 0x15, 0xb9, 0xe3, 0xe2, 0x5b, 0xc6, 0xd2, + 0x55, 0xdd, 0xab, 0x55, 0x29, 0x7c, 0xda, 0x0e, 0x1c, 0x09, 0xfc, 0x73, + 0x0d, 0x01, 0xed, 0x6d, 0x2f, 0x05, 0xd0, 0xd5, 0x1d, 0xce, 0x18, 0x7f, + 0xb0, 0xc8, 0x47, 0x77, 0xd2, 0xa9, 0x9e, 0xfc, 0x39, 0x4b, 0x3d, 0x94, + 0x33, 0x02, 0x41, 0x00, 0x8f, 0x94, 0x09, 0x2d, 0x17, 0x44, 0x75, 0x0a, + 0xf1, 0x10, 0xee, 0x1b, 0xe7, 0xd7, 0x2f, 0xf6, 0xca, 0xdc, 0x49, 0x15, + 0x72, 0x09, 0x58, 0x51, 0xfe, 0x61, 0xd8, 0xee, 0xf7, 0x27, 0xe7, 0xe8, + 0x2c, 0x47, 0xf1, 0x0f, 0x00, 0x63, 0x5e, 0x76, 0xcb, 0x3f, 0x02, 0x19, + 0xe6, 0xda, 0xfa, 0x01, 0x05, 0xd7, 0x65, 0x37, 0x0b, 0x60, 0x7f, 0x94, + 0x2a, 0x80, 0x8d, 0x22, 0x81, 0x68, 0x65, 0x63, 0x02, 0x41, 0x00, 0xc2, + 0xd4, 0x18, 0xde, 0x47, 0x9e, 0xfb, 0x8d, 0x91, 0x05, 0xc5, 0x3c, 0x9d, + 0xcf, 0x8a, 0x60, 0xc7, 0x9b, 0x2b, 0xe5, 0xc6, 0xba, 0x1b, 0xfc, 0xf3, + 0xd9, 0x54, 0x97, 0xe9, 0xc4, 0x00, 0x80, 0x90, 0x4a, 0xd2, 0x6a, 0xbc, + 0x8b, 0x62, 0x22, 0x3c, 0x68, 0x0c, 0xda, 0xdb, 0xe3, 0xd2, 0x76, 0x8e, + 0xff, 0x03, 0x12, 0x09, 0x2a, 0xac, 0x21, 0x44, 0xb7, 0x3e, 0x91, 0x9c, + 0x09, 0xf6, 0xd7, 0x02, 0x41, 0x00, 0xc0, 0xa1, 0xbb, 0x70, 0xdc, 0xf8, + 0xeb, 0x17, 0x61, 0xd4, 0x8c, 0x7c, 0x3b, 0x82, 0x91, 0x58, 0xff, 0xf9, + 0x19, 0xac, 0x3a, 0x73, 0xa7, 0x20, 0xe5, 0x22, 0x02, 0xc4, 0xf6, 0xb9, + 0xb9, 0x43, 0x53, 0x35, 0x88, 0xe1, 0x05, 0xb6, 0x43, 0x9b, 0x39, 0xc8, + 0x04, 0x4d, 0x2b, 0x01, 0xf7, 0xe6, 0x1b, 0x8d, 0x7e, 0x89, 0xe3, 0x43, + 0xd4, 0xf3, 0xab, 0x28, 0xd4, 0x5a, 0x1f, 0x20, 0xea, 0xbe}; + + std::vector<uint8_t> input1; + std::vector<uint8_t> input2; + + input1.resize(sizeof(short_integer_with_high_bit)); + input2.resize(sizeof(short_integer_without_high_bit)); + + memcpy(&input1.front(), short_integer_with_high_bit, + sizeof(short_integer_with_high_bit)); + memcpy(&input2.front(), short_integer_without_high_bit, + sizeof(short_integer_without_high_bit)); + + std::unique_ptr<RSAPrivateKey> keypair1( + RSAPrivateKey::CreateFromPrivateKeyInfo(input1)); + std::unique_ptr<RSAPrivateKey> keypair2( + RSAPrivateKey::CreateFromPrivateKeyInfo(input2)); + ASSERT_TRUE(keypair1.get()); + ASSERT_TRUE(keypair2.get()); + + std::vector<uint8_t> output1; + std::vector<uint8_t> output2; + ASSERT_TRUE(keypair1->ExportPrivateKey(&output1)); + ASSERT_TRUE(keypair2->ExportPrivateKey(&output2)); + + ASSERT_EQ(input1.size(), output1.size()); + ASSERT_EQ(input2.size(), output2.size()); + ASSERT_EQ(0, memcmp(&output1.front(), &input1.front(), input1.size())); + ASSERT_EQ(0, memcmp(&output2.front(), &input2.front(), input2.size())); +} + +TEST(RSAPrivateKeyUnitTest, CreateFromKeyTest) { + std::unique_ptr<RSAPrivateKey> key_pair(RSAPrivateKey::Create(512)); + ASSERT_TRUE(key_pair.get()); + + std::unique_ptr<RSAPrivateKey> key_copy( + RSAPrivateKey::CreateFromKey(key_pair->key())); + ASSERT_TRUE(key_copy.get()); + + std::vector<uint8_t> privkey; + std::vector<uint8_t> pubkey; + ASSERT_TRUE(key_pair->ExportPrivateKey(&privkey)); + ASSERT_TRUE(key_pair->ExportPublicKey(&pubkey)); + + std::vector<uint8_t> privkey_copy; + std::vector<uint8_t> pubkey_copy; + ASSERT_TRUE(key_copy->ExportPrivateKey(&privkey_copy)); + ASSERT_TRUE(key_copy->ExportPublicKey(&pubkey_copy)); + + ASSERT_EQ(privkey, privkey_copy); + ASSERT_EQ(pubkey, pubkey_copy); +} +} // namespace openscreen diff --git a/util/crypto/secure_hash.cc b/util/crypto/secure_hash.cc new file mode 100644 index 00000000..14ed726a --- /dev/null +++ b/util/crypto/secure_hash.cc @@ -0,0 +1,55 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "util/crypto/secure_hash.h" + +#include <stddef.h> + +#include <cstring> + +#include "openssl/mem.h" +#include "platform/api/logging.h" +#include "util/crypto/openssl_util.h" + +namespace openscreen { + +SecureHash::SecureHash(const EVP_MD* type) { + EVP_DigestInit(ctx_.get(), type); +} + +SecureHash::SecureHash(const SecureHash& other) { + *this = other; +} + +SecureHash& SecureHash::operator=(const SecureHash& other) { + EVP_MD_CTX_copy_ex(this->ctx_.get(), other.ctx_.get()); + return *this; +} + +SecureHash::SecureHash(SecureHash&& other) = default; +SecureHash& SecureHash::operator=(SecureHash&& other) = default; + +SecureHash::~SecureHash() = default; + +void SecureHash::Update(const uint8_t* input, size_t len) { + EVP_DigestUpdate(ctx_.get(), input, len); +} + +void SecureHash::Finish(uint8_t* output) { + EVP_DigestFinal(ctx_.get(), output, nullptr); +} + +void SecureHash::Update(const std::string& input) { + Update(reinterpret_cast<const uint8_t*>(input.data()), input.length()); +} + +void SecureHash::Finish(char* output) { + Finish(reinterpret_cast<uint8_t*>(output)); +} + +size_t SecureHash::GetHashLength() const { + return EVP_MD_CTX_size(ctx_.get()); +} + +} // namespace openscreen diff --git a/util/crypto/secure_hash.h b/util/crypto/secure_hash.h new file mode 100644 index 00000000..7c007f96 --- /dev/null +++ b/util/crypto/secure_hash.h @@ -0,0 +1,48 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UTIL_CRYPTO_SECURE_HASH_H_ +#define UTIL_CRYPTO_SECURE_HASH_H_ + +#include <stddef.h> + +#include <memory> +#include <string> + +#include "openssl/base.h" +#include "openssl/evp.h" +#include "platform/base/macros.h" + +namespace openscreen { + +// A wrapper to calculate secure hashes incrementally, allowing to +// be used when the full input is not known in advance. The end result will the +// same as if we have the full input in advance. +class SecureHash { + public: + SecureHash(const EVP_MD* type); + SecureHash(const SecureHash& other); + SecureHash(SecureHash&& other); + SecureHash& operator=(const SecureHash& other); + SecureHash& operator=(SecureHash&& other); + + ~SecureHash(); + + void Update(const uint8_t* input, size_t len); + void Finish(uint8_t* output); + + // Handy versions that do the kludgy casting to unsigned in the background. + void Update(const std::string& input); + void Finish(char* output); + + size_t GetHashLength() const; + + private: + bssl::UniquePtr<EVP_MD_CTX> ctx_ = + bssl::UniquePtr<EVP_MD_CTX>(EVP_MD_CTX_new()); +}; + +} // namespace openscreen + +#endif // UTIL_CRYPTO_SECURE_HASH_H_ diff --git a/util/crypto/secure_hash_unittest.cc b/util/crypto/secure_hash_unittest.cc new file mode 100644 index 00000000..e7a2be02 --- /dev/null +++ b/util/crypto/secure_hash_unittest.cc @@ -0,0 +1,103 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "util/crypto/secure_hash.h" + +#include <stddef.h> +#include <stdint.h> + +#include <memory> +#include <string> +#include <vector> + +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include "openssl/evp.h" +#include "openssl/sha.h" + +namespace openscreen { +TEST(SecureHashTest, TestUpdate) { + // Example B.3 from FIPS 180-2: long message. + std::string input3(500000, 'a'); // 'a' repeated half a million times + const int kExpectedHashOfInput3[] = { + 0xcd, 0xc7, 0x6e, 0x5c, 0x99, 0x14, 0xfb, 0x92, 0x81, 0xa1, 0xc7, + 0xe2, 0x84, 0xd7, 0x3e, 0x67, 0xf1, 0x80, 0x9a, 0x48, 0xa4, 0x97, + 0x20, 0x0e, 0x04, 0x6d, 0x39, 0xcc, 0xc7, 0x11, 0x2c, 0xd0}; + + SecureHash ctx(EVP_sha256()); + std::vector<uint8_t> output3(ctx.GetHashLength()); + ctx.Update(input3); + ctx.Update(input3); + ctx.Finish(output3.data()); + EXPECT_THAT(output3, testing::ElementsAreArray(kExpectedHashOfInput3)); +} + +TEST(SecureHashTest, TestCopyable) { + std::string input1(10001, 'a'); // 'a' repeated 10001 times + std::string input2(10001, 'd'); // 'd' repeated 10001 times + + const uint8_t kExpectedHashOfInput1[SHA256_DIGEST_LENGTH] = { + 0x0c, 0xab, 0x99, 0xa0, 0x58, 0x60, 0x0f, 0xfa, 0xad, 0x12, 0x92, + 0xd0, 0xc5, 0x3c, 0x05, 0x48, 0xeb, 0xaf, 0x88, 0xdd, 0x1d, 0x01, + 0x03, 0x03, 0x45, 0x70, 0x5f, 0x01, 0x8a, 0x81, 0x39, 0x09}; + const uint8_t kExpectedHashOfInput1And2[SHA256_DIGEST_LENGTH] = { + 0x4c, 0x8e, 0x26, 0x5a, 0xc3, 0x85, 0x1f, 0x1f, 0xa5, 0x04, 0x1c, + 0xc7, 0x88, 0x53, 0x1c, 0xc7, 0x80, 0x47, 0x15, 0xfb, 0x47, 0xff, + 0x72, 0xb1, 0x28, 0x37, 0xb0, 0x4d, 0x6e, 0x22, 0x2e, 0x4d}; + + SecureHash ctx1(EVP_sha256()); + std::vector<uint8_t> output1(ctx1.GetHashLength()); + ctx1.Update(input1); + + SecureHash ctx2 = ctx1; + std::vector<uint8_t> output2(ctx2.GetHashLength()); + + SecureHash ctx3 = ctx1; + std::vector<uint8_t> output3(ctx3.GetHashLength()); + + // At this point, ctx1, ctx2, and ctx3 are all equivalent and represent the + // state after hashing input1. + + // Updating ctx1 and ctx2 with input2 should produce equivalent results. + ctx1.Update(input2); + ctx1.Finish(output1.data()); + + ctx2.Update(input2); + ctx2.Finish(output2.data()); + + EXPECT_THAT(output1, testing::ElementsAreArray(output2)); + EXPECT_THAT(output1, testing::ElementsAreArray(kExpectedHashOfInput1And2)); + + // Finish() ctx3, which should produce the hash of input1. + ctx3.Finish(output3.data()); + EXPECT_THAT(output3, testing::ElementsAreArray(kExpectedHashOfInput1)); +} + +TEST(SecureHashTest, TestLength) { + SecureHash ctx(EVP_sha256()); + EXPECT_EQ(SHA256_DIGEST_LENGTH, ctx.GetHashLength()); +} + +TEST(SecureHashTest, Equality) { + std::string input1(10001, 'a'); // 'a' repeated 10001 times + std::string input2(10001, 'd'); // 'd' repeated 10001 times + + // Call Update() twice on input1 and input2. + SecureHash ctx1(EVP_sha256()); + std::vector<uint8_t> output1(ctx1.GetHashLength()); + ctx1.Update(input1); + ctx1.Update(input2); + ctx1.Finish(output1.data()); + + // Call Update() once one input1 + input2 (concatenation). + SecureHash ctx2(EVP_sha256()); + std::vector<uint8_t> output2(ctx2.GetHashLength()); + std::string input3 = input1 + input2; + ctx2.Update(input3); + ctx2.Finish(output2.data()); + + // The hash should be the same. + EXPECT_THAT(output1, testing::ElementsAreArray(output2)); +} +} // namespace openscreen diff --git a/util/crypto/sha2.cc b/util/crypto/sha2.cc new file mode 100644 index 00000000..dc4baa09 --- /dev/null +++ b/util/crypto/sha2.cc @@ -0,0 +1,27 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "util/crypto/sha2.h" + +#include <stddef.h> + +#include <memory> + +#include "util/crypto/secure_hash.h" +#include "util/std_util.h" + +namespace openscreen { + +void SHA256HashString(absl::string_view str, + uint8_t output[SHA256_DIGEST_LENGTH]) { + SHA256(reinterpret_cast<const uint8_t*>(str.data()), str.length(), output); +} + +std::string SHA256HashString(absl::string_view str) { + std::string output(SHA256_DIGEST_LENGTH, 0); + SHA256HashString(str, reinterpret_cast<uint8_t*>(data(output))); + return output; +} + +} // namespace openscreen diff --git a/util/crypto/sha2.h b/util/crypto/sha2.h new file mode 100644 index 00000000..59da3453 --- /dev/null +++ b/util/crypto/sha2.h @@ -0,0 +1,33 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UTIL_CRYPTO_SHA2_H_ +#define UTIL_CRYPTO_SHA2_H_ + +#include <stddef.h> + +#include <string> + +#include "absl/strings/string_view.h" +#include "openssl/sha.h" + +namespace openscreen { + +// These functions perform SHA-256 operations. +// +// Functions for SHA-384 and SHA-512 can be added when the need arises. + +// Computes the SHA-256 hash of the input string 'str' and stores the first +// 'len' bytes of the hash in the output buffer 'output'. If 'len' > 32, +// only 32 bytes (the full hash) are stored in the 'output' buffer. +void SHA256HashString(absl::string_view str, + uint8_t output[SHA256_DIGEST_LENGTH]); + +// Convenience version of the above that returns the result in a 32-byte +// string. +std::string SHA256HashString(absl::string_view str); + +} // namespace openscreen + +#endif // UTIL_CRYPTO_SHA2_H_ diff --git a/util/crypto/sha2_unittest.cc b/util/crypto/sha2_unittest.cc new file mode 100644 index 00000000..57d55348 --- /dev/null +++ b/util/crypto/sha2_unittest.cc @@ -0,0 +1,68 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "util/crypto/sha2.h" + +#include <stddef.h> +#include <stdint.h> + +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include "util/std_util.h" + +namespace openscreen { +TEST(Sha256Test, Test1) { + // Example B.1 from FIPS 180-2: one-block message. + std::string input = "abc"; + constexpr uint8_t kExpected[] = { + 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, + 0xde, 0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, + 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad}; + + uint8_t output[SHA256_DIGEST_LENGTH]; + SHA256HashString(input, output); + EXPECT_THAT(output, testing::ElementsAreArray(kExpected)); +} + +TEST(Sha256Test, Test1_String) { + // Same as the above, but using the wrapper that returns a std::string. + // Example B.1 from FIPS 180-2: one-block message. + std::string input = "abc"; + constexpr uint8_t kExpected[] = { + 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, + 0xde, 0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, + 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad}; + + const std::string output = SHA256HashString(input); + ASSERT_EQ(SHA256_DIGEST_LENGTH, output.size()); + EXPECT_THAT(output, testing::ElementsAreArray(kExpected)); +} + +TEST(Sha256Test, Test2) { + // Example B.2 from FIPS 180-2: multi-block message. + std::string input = + "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; + constexpr uint8_t kExpected[] = { + 0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8, 0xe5, 0xc0, 0x26, + 0x93, 0x0c, 0x3e, 0x60, 0x39, 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, + 0x21, 0x67, 0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1}; + + uint8_t output[SHA256_DIGEST_LENGTH]; + SHA256HashString(input, output); + EXPECT_THAT(output, testing::ElementsAreArray(kExpected)); +} + +TEST(Sha256Test, Test3) { + // Example B.3 from FIPS 180-2: long message. + std::string input(1000000, 'a'); // 'a' repeated a million times + constexpr uint8_t kExpected[] = { + 0xcd, 0xc7, 0x6e, 0x5c, 0x99, 0x14, 0xfb, 0x92, 0x81, 0xa1, 0xc7, + 0xe2, 0x84, 0xd7, 0x3e, 0x67, 0xf1, 0x80, 0x9a, 0x48, 0xa4, 0x97, + 0x20, 0x0e, 0x04, 0x6d, 0x39, 0xcc, 0xc7, 0x11, 0x2c, 0xd0}; + + uint8_t output[SHA256_DIGEST_LENGTH]; + SHA256HashString(input, output); + EXPECT_THAT(output, testing::ElementsAreArray(kExpected)); +} +} // namespace openscreen diff --git a/util/json/DEPS b/util/json/DEPS new file mode 100644 index 00000000..2defcf11 --- /dev/null +++ b/util/json/DEPS @@ -0,0 +1,8 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +include_rules = [ + '+platform/api', + '+json' +] diff --git a/util/json/json_reader.cc b/util/json/json_reader.cc new file mode 100644 index 00000000..a128a367 --- /dev/null +++ b/util/json/json_reader.cc @@ -0,0 +1,40 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "util/json/json_reader.h" + +#include <memory> +#include <string> + +#include "json/value.h" +#include "platform/api/logging.h" +#include "platform/base/error.h" + +namespace openscreen { +namespace { +// A reasonable maximum stack depth, may need to adjust as needs change. +constexpr int kMaxStackDepth = 64; +} // namespace + +JsonReader::JsonReader() { + builder_["stackLimit"] = kMaxStackDepth; +} + +ErrorOr<Json::Value> JsonReader::Read(absl::string_view document) { + if (document.empty()) { + return ErrorOr<Json::Value>(Error::Code::kJsonParseError, "empty document"); + } + + Json::Value root_node; + std::string error_msg; + std::unique_ptr<Json::CharReader> reader(builder_.newCharReader()); + const bool succeeded = + reader->parse(document.begin(), document.end(), &root_node, &error_msg); + if (!succeeded) { + return ErrorOr<Json::Value>(Error::Code::kJsonParseError, error_msg); + } + + return root_node; +} +} // namespace openscreen diff --git a/util/json/json_reader.h b/util/json/json_reader.h new file mode 100644 index 00000000..cb7cded0 --- /dev/null +++ b/util/json/json_reader.h @@ -0,0 +1,33 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UTIL_JSON_JSON_READER_H_ +#define UTIL_JSON_JSON_READER_H_ + +#include <memory> + +#include "absl/strings/string_view.h" +#include "json/reader.h" + +namespace Json { +class Value; +} + +namespace openscreen { +template <typename T> +class ErrorOr; + +class JsonReader { + public: + JsonReader(); + + ErrorOr<Json::Value> Read(absl::string_view document); + + private: + Json::CharReaderBuilder builder_; +}; + +} // namespace openscreen + +#endif // UTIL_JSON_JSON_READER_H_
\ No newline at end of file diff --git a/util/json/json_reader_unittest.cc b/util/json/json_reader_unittest.cc new file mode 100644 index 00000000..b94cca13 --- /dev/null +++ b/util/json/json_reader_unittest.cc @@ -0,0 +1,53 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "util/json/json_reader.h" + +#include <string> + +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include "platform/base/error.h" + +namespace openscreen { +namespace { +template <typename Value> +void AssertError(ErrorOr<Value> error_or, Error::Code code) { + EXPECT_EQ(error_or.error().code(), code); +} +} // namespace + +TEST(JsonReaderTest, MalformedDocumentReturnsParseError) { + JsonReader reader; + + const std::array<std::string, 4> kMalformedDocuments{ + {"", "{", "{ foo: bar }", R"({"foo": "bar", "foo": baz})"}}; + + for (auto& document : kMalformedDocuments) { + AssertError(reader.Read(document), Error::Code::kJsonParseError); + } +} + +TEST(JsonReaderTest, ValidEmptyDocumentParsedCorrectly) { + JsonReader reader; + + const auto actual = reader.Read("{}"); + + EXPECT_TRUE(actual.is_value()); + EXPECT_EQ(actual.value().getMemberNames().size(), 0); +} + +// Jsoncpp has its own suite of tests ensure that things are parsed correctly, +// so we only do some rudimentary checks here to make sure we didn't mangle +// the value. +TEST(JsonReaderTest, ValidDocumentParsedCorrectly) { + JsonReader reader; + + const auto actual = reader.Read(R"({"foo": "bar", "baz": 1337})"); + + EXPECT_TRUE(actual.is_value()); + EXPECT_EQ(actual.value().getMemberNames().size(), 2); +} + +} // namespace openscreen diff --git a/util/json/json_writer.cc b/util/json/json_writer.cc new file mode 100644 index 00000000..c2d01521 --- /dev/null +++ b/util/json/json_writer.cc @@ -0,0 +1,46 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "util/json/json_writer.h" + +#include <memory> +#include <sstream> +#include <string> +#include <utility> + +#include "json/value.h" +#include "platform/api/logging.h" +#include "platform/base/error.h" + +namespace openscreen { +JsonWriter::JsonWriter() { +#ifndef _DEBUG + // Default is to "pretty print" the output JSON in a human readable + // format. On non-debug builds, we can remove pretty printing by simply + // getting rid of all indentation. + factory_["indentation"] = ""; +#endif +} + +ErrorOr<std::string> JsonWriter::Write(const Json::Value& value) { + if (value.empty()) { + return ErrorOr<std::string>(Error::Code::kJsonWriteError, "Empty value"); + } + + std::unique_ptr<Json::StreamWriter> const writer(factory_.newStreamWriter()); + std::stringstream stream; + writer->write(value, &stream); + stream << std::endl; + + if (!stream) { + // Note: jsoncpp doesn't give us more information about what actually + // went wrong, just says to "check the stream". However, failures on + // the stream should be rare, as we do not throw any errors in the jsoncpp + // library. + return ErrorOr<std::string>(Error::Code::kJsonWriteError, "Invalid stream"); + } + + return stream.str(); +} +} // namespace openscreen diff --git a/util/json/json_writer.h b/util/json/json_writer.h new file mode 100644 index 00000000..df37d9a0 --- /dev/null +++ b/util/json/json_writer.h @@ -0,0 +1,34 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UTIL_JSON_JSON_WRITER_H_ +#define UTIL_JSON_JSON_WRITER_H_ + +#include <memory> +#include <string> + +#include "absl/strings/string_view.h" +#include "json/writer.h" + +namespace Json { +class Value; +} + +namespace openscreen { +template <typename T> +class ErrorOr; + +class JsonWriter { + public: + JsonWriter(); + + ErrorOr<std::string> Write(const Json::Value& value); + + private: + Json::StreamWriterBuilder factory_; +}; + +} // namespace openscreen + +#endif // UTIL_JSON_JSON_WRITER_H_ diff --git a/util/json/json_writer_unittest.cc b/util/json/json_writer_unittest.cc new file mode 100644 index 00000000..8b75c82e --- /dev/null +++ b/util/json/json_writer_unittest.cc @@ -0,0 +1,32 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "util/json/json_writer.h" + +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include "platform/base/error.h" + +namespace openscreen { + +TEST(JsonWriterTest, NullValueReturnsError) { + JsonWriter writer; + + const auto null_value = Json::Value(); + const auto actual = writer.Write(null_value); + + EXPECT_TRUE(actual.is_error()); + EXPECT_EQ(actual.error().code(), Error::Code::kJsonWriteError); +} + +TEST(JsonWriterTest, ValidValueReturnsString) { + JsonWriter writer; + + const Json::Int64 value = 31337; + const auto actual = writer.Write(value); + + EXPECT_TRUE(actual.is_value()); + EXPECT_EQ(actual.value(), "31337\n"); +} +} // namespace openscreen diff --git a/util/std_util.h b/util/std_util.h new file mode 100644 index 00000000..bd370f8e --- /dev/null +++ b/util/std_util.h @@ -0,0 +1,52 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UTIL_STD_UTIL_H_ +#define UTIL_STD_UTIL_H_ + +#include <map> +#include <string> + +#include "absl/algorithm/container.h" + +namespace openscreen { + +// std::basic_string::data() has no mutable overload prior to C++17 [1]. +// Hence this overload is provided. +// Note: str[0] is safe even for empty strings, as they are guaranteed to be +// null-terminated [2]. +// +// [1] http://en.cppreference.com/w/cpp/string/basic_string/data +// [2] http://en.cppreference.com/w/cpp/string/basic_string/operator_at +template <typename CharT, typename Traits, typename Allocator> +CharT* data(std::basic_string<CharT, Traits, Allocator>& str) { + return std::addressof(str[0]); +} + +template <typename Key, typename Value> +void RemoveValueFromMap(std::map<Key, Value*>* map, Value* value) { + for (auto it = map->begin(); it != map->end();) { + if (it->second == value) { + it = map->erase(it); + } else { + ++it; + } + } +} + +template <typename ForwardIteratingContainer> +bool AreElementsSortedAndUnique(const ForwardIteratingContainer& c) { + return absl::c_is_sorted(c) && (absl::c_adjacent_find(c) == c.end()); +} + +template <typename RandomAccessContainer> +void SortAndDedupeElements(RandomAccessContainer* c) { + std::sort(c->begin(), c->end()); + const auto new_end = std::unique(c->begin(), c->end()); + c->erase(new_end, c->end()); +} + +} // namespace openscreen + +#endif // UTIL_STD_UTIL_H_ diff --git a/util/stringprintf.h b/util/stringprintf.h new file mode 100644 index 00000000..93e5eb93 --- /dev/null +++ b/util/stringprintf.h @@ -0,0 +1,41 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UTIL_STRINGPRINTF_H_ +#define UTIL_STRINGPRINTF_H_ + +#include <ostream> + +namespace openscreen { + +template <typename It> +void PrettyPrintAsciiHex(std::ostream& os, It first, It last) { + auto it = first; + while (it != last) { + uint8_t c = *it++; + if (c >= ' ' && c <= '~') { + os.put(c); + } else { + // Output a hex escape sequence for non-printable values. + os.put('\\'); + os.put('x'); + char digit = (c >> 4) & 0xf; + if (digit >= 0 && digit <= 9) { + os.put(digit + '0'); + } else { + os.put(digit - 10 + 'a'); + } + digit = c & 0xf; + if (digit >= 0 && digit <= 9) { + os.put(digit + '0'); + } else { + os.put(digit - 10 + 'a'); + } + } + } +} + +} // namespace openscreen + +#endif // UTIL_STRINGPRINTF_H_ |