From ce7fcbb4aea884bb4bf433cf419ffa267f859c87 Mon Sep 17 00:00:00 2001 From: Lee Clagett Date: Sun, 5 Feb 2017 17:48:03 -0500 Subject: Add server auth to monerod, and client auth to wallet-cli and wallet-rpc --- contrib/epee/include/net/http_base.h | 12 + contrib/epee/include/net/http_client.h | 95 ++- contrib/epee/include/net/http_protocol_handler.h | 1 - contrib/epee/include/net/http_protocol_handler.inl | 7 - contrib/epee/include/net/http_server_impl_base.h | 4 +- .../epee/include/storages/http_abstract_invoke.h | 11 +- contrib/epee/src/http_auth.cpp | 2 +- src/common/CMakeLists.txt | 3 + src/common/command_line.cpp | 1 - src/common/command_line.h | 1 - src/common/common_fwd.h | 41 ++ src/common/password.cpp | 271 ++++++++ src/common/password.h | 96 +++ src/common/rpc_client.h | 6 +- src/daemon/command_parser_executor.cpp | 4 +- src/daemon/command_parser_executor.h | 5 +- src/daemon/command_server.cpp | 4 +- src/daemon/command_server.h | 4 +- src/daemon/daemon.cpp | 4 +- src/daemon/main.cpp | 21 +- src/daemon/rpc_command_executor.cpp | 8 +- src/daemon/rpc_command_executor.h | 5 +- src/rpc/CMakeLists.txt | 7 +- src/rpc/core_rpc_server.cpp | 49 +- src/rpc/core_rpc_server.h | 8 - src/rpc/rpc_args.cpp | 96 +++ src/rpc/rpc_args.h | 67 ++ src/simplewallet/simplewallet.cpp | 2 +- src/simplewallet/simplewallet.h | 2 +- src/wallet/CMakeLists.txt | 3 +- src/wallet/api/wallet.cpp | 2 +- src/wallet/api/wallet_manager.cpp | 2 +- src/wallet/password_container.cpp | 248 ------- src/wallet/password_container.h | 67 -- src/wallet/wallet2.cpp | 21 +- src/wallet/wallet2.h | 7 +- src/wallet/wallet_rpc_server.cpp | 87 +-- tests/functional_tests/transactions_flow_test.cpp | 2 +- tests/unit_tests/CMakeLists.txt | 2 +- tests/unit_tests/http.cpp | 738 +++++++++++++++++++++ tests/unit_tests/http_auth.cpp | 724 -------------------- 41 files changed, 1523 insertions(+), 1217 deletions(-) create mode 100644 src/common/common_fwd.h create mode 100644 src/common/password.cpp create mode 100644 src/common/password.h create mode 100644 src/rpc/rpc_args.cpp create mode 100644 src/rpc/rpc_args.h delete mode 100644 src/wallet/password_container.cpp delete mode 100644 src/wallet/password_container.h create mode 100644 tests/unit_tests/http.cpp delete mode 100644 tests/unit_tests/http_auth.cpp diff --git a/contrib/epee/include/net/http_base.h b/contrib/epee/include/net/http_base.h index d8e31521f..e5aa06cb4 100644 --- a/contrib/epee/include/net/http_base.h +++ b/contrib/epee/include/net/http_base.h @@ -29,6 +29,9 @@ #pragma once #include #include +#include +#include +#include #include "string_tools.h" @@ -90,6 +93,15 @@ namespace net_utils return std::string(); } + static inline void add_field(std::string& out, const boost::string_ref name, const boost::string_ref value) + { + out.append(name.data(), name.size()).append(": "); + out.append(value.data(), value.size()).append("\r\n"); + } + static inline void add_field(std::string& out, const std::pair& field) + { + add_field(out, field.first, field.second); + } struct http_header_info diff --git a/contrib/epee/include/net/http_client.h b/contrib/epee/include/net/http_client.h index c5aeb9251..3d8c759cd 100644 --- a/contrib/epee/include/net/http_client.h +++ b/contrib/epee/include/net/http_client.h @@ -30,6 +30,8 @@ #include #include #include +#include +#include //#include #include #include @@ -45,6 +47,7 @@ #include "string_tools.h" #include "reg_exp_definer.h" #include "http_base.h" +#include "http_auth.h" #include "to_nonconst_iterator.h" #include "net_parse_helpers.h" @@ -236,9 +239,6 @@ using namespace std; class http_simple_client: public i_target_handler { - public: - - private: enum reciev_machine_state { @@ -263,6 +263,7 @@ using namespace std; blocked_mode_client m_net_client; std::string m_host_buff; std::string m_port; + http_client_auth m_auth; std::string m_header_cache; http_response_info m_response_info; size_t m_len_in_summary; @@ -280,6 +281,7 @@ using namespace std; , m_net_client() , m_host_buff() , m_port() + , m_auth() , m_header_cache() , m_response_info() , m_len_in_summary(0) @@ -291,21 +293,22 @@ using namespace std; , m_lock() {} - bool set_server(const std::string& address) + bool set_server(const std::string& address, boost::optional user) { http::url_content parsed{}; const bool r = parse_url(address, parsed); CHECK_AND_ASSERT_MES(r, false, "failed to parse url: " << address); - set_server(std::move(parsed.host), std::to_string(parsed.port)); + set_server(std::move(parsed.host), std::to_string(parsed.port), std::move(user)); return true; } - void set_server(std::string host, std::string port) + void set_server(std::string host, std::string port, boost::optional user) { CRITICAL_REGION_LOCAL(m_lock); disconnect(); m_host_buff = std::move(host); m_port = std::move(port); + m_auth = user ? http_client_auth{std::move(*user)} : http_client_auth{}; } bool connect(std::chrono::milliseconds timeout) @@ -335,14 +338,14 @@ using namespace std; } //--------------------------------------------------------------------------- inline - bool invoke_get(const std::string& uri, std::chrono::milliseconds timeout, const std::string& body = std::string(), const http_response_info** ppresponse_info = NULL, const fields_list& additional_params = fields_list()) + bool invoke_get(const boost::string_ref uri, std::chrono::milliseconds timeout, const std::string& body = std::string(), const http_response_info** ppresponse_info = NULL, const fields_list& additional_params = fields_list()) { CRITICAL_REGION_LOCAL(m_lock); return invoke(uri, "GET", body, timeout, ppresponse_info, additional_params); } //--------------------------------------------------------------------------- - inline bool invoke(const std::string& uri, const std::string& method, const std::string& body, std::chrono::milliseconds timeout, const http_response_info** ppresponse_info = NULL, const fields_list& additional_params = fields_list()) + inline bool invoke(const boost::string_ref uri, const boost::string_ref method, const std::string& body, std::chrono::milliseconds timeout, const http_response_info** ppresponse_info = NULL, const fields_list& additional_params = fields_list()) { CRITICAL_REGION_LOCAL(m_lock); if(!is_connected()) @@ -354,32 +357,64 @@ using namespace std; return false; } } - m_response_info.clear(); - std::string req_buff = method + " "; - req_buff += uri + " HTTP/1.1\r\n" + - "Host: "+ m_host_buff +"\r\n" + "Content-Length: " + boost::lexical_cast(body.size()) + "\r\n"; + std::string req_buff{}; + req_buff.reserve(2048); + req_buff.append(method.data(), method.size()).append(" ").append(uri.data(), uri.size()).append(" HTTP/1.1\r\n"); + add_field(req_buff, "Host", m_host_buff); + add_field(req_buff, "Content-Length", std::to_string(body.size())); //handle "additional_params" - for(fields_list::const_iterator it = additional_params.begin(); it!=additional_params.end(); it++) - req_buff += it->first + ": " + it->second + "\r\n"; - req_buff += "\r\n"; - //-- - - bool res = m_net_client.send(req_buff, timeout); - CHECK_AND_ASSERT_MES(res, false, "HTTP_CLIENT: Failed to SEND"); - if(body.size()) - res = m_net_client.send(body, timeout); - CHECK_AND_ASSERT_MES(res, false, "HTTP_CLIENT: Failed to SEND"); - - if(ppresponse_info) - *ppresponse_info = &m_response_info; - - m_state = reciev_machine_state_header; - return handle_reciev(timeout); + for(const auto& field : additional_params) + add_field(req_buff, field); + + for (unsigned sends = 0; sends < 2; ++sends) + { + const std::size_t initial_size = req_buff.size(); + const auto auth = m_auth.get_auth_field(method, uri); + if (auth) + add_field(req_buff, *auth); + + req_buff += "\r\n"; + //-- + + bool res = m_net_client.send(req_buff, timeout); + CHECK_AND_ASSERT_MES(res, false, "HTTP_CLIENT: Failed to SEND"); + if(body.size()) + res = m_net_client.send(body, timeout); + CHECK_AND_ASSERT_MES(res, false, "HTTP_CLIENT: Failed to SEND"); + + + m_response_info.clear(); + m_state = reciev_machine_state_header; + if (!handle_reciev(timeout)) + return false; + if (m_response_info.m_response_code != 401) + { + if(ppresponse_info) + *ppresponse_info = std::addressof(m_response_info); + return true; + } + + switch (m_auth.handle_401(m_response_info)) + { + case http_client_auth::kSuccess: + break; + case http_client_auth::kBadPassword: + sends = 2; + break; + default: + case http_client_auth::kParseFailure: + LOG_ERROR("Bad server response for authentication"); + return false; + } + req_buff.resize(initial_size); // rollback for new auth generation + } + LOG_ERROR("Client has incorrect username/password for server requiring authentication"); + return false; } //--------------------------------------------------------------------------- - inline bool invoke_post(const std::string& uri, const std::string& body, std::chrono::milliseconds timeout, const http_response_info** ppresponse_info = NULL, const fields_list& additional_params = fields_list()) + inline bool invoke_post(const boost::string_ref uri, const std::string& body, std::chrono::milliseconds timeout, const http_response_info** ppresponse_info = NULL, const fields_list& additional_params = fields_list()) { CRITICAL_REGION_LOCAL(m_lock); return invoke(uri, "POST", body, timeout, ppresponse_info, additional_params); @@ -730,7 +765,7 @@ using namespace std; else if(result[i++].matched)//"User-Agent" body_info.m_user_agent = result[field_val]; else if(result[i++].matched)//e.t.c (HAVE TO BE MATCHED!) - {;} + body_info.m_etc_fields.emplace_back(result[11], result[field_val]); else {CHECK_AND_ASSERT_MES(false, false, "http_stream_filter::parse_cached_header() not matched last entry in:"< m_user; critical_section m_lock; }; diff --git a/contrib/epee/include/net/http_protocol_handler.inl b/contrib/epee/include/net/http_protocol_handler.inl index 5bfaf4767..d9eca2479 100644 --- a/contrib/epee/include/net/http_protocol_handler.inl +++ b/contrib/epee/include/net/http_protocol_handler.inl @@ -390,13 +390,6 @@ namespace net_utils return false; } - if (!m_config.m_required_user_agent.empty() && m_query_info.m_header_info.m_user_agent != m_config.m_required_user_agent) - { - LOG_ERROR("simple_http_connection_handler::analize_cached_request_header_and_invoke_state(): unexpected user agent: " << m_query_info.m_header_info.m_user_agent); - m_state = http_state_error; - return false; - } - m_cache.erase(0, pos); std::string req_command_str = m_query_info.m_full_request_str; diff --git a/contrib/epee/include/net/http_server_impl_base.h b/contrib/epee/include/net/http_server_impl_base.h index f2a580167..2a762b3ca 100644 --- a/contrib/epee/include/net/http_server_impl_base.h +++ b/contrib/epee/include/net/http_server_impl_base.h @@ -56,7 +56,7 @@ namespace epee {} bool init(const std::string& bind_port = "0", const std::string& bind_ip = "0.0.0.0", - std::string user_agent = "", boost::optional user = boost::none) + boost::optional user = boost::none) { //set self as callback handler @@ -65,8 +65,6 @@ namespace epee //here set folder for hosting reqests m_net_server.get_config_object().m_folder = ""; - // workaround till we get auth/encryption - m_net_server.get_config_object().m_required_user_agent = std::move(user_agent); m_net_server.get_config_object().m_user = std::move(user); LOG_PRINT_L0("Binding on " << bind_ip << ":" << bind_port); diff --git a/contrib/epee/include/storages/http_abstract_invoke.h b/contrib/epee/include/storages/http_abstract_invoke.h index 36177c7e0..47981acb3 100644 --- a/contrib/epee/include/storages/http_abstract_invoke.h +++ b/contrib/epee/include/storages/http_abstract_invoke.h @@ -26,6 +26,9 @@ // #pragma once +#include +#include +#include #include "portable_storage_template_helper.h" #include "net/http_base.h" #include "net/http_server_handlers_map2.h" @@ -35,7 +38,7 @@ namespace epee namespace net_utils { template - bool invoke_http_json(const std::string& uri, const t_request& out_struct, t_response& result_struct, t_transport& transport, std::chrono::milliseconds timeout = std::chrono::seconds(5), const std::string& method = "GET") + bool invoke_http_json(const boost::string_ref uri, const t_request& out_struct, t_response& result_struct, t_transport& transport, std::chrono::milliseconds timeout = std::chrono::seconds(5), const boost::string_ref method = "GET") { std::string req_param; if(!serialization::store_t_to_json(out_struct, req_param)) @@ -66,7 +69,7 @@ namespace epee template - bool invoke_http_bin(const std::string& uri, const t_request& out_struct, t_response& result_struct, t_transport& transport, std::chrono::milliseconds timeout = std::chrono::seconds(5), const std::string& method = "GET") + bool invoke_http_bin(const boost::string_ref uri, const t_request& out_struct, t_response& result_struct, t_transport& transport, std::chrono::milliseconds timeout = std::chrono::seconds(5), const boost::string_ref method = "GET") { std::string req_param; if(!serialization::store_t_to_binary(out_struct, req_param)) @@ -95,7 +98,7 @@ namespace epee } template - bool invoke_http_json_rpc(const std::string& uri, std::string method_name, const t_request& out_struct, t_response& result_struct, t_transport& transport, std::chrono::milliseconds timeout = std::chrono::seconds(5), const std::string& http_method = "GET", const std::string& req_id = "0") + bool invoke_http_json_rpc(const boost::string_ref uri, std::string method_name, const t_request& out_struct, t_response& result_struct, t_transport& transport, std::chrono::milliseconds timeout = std::chrono::seconds(5), const boost::string_ref http_method = "GET", const std::string& req_id = "0") { epee::json_rpc::request req_t = AUTO_VAL_INIT(req_t); req_t.jsonrpc = "2.0"; @@ -117,7 +120,7 @@ namespace epee } template - bool invoke_http_json_rpc(const std::string& uri, typename t_command::request& out_struct, typename t_command::response& result_struct, t_transport& transport, std::chrono::milliseconds timeout = std::chrono::seconds(5), const std::string& http_method = "GET", const std::string& req_id = "0") + bool invoke_http_json_rpc(const boost::string_ref uri, typename t_command::request& out_struct, typename t_command::response& result_struct, t_transport& transport, std::chrono::milliseconds timeout = std::chrono::seconds(5), const boost::string_ref http_method = "GET", const std::string& req_id = "0") { return invoke_http_json_rpc(uri, t_command::methodname(), out_struct, result_struct, transport, timeout, http_method, req_id); } diff --git a/contrib/epee/src/http_auth.cpp b/contrib/epee/src/http_auth.cpp index 7fd32dabc..4d2523e1f 100644 --- a/contrib/epee/src/http_auth.cpp +++ b/contrib/epee/src/http_auth.cpp @@ -362,7 +362,7 @@ namespace server_parameters best{}; - const std::list& fields = response.m_additional_fields; + const std::list& fields = response.m_header_info.m_etc_fields; auto current = fields.begin(); const auto end = fields.end(); while (true) diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt index dd17f6d64..a5d06f092 100644 --- a/src/common/CMakeLists.txt +++ b/src/common/CMakeLists.txt @@ -32,6 +32,7 @@ set(common_sources dns_utils.cpp util.cpp i18n.cpp + password.cpp perf_timer.cpp task_region.cpp thread_group.cpp) @@ -46,6 +47,7 @@ set(common_private_headers base58.h boost_serialization_helper.h command_line.h + common_fwd.h dns_utils.h http_connection.h int-util.h @@ -56,6 +58,7 @@ set(common_private_headers util.h varint.h i18n.h + password.h perf_timer.h stack_trace.h task_region.h diff --git a/src/common/command_line.cpp b/src/common/command_line.cpp index d95859256..c3df5c096 100644 --- a/src/common/command_line.cpp +++ b/src/common/command_line.cpp @@ -76,7 +76,6 @@ namespace command_line const arg_descriptor arg_version = {"version", "Output version information"}; const arg_descriptor arg_data_dir = {"data-dir", "Specify data directory"}; const arg_descriptor arg_testnet_data_dir = {"testnet-data-dir", "Specify testnet data directory"}; - const arg_descriptor arg_user_agent = {"user-agent", "Restrict RPC use to clients using this user agent"}; const arg_descriptor arg_test_drop_download = {"test-drop-download", "For net tests: in download, discard ALL blocks instead checking/saving them (very fast)"}; const arg_descriptor arg_test_drop_download_height = {"test-drop-download-height", "Like test-drop-download but disards only after around certain height", 0}; const arg_descriptor arg_test_dbg_lock_sleep = {"test-dbg-lock-sleep", "Sleep time in ms, defaults to 0 (off), used to debug before/after locking mutex. Values 100 to 1000 are good for tests."}; diff --git a/src/common/command_line.h b/src/common/command_line.h index 3f0919e99..a09365a6b 100644 --- a/src/common/command_line.h +++ b/src/common/command_line.h @@ -207,7 +207,6 @@ namespace command_line extern const arg_descriptor arg_version; extern const arg_descriptor arg_data_dir; extern const arg_descriptor arg_testnet_data_dir; - extern const arg_descriptor arg_user_agent; extern const arg_descriptor arg_test_drop_download; extern const arg_descriptor arg_test_drop_download_height; extern const arg_descriptor arg_test_dbg_lock_sleep; diff --git a/src/common/common_fwd.h b/src/common/common_fwd.h new file mode 100644 index 000000000..5d67251b1 --- /dev/null +++ b/src/common/common_fwd.h @@ -0,0 +1,41 @@ +// Copyright (c) 2014-2017, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, this list +// of conditions and the following disclaimer in the documentation and/or other +// materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its contributors may be +// used to endorse or promote products derived from this software without specific +// prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers + +#pragma once + +namespace tools +{ + class DNSResolver; + struct login; + class password_container; + class t_http_connection; + class task_region; + class thread_group; +} diff --git a/src/common/password.cpp b/src/common/password.cpp new file mode 100644 index 000000000..bdc9c69c0 --- /dev/null +++ b/src/common/password.cpp @@ -0,0 +1,271 @@ +// Copyright (c) 2014-2017, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, this list +// of conditions and the following disclaimer in the documentation and/or other +// materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its contributors may be +// used to endorse or promote products derived from this software without specific +// prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers + +#include "password.h" + +#include +#include +#include + +#if defined(_WIN32) +#include +#include +#else +#include +#include +#endif + +namespace +{ +#if defined(_WIN32) + bool is_cin_tty() noexcept + { + return 0 != _isatty(_fileno(stdin)); + } + + bool read_from_tty(std::string& pass) + { + static constexpr const char BACKSPACE = 8; + + HANDLE h_cin = ::GetStdHandle(STD_INPUT_HANDLE); + + DWORD mode_old; + ::GetConsoleMode(h_cin, &mode_old); + DWORD mode_new = mode_old & ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT); + ::SetConsoleMode(h_cin, mode_new); + + bool r = true; + pass.reserve(tools::password_container::max_password_size); + while (pass.size() < tools::password_container::max_password_size) + { + DWORD read; + char ch; + r = (TRUE == ::ReadConsoleA(h_cin, &ch, 1, &read, NULL)); + r &= (1 == read); + if (!r) + { + break; + } + else if (ch == '\n' || ch == '\r') + { + std::cout << std::endl; + break; + } + else if (ch == BACKSPACE) + { + if (!pass.empty()) + { + pass.back() = '\0'; + pass.resize(pass.size() - 1); + std::cout << "\b \b"; + } + } + else + { + pass.push_back(ch); + std::cout << '*'; + } + } + + ::SetConsoleMode(h_cin, mode_old); + + return r; + } + +#else // end WIN32 + + bool is_cin_tty() noexcept + { + return 0 != isatty(fileno(stdin)); + } + + int getch() noexcept + { + struct termios tty_old; + tcgetattr(STDIN_FILENO, &tty_old); + + struct termios tty_new; + tty_new = tty_old; + tty_new.c_lflag &= ~(ICANON | ECHO); + tcsetattr(STDIN_FILENO, TCSANOW, &tty_new); + + int ch = getchar(); + + tcsetattr(STDIN_FILENO, TCSANOW, &tty_old); + + return ch; + } + + bool read_from_tty(std::string& aPass) + { + static constexpr const char BACKSPACE = 127; + + aPass.reserve(tools::password_container::max_password_size); + while (aPass.size() < tools::password_container::max_password_size) + { + int ch = getch(); + if (EOF == ch) + { + return false; + } + else if (ch == '\n' || ch == '\r') + { + std::cout << std::endl; + break; + } + else if (ch == BACKSPACE) + { + if (!aPass.empty()) + { + aPass.back() = '\0'; + aPass.resize(aPass.size() - 1); + std::cout << "\b \b"; + } + } + else + { + aPass.push_back(ch); + std::cout << '*'; + } + } + + return true; + } + +#endif // end !WIN32 + + void clear(std::string& pass) noexcept + { + //! TODO Call a memory wipe function that hopefully is not optimized out + pass.replace(0, pass.capacity(), pass.capacity(), '\0'); + pass.clear(); + } + + bool read_from_tty(const bool verify, const char *message, std::string& pass1, std::string& pass2) + { + while (true) + { + if (message) + std::cout << message <<": "; + if (!read_from_tty(pass1)) + return false; + if (verify) + { + std::cout << "Confirm Password: "; + if (!read_from_tty(pass2)) + return false; + if(pass1!=pass2) + { + std::cout << "Passwords do not match! Please try again." << std::endl; + clear(pass1); + clear(pass2); + } + else //new password matches + return true; + } + else + return true; + //No need to verify password entered at this point in the code + } + + return false; + } + + bool read_from_file(std::string& pass) + { + pass.reserve(tools::password_container::max_password_size); + for (size_t i = 0; i < tools::password_container::max_password_size; ++i) + { + char ch = static_cast(std::cin.get()); + if (std::cin.eof() || ch == '\n' || ch == '\r') + { + break; + } + else if (std::cin.fail()) + { + return false; + } + else + { + pass.push_back(ch); + } + } + return true; + } + +} // anonymous namespace + +namespace tools +{ + // deleted via private member + password_container::password_container() noexcept : m_password() {} + password_container::password_container(std::string&& password) noexcept + : m_password(std::move(password)) + { + } + + password_container::~password_container() noexcept + { + clear(m_password); + } + + boost::optional password_container::prompt(const bool verify, const char *message) + { + password_container pass1{}; + password_container pass2{}; + if (is_cin_tty() ? read_from_tty(verify, message, pass1.m_password, pass2.m_password) : read_from_file(pass1.m_password)) + return {std::move(pass1)}; + + return boost::none; + } + + boost::optional login::parse(std::string&& userpass, bool verify, const char* message) + { + login out{}; + password_container wipe{std::move(userpass)}; + + const auto loc = wipe.password().find(':'); + if (loc == std::string::npos) + { + auto result = tools::password_container::prompt(verify, message); + if (!result) + return boost::none; + + out.password = std::move(*result); + } + else + { + out.password = password_container{wipe.password().substr(loc + 1)}; + } + + out.username = wipe.password().substr(0, loc); + return {std::move(out)}; + } +} diff --git a/src/common/password.h b/src/common/password.h new file mode 100644 index 000000000..12f715df4 --- /dev/null +++ b/src/common/password.h @@ -0,0 +1,96 @@ +// Copyright (c) 2014-2017, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, this list +// of conditions and the following disclaimer in the documentation and/or other +// materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its contributors may be +// used to endorse or promote products derived from this software without specific +// prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers + +#pragma once + +#include +#include + +namespace tools +{ + class password_container + { + public: + static constexpr const size_t max_password_size = 1024; + + //! Empty password + password_container() noexcept; + + //! `password` is used as password + password_container(std::string&& password) noexcept; + + //! \return A password from stdin TTY prompt or `std::cin` pipe. + static boost::optional prompt(bool verify, const char *mesage = "Password"); + + password_container(const password_container&) = delete; + password_container(password_container&& rhs) = default; + + //! Wipes internal password + ~password_container() noexcept; + + password_container& operator=(const password_container&) = delete; + password_container& operator=(password_container&&) = default; + + const std::string& password() const noexcept { return m_password; } + + private: + //! TODO Custom allocator that locks to RAM? + std::string m_password; + }; + + struct login + { + login() = default; + + /*! + Extracts username and password from the format `username:password`. A + blank username or password is allowed. If the `:` character is not + present, `password_container::prompt` will be called by forwarding the + `verify` and `message` arguments. + + \param userpass Is "consumed", and the memory contents are wiped. + \param verify is passed to `password_container::prompt` if necessary. + \param message is passed to `password_container::prompt` if necessary. + + \return The username and password, or boost::none if + `password_container::prompt` fails. + */ + static boost::optional parse(std::string&& userpass, bool verify, const char* message = "Password"); + + login(const login&) = delete; + login(login&&) = default; + ~login() = default; + login& operator=(const login&) = delete; + login& operator=(login&&) = default; + + std::string username; + password_container password; + }; +} diff --git a/src/common/rpc_client.h b/src/common/rpc_client.h index f5ecc8b50..40c103bf3 100644 --- a/src/common/rpc_client.h +++ b/src/common/rpc_client.h @@ -28,10 +28,13 @@ #pragma once +#include + #include "common/http_connection.h" #include "common/scoped_message_writer.h" #include "rpc/core_rpc_server_commands_defs.h" #include "storages/http_abstract_invoke.h" +#include "net/http_auth.h" #include "net/http_client.h" #include "string_tools.h" @@ -45,11 +48,12 @@ namespace tools t_rpc_client( uint32_t ip , uint16_t port + , boost::optional user ) : m_http_client{} { m_http_client.set_server( - epee::string_tools::get_ip_string_from_int32(ip), std::to_string(port) + epee::string_tools::get_ip_string_from_int32(ip), std::to_string(port), std::move(user) ); } diff --git a/src/daemon/command_parser_executor.cpp b/src/daemon/command_parser_executor.cpp index 27f9d0fd7..fd73654ac 100644 --- a/src/daemon/command_parser_executor.cpp +++ b/src/daemon/command_parser_executor.cpp @@ -37,11 +37,11 @@ namespace daemonize { t_command_parser_executor::t_command_parser_executor( uint32_t ip , uint16_t port - , const std::string &user_agent + , const boost::optional& login , bool is_rpc , cryptonote::core_rpc_server* rpc_server ) - : m_executor(ip, port, user_agent, is_rpc, rpc_server) + : m_executor(ip, port, login, is_rpc, rpc_server) {} bool t_command_parser_executor::print_peer_list(const std::vector& args) diff --git a/src/daemon/command_parser_executor.h b/src/daemon/command_parser_executor.h index 15293ade9..1fe3e0f98 100644 --- a/src/daemon/command_parser_executor.h +++ b/src/daemon/command_parser_executor.h @@ -36,7 +36,10 @@ #pragma once +#include + #include "daemon/rpc_command_executor.h" +#include "common/common_fwd.h" #include "rpc/core_rpc_server.h" namespace daemonize { @@ -49,7 +52,7 @@ public: t_command_parser_executor( uint32_t ip , uint16_t port - , const std::string &user_agent + , const boost::optional& login , bool is_rpc , cryptonote::core_rpc_server* rpc_server = NULL ); diff --git a/src/daemon/command_server.cpp b/src/daemon/command_server.cpp index 95fd3178c..34868b576 100644 --- a/src/daemon/command_server.cpp +++ b/src/daemon/command_server.cpp @@ -40,11 +40,11 @@ namespace p = std::placeholders; t_command_server::t_command_server( uint32_t ip , uint16_t port - , const std::string &user_agent + , const boost::optional& login , bool is_rpc , cryptonote::core_rpc_server* rpc_server ) - : m_parser(ip, port, user_agent, is_rpc, rpc_server) + : m_parser(ip, port, login, is_rpc, rpc_server) , m_command_lookup() , m_is_rpc(is_rpc) { diff --git a/src/daemon/command_server.h b/src/daemon/command_server.h index fb1702aae..9ecf06b9d 100644 --- a/src/daemon/command_server.h +++ b/src/daemon/command_server.h @@ -39,6 +39,8 @@ Passing RPC commands: #pragma once +#include +#include "common/common_fwd.h" #include "console_handler.h" #include "daemon/command_parser_executor.h" @@ -54,7 +56,7 @@ public: t_command_server( uint32_t ip , uint16_t port - , const std::string &user_agent + , const boost::optional& login , bool is_rpc = true , cryptonote::core_rpc_server* rpc_server = NULL ); diff --git a/src/daemon/daemon.cpp b/src/daemon/daemon.cpp index 287c30cb4..e40136a71 100644 --- a/src/daemon/daemon.cpp +++ b/src/daemon/daemon.cpp @@ -33,6 +33,7 @@ #include "misc_log_ex.h" #include "daemon/daemon.h" +#include "common/password.h" #include "common/util.h" #include "daemon/core.h" #include "daemon/p2p.h" @@ -127,7 +128,8 @@ bool t_daemon::run(bool interactive) if (interactive) { - rpc_commands = new daemonize::t_command_server(0, 0, "", false, mp_internals->rpc.get_server()); + // The first three variables are not used when the fourth is false + rpc_commands = new daemonize::t_command_server(0, 0, boost::none, false, mp_internals->rpc.get_server()); rpc_commands->start_handling(std::bind(&daemonize::t_daemon::stop_p2p, this)); } diff --git a/src/daemon/main.cpp b/src/daemon/main.cpp index e08065ccd..2fa48cd92 100644 --- a/src/daemon/main.cpp +++ b/src/daemon/main.cpp @@ -30,6 +30,7 @@ #include "common/command_line.h" #include "common/scoped_message_writer.h" +#include "common/password.h" #include "common/util.h" #include "cryptonote_core/cryptonote_core.h" #include "cryptonote_core/miner.h" @@ -40,6 +41,7 @@ #include "misc_log_ex.h" #include "p2p/net_node.h" #include "rpc/core_rpc_server.h" +#include "rpc/rpc_args.h" #include "daemon/command_line_args.h" #include "blockchain_db/db_types.h" @@ -220,13 +222,13 @@ int main(int argc, char const * argv[]) if (command.size()) { - auto rpc_ip_str = command_line::get_arg(vm, cryptonote::core_rpc_server::arg_rpc_bind_ip); + const cryptonote::rpc_args::descriptors arg{}; + auto rpc_ip_str = command_line::get_arg(vm, arg.rpc_bind_ip); auto rpc_port_str = command_line::get_arg(vm, cryptonote::core_rpc_server::arg_rpc_bind_port); if (testnet_mode) { rpc_port_str = command_line::get_arg(vm, cryptonote::core_rpc_server::arg_testnet_rpc_bind_port); } - auto user_agent = command_line::get_arg(vm, cryptonote::core_rpc_server::arg_user_agent); uint32_t rpc_ip; uint16_t rpc_port; @@ -241,7 +243,20 @@ int main(int argc, char const * argv[]) return 1; } - daemonize::t_command_server rpc_commands{rpc_ip, rpc_port, user_agent}; + boost::optional login{}; + if (command_line::has_arg(vm, arg.rpc_login)) + { + login = tools::login::parse( + command_line::get_arg(vm, arg.rpc_login), false, "Daemon client password" + ); + if (!login) + { + std::cerr << "Failed to obtain password" << std::endl; + return 1; + } + } + + daemonize::t_command_server rpc_commands{rpc_ip, rpc_port, std::move(login)}; if (rpc_commands.process_command_vec(command)) { return 0; diff --git a/src/daemon/rpc_command_executor.cpp b/src/daemon/rpc_command_executor.cpp index f7d85b5ef..3ea160c55 100644 --- a/src/daemon/rpc_command_executor.cpp +++ b/src/daemon/rpc_command_executor.cpp @@ -29,6 +29,7 @@ // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include "string_tools.h" +#include "common/password.h" #include "common/scoped_message_writer.h" #include "daemon/rpc_command_executor.h" #include "rpc/core_rpc_server_commands_defs.h" @@ -95,7 +96,7 @@ namespace { t_rpc_command_executor::t_rpc_command_executor( uint32_t ip , uint16_t port - , const std::string &user_agent + , const boost::optional& login , bool is_rpc , cryptonote::core_rpc_server* rpc_server ) @@ -103,7 +104,10 @@ t_rpc_command_executor::t_rpc_command_executor( { if (is_rpc) { - m_rpc_client = new tools::t_rpc_client(ip, port); + boost::optional http_login{}; + if (login) + http_login.emplace(login->username, login->password.password()); + m_rpc_client = new tools::t_rpc_client(ip, port, std::move(http_login)); } else { diff --git a/src/daemon/rpc_command_executor.h b/src/daemon/rpc_command_executor.h index afcd99d32..4691844fa 100644 --- a/src/daemon/rpc_command_executor.h +++ b/src/daemon/rpc_command_executor.h @@ -38,6 +38,9 @@ #pragma once +#include + +#include "common/common_fwd.h" #include "common/rpc_client.h" #include "misc_log_ex.h" #include "cryptonote_core/cryptonote_core.h" @@ -60,7 +63,7 @@ public: t_rpc_command_executor( uint32_t ip , uint16_t port - , const std::string &user_agent + , const boost::optional& user , bool is_rpc = true , cryptonote::core_rpc_server* rpc_server = NULL ); diff --git a/src/rpc/CMakeLists.txt b/src/rpc/CMakeLists.txt index 6df93cde1..1f9c40209 100644 --- a/src/rpc/CMakeLists.txt +++ b/src/rpc/CMakeLists.txt @@ -27,9 +27,11 @@ # THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. set(rpc_sources - core_rpc_server.cpp) + core_rpc_server.cpp + rpc_args.cpp) -set(rpc_headers) +set(rpc_headers + rpc_args.h) set(rpc_private_headers core_rpc_server.h @@ -44,6 +46,7 @@ monero_add_library(rpc ${rpc_private_headers}) target_link_libraries(rpc PUBLIC + common cryptonote_core cryptonote_protocol epee diff --git a/src/rpc/core_rpc_server.cpp b/src/rpc/core_rpc_server.cpp index b2e8e6716..2b6b15403 100644 --- a/src/rpc/core_rpc_server.cpp +++ b/src/rpc/core_rpc_server.cpp @@ -38,6 +38,7 @@ using namespace epee; #include "cryptonote_core/cryptonote_basic_impl.h" #include "misc_language.h" #include "crypto/hash.h" +#include "rpc/rpc_args.h" #include "core_rpc_server_error_codes.h" #define MAX_RESTRICTED_FAKE_OUTS_COUNT 40 @@ -49,11 +50,10 @@ namespace cryptonote //----------------------------------------------------------------------------------- void core_rpc_server::init_options(boost::program_options::options_description& desc) { - command_line::add_arg(desc, arg_rpc_bind_ip); command_line::add_arg(desc, arg_rpc_bind_port); command_line::add_arg(desc, arg_testnet_rpc_bind_port); command_line::add_arg(desc, arg_restricted_rpc); - command_line::add_arg(desc, arg_user_agent); + cryptonote::rpc_args::init_options(desc); } //------------------------------------------------------------------------------------------------------------------------------ core_rpc_server::core_rpc_server( @@ -64,29 +64,29 @@ namespace cryptonote , m_p2p(p2p) {} //------------------------------------------------------------------------------------------------------------------------------ - bool core_rpc_server::handle_command_line( + bool core_rpc_server::init( const boost::program_options::variables_map& vm ) { + m_testnet = command_line::get_arg(vm, command_line::arg_testnet_on); + m_net_server.set_threads_prefix("RPC"); + auto p2p_bind_arg = m_testnet ? arg_testnet_rpc_bind_port : arg_rpc_bind_port; - m_bind_ip = command_line::get_arg(vm, arg_rpc_bind_ip); - m_port = command_line::get_arg(vm, p2p_bind_arg); + auto rpc_config = cryptonote::rpc_args::process(vm); + if (!rpc_config) + return false; + m_restricted = command_line::get_arg(vm, arg_restricted_rpc); - return true; - } - //------------------------------------------------------------------------------------------------------------------------------ - bool core_rpc_server::init( - const boost::program_options::variables_map& vm - ) - { - m_testnet = command_line::get_arg(vm, command_line::arg_testnet_on); - std::string m_user_agent = command_line::get_arg(vm, command_line::arg_user_agent); - m_net_server.set_threads_prefix("RPC"); - bool r = handle_command_line(vm); - CHECK_AND_ASSERT_MES(r, false, "Failed to process command line in core_rpc_server"); - return epee::http_server_impl_base::init(m_port, m_bind_ip, m_user_agent); + boost::optional http_login{}; + std::string port = command_line::get_arg(vm, p2p_bind_arg); + if (rpc_config->login) + http_login.emplace(std::move(rpc_config->login->username), std::move(rpc_config->login->password).password()); + + return epee::http_server_impl_base::init( + std::move(port), std::move(rpc_config->bind_ip), std::move(http_login) + ); } //------------------------------------------------------------------------------------------------------------------------------ bool core_rpc_server::check_core_busy() @@ -1446,12 +1446,6 @@ namespace cryptonote } //------------------------------------------------------------------------------------------------------------------------------ - const command_line::arg_descriptor core_rpc_server::arg_rpc_bind_ip = { - "rpc-bind-ip" - , "IP for RPC server" - , "127.0.0.1" - }; - const command_line::arg_descriptor core_rpc_server::arg_rpc_bind_port = { "rpc-bind-port" , "Port for RPC server" @@ -1469,11 +1463,4 @@ namespace cryptonote , "Restrict RPC to view only commands" , false }; - - const command_line::arg_descriptor core_rpc_server::arg_user_agent = { - "user-agent" - , "Restrict RPC to clients using this user agent" - , "" - }; - } // namespace cryptonote diff --git a/src/rpc/core_rpc_server.h b/src/rpc/core_rpc_server.h index 767bcc715..0421511a2 100644 --- a/src/rpc/core_rpc_server.h +++ b/src/rpc/core_rpc_server.h @@ -52,11 +52,9 @@ namespace cryptonote { public: - static const command_line::arg_descriptor arg_rpc_bind_ip; static const command_line::arg_descriptor arg_rpc_bind_port; static const command_line::arg_descriptor arg_testnet_rpc_bind_port; static const command_line::arg_descriptor arg_restricted_rpc; - static const command_line::arg_descriptor arg_user_agent; typedef epee::net_utils::connection_context_base connection_context; @@ -175,10 +173,6 @@ namespace cryptonote //----------------------- private: - - bool handle_command_line( - const boost::program_options::variables_map& vm - ); bool check_core_busy(); bool check_core_ready(); @@ -188,8 +182,6 @@ private: core& m_core; nodetool::node_server >& m_p2p; - std::string m_port; - std::string m_bind_ip; bool m_testnet; bool m_restricted; }; diff --git a/src/rpc/rpc_args.cpp b/src/rpc/rpc_args.cpp new file mode 100644 index 000000000..79f3f7e12 --- /dev/null +++ b/src/rpc/rpc_args.cpp @@ -0,0 +1,96 @@ +// Copyright (c) 2014-2017, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, this list +// of conditions and the following disclaimer in the documentation and/or other +// materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its contributors may be +// used to endorse or promote products derived from this software without specific +// prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +#include "rpc_args.h" + +#include +#include "common/command_line.h" +#include "common/i18n.h" + +namespace cryptonote +{ + rpc_args::descriptors::descriptors() + : rpc_bind_ip({"rpc-bind-ip", rpc_args::tr("Specify ip to bind rpc server"), "127.0.0.1"}) + , rpc_login({"rpc-login", rpc_args::tr("Specify username[:password] required for RPC server"), "", true}) + , confirm_external_bind({"confirm-external-bind", rpc_args::tr("Confirm rcp-bind-ip value is NOT a loopback (local) IP")}) + {} + + const char* rpc_args::tr(const char* str) { return i18n_translate(str, "cryptonote::rpc_args"); } + + void rpc_args::init_options(boost::program_options::options_description& desc) + { + const descriptors arg{}; + command_line::add_arg(desc, arg.rpc_bind_ip); + command_line::add_arg(desc, arg.rpc_login); + command_line::add_arg(desc, arg.confirm_external_bind); + } + + boost::optional rpc_args::process(const boost::program_options::variables_map& vm) + { + const descriptors arg{}; + rpc_args config{}; + + config.bind_ip = command_line::get_arg(vm, arg.rpc_bind_ip); + if (!config.bind_ip.empty()) + { + // always parse IP here for error consistency + boost::system::error_code ec{}; + const auto parsed_ip = boost::asio::ip::address::from_string(config.bind_ip, ec); + if (ec) + { + LOG_ERROR(tr("Invalid IP address given for --") << arg.rpc_bind_ip.name); + return boost::none; + } + + if (!parsed_ip.is_loopback() && !command_line::get_arg(vm, arg.confirm_external_bind)) + { + LOG_ERROR( + "--" << arg.rpc_bind_ip.name << + tr(" permits inbound unencrypted external connections. Consider SSH tunnel or SSL proxy instead. Override with --") << + arg.confirm_external_bind.name + ); + return boost::none; + } + } + + if (command_line::has_arg(vm, arg.rpc_login)) + { + config.login = tools::login::parse(command_line::get_arg(vm, arg.rpc_login), true, "RPC server password"); + if (!config.login) + return boost::none; + + if (config.login->username.empty()) + { + LOG_ERROR(tr("Username specified with --") << arg.rpc_login.name << tr(" cannot be empty")); + return boost::none; + } + } + + return {std::move(config)}; + } +} diff --git a/src/rpc/rpc_args.h b/src/rpc/rpc_args.h new file mode 100644 index 000000000..d6e7bab07 --- /dev/null +++ b/src/rpc/rpc_args.h @@ -0,0 +1,67 @@ +// Copyright (c) 2014-2017, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, this list +// of conditions and the following disclaimer in the documentation and/or other +// materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its contributors may be +// used to endorse or promote products derived from this software without specific +// prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +#pragma once + +#include +#include +#include +#include + +#include "common/command_line.h" +#include "common/password.h" + +namespace cryptonote +{ + //! Processes command line arguments related to server-side RPC + struct rpc_args + { + // non-static construction prevents initialization order issues + struct descriptors + { + descriptors(); + descriptors(const descriptors&) = delete; + descriptors(descriptors&&) = delete; + descriptors& operator=(const descriptors&) = delete; + descriptors& operator=(descriptors&&) = delete; + + const command_line::arg_descriptor rpc_bind_ip; + const command_line::arg_descriptor rpc_login; + const command_line::arg_descriptor confirm_external_bind; + }; + + static const char* tr(const char* str); + static void init_options(boost::program_options::options_description& desc); + + //! \return Arguments specified by user, or `boost::none` if error + static boost::optional process(const boost::program_options::variables_map& vm); + + std::string bind_ip; + boost::optional login; // currently `boost::none` if unspecified by user + }; +} diff --git a/src/simplewallet/simplewallet.cpp b/src/simplewallet/simplewallet.cpp index a8f1d177f..7ffce6798 100644 --- a/src/simplewallet/simplewallet.cpp +++ b/src/simplewallet/simplewallet.cpp @@ -1192,7 +1192,7 @@ bool simple_wallet::init(const boost::program_options::variables_map& vm) } catch (const std::exception &e) { } - m_http_client.set_server(m_wallet->get_daemon_address()); + m_http_client.set_server(m_wallet->get_daemon_address(), m_wallet->get_daemon_login()); m_wallet->callback(this); return true; } diff --git a/src/simplewallet/simplewallet.h b/src/simplewallet/simplewallet.h index ce0a24be7..b101f3e0b 100644 --- a/src/simplewallet/simplewallet.h +++ b/src/simplewallet/simplewallet.h @@ -44,7 +44,7 @@ #include "cryptonote_core/cryptonote_basic_impl.h" #include "wallet/wallet2.h" #include "console_handler.h" -#include "wallet/password_container.h" +#include "common/password.h" #include "crypto/crypto.h" // for definition of crypto::secret_key #undef MONERO_DEFAULT_LOG_CATEGORY diff --git a/src/wallet/CMakeLists.txt b/src/wallet/CMakeLists.txt index 922464a3c..8626001ce 100644 --- a/src/wallet/CMakeLists.txt +++ b/src/wallet/CMakeLists.txt @@ -31,7 +31,6 @@ set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) set(wallet_sources - password_container.cpp wallet2.cpp wallet_args.cpp node_rpc_proxy.cpp @@ -49,7 +48,6 @@ set(wallet_api_headers set(wallet_private_headers - password_container.h wallet2.h wallet_args.h wallet_errors.h @@ -74,6 +72,7 @@ monero_add_library(wallet ${wallet_private_headers}) target_link_libraries(wallet PUBLIC + common cryptonote_core mnemonics p2p diff --git a/src/wallet/api/wallet.cpp b/src/wallet/api/wallet.cpp index 9e40d2e02..325f8522e 100644 --- a/src/wallet/api/wallet.cpp +++ b/src/wallet/api/wallet.cpp @@ -1364,7 +1364,7 @@ bool WalletImpl::isNewWallet() const bool WalletImpl::doInit(const string &daemon_address, uint64_t upper_transaction_size_limit) { - if (!m_wallet->init(daemon_address, upper_transaction_size_limit)) + if (!m_wallet->init(daemon_address, boost::none, upper_transaction_size_limit)) return false; // in case new wallet, this will force fast-refresh (pulling hashes instead of blocks) diff --git a/src/wallet/api/wallet_manager.cpp b/src/wallet/api/wallet_manager.cpp index c761cc6d2..4104e7884 100644 --- a/src/wallet/api/wallet_manager.cpp +++ b/src/wallet/api/wallet_manager.cpp @@ -48,7 +48,7 @@ namespace { bool connect_and_invoke(const std::string& address, const std::string& path, const Request& request, Response& response) { epee::net_utils::http::http_simple_client client{}; - return client.set_server(address) && epee::net_utils::invoke_http_json(path, request, response, client); + return client.set_server(address, boost::none) && epee::net_utils::invoke_http_json(path, request, response, client); } } diff --git a/src/wallet/password_container.cpp b/src/wallet/password_container.cpp deleted file mode 100644 index 832b93a1a..000000000 --- a/src/wallet/password_container.cpp +++ /dev/null @@ -1,248 +0,0 @@ -// Copyright (c) 2014-2016, The Monero Project -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, are -// permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of -// conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list -// of conditions and the following disclaimer in the documentation and/or other -// materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be -// used to endorse or promote products derived from this software without specific -// prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL -// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF -// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers - -#include "password_container.h" - -#include -#include -#include - -#if defined(_WIN32) -#include -#include -#else -#include -#include -#endif - -namespace -{ -#if defined(_WIN32) - bool is_cin_tty() noexcept - { - return 0 != _isatty(_fileno(stdin)); - } - - bool read_from_tty(std::string& pass) - { - static constexpr const char BACKSPACE = 8; - - HANDLE h_cin = ::GetStdHandle(STD_INPUT_HANDLE); - - DWORD mode_old; - ::GetConsoleMode(h_cin, &mode_old); - DWORD mode_new = mode_old & ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT); - ::SetConsoleMode(h_cin, mode_new); - - bool r = true; - pass.reserve(tools::password_container::max_password_size); - while (pass.size() < tools::password_container::max_password_size) - { - DWORD read; - char ch; - r = (TRUE == ::ReadConsoleA(h_cin, &ch, 1, &read, NULL)); - r &= (1 == read); - if (!r) - { - break; - } - else if (ch == '\n' || ch == '\r') - { - std::cout << std::endl; - break; - } - else if (ch == BACKSPACE) - { - if (!pass.empty()) - { - pass.back() = '\0'; - pass.resize(pass.size() - 1); - std::cout << "\b \b"; - } - } - else - { - pass.push_back(ch); - std::cout << '*'; - } - } - - ::SetConsoleMode(h_cin, mode_old); - - return r; - } - -#else // end WIN32 - - bool is_cin_tty() noexcept - { - return 0 != isatty(fileno(stdin)); - } - - int getch() noexcept - { - struct termios tty_old; - tcgetattr(STDIN_FILENO, &tty_old); - - struct termios tty_new; - tty_new = tty_old; - tty_new.c_lflag &= ~(ICANON | ECHO); - tcsetattr(STDIN_FILENO, TCSANOW, &tty_new); - - int ch = getchar(); - - tcsetattr(STDIN_FILENO, TCSANOW, &tty_old); - - return ch; - } - - bool read_from_tty(std::string& aPass) - { - static constexpr const char BACKSPACE = 127; - - aPass.reserve(tools::password_container::max_password_size); - while (aPass.size() < tools::password_container::max_password_size) - { - int ch = getch(); - if (EOF == ch) - { - return false; - } - else if (ch == '\n' || ch == '\r') - { - std::cout << std::endl; - break; - } - else if (ch == BACKSPACE) - { - if (!aPass.empty()) - { - aPass.back() = '\0'; - aPass.resize(aPass.size() - 1); - std::cout << "\b \b"; - } - } - else - { - aPass.push_back(ch); - std::cout << '*'; - } - } - - return true; - } - -#endif // end !WIN32 - - void clear(std::string& pass) noexcept - { - //! TODO Call a memory wipe function that hopefully is not optimized out - pass.replace(0, pass.capacity(), pass.capacity(), '\0'); - pass.clear(); - } - - bool read_from_tty(const bool verify, const char *message, std::string& pass1, std::string& pass2) - { - while (true) - { - if (message) - std::cout << message <<": "; - if (!read_from_tty(pass1)) - return false; - if (verify) - { - std::cout << "Confirm Password: "; - if (!read_from_tty(pass2)) - return false; - if(pass1!=pass2) - { - std::cout << "Passwords do not match! Please try again." << std::endl; - clear(pass1); - clear(pass2); - } - else //new password matches - return true; - } - else - return true; - //No need to verify password entered at this point in the code - } - - return false; - } - - bool read_from_file(std::string& pass) - { - pass.reserve(tools::password_container::max_password_size); - for (size_t i = 0; i < tools::password_container::max_password_size; ++i) - { - char ch = static_cast(std::cin.get()); - if (std::cin.eof() || ch == '\n' || ch == '\r') - { - break; - } - else if (std::cin.fail()) - { - return false; - } - else - { - pass.push_back(ch); - } - } - return true; - } - -} // anonymous namespace - -namespace tools -{ - // deleted via private member - password_container::password_container() noexcept : m_password() {} - password_container::password_container(std::string&& password) noexcept - : m_password(std::move(password)) - { - } - - password_container::~password_container() noexcept - { - clear(m_password); - } - - boost::optional password_container::prompt(const bool verify, const char *message) - { - password_container pass1{}; - password_container pass2{}; - if (is_cin_tty() ? read_from_tty(verify, message, pass1.m_password, pass2.m_password) : read_from_file(pass1.m_password)) - return {std::move(pass1)}; - - return boost::none; - } -} diff --git a/src/wallet/password_container.h b/src/wallet/password_container.h deleted file mode 100644 index 9c6faf9c8..000000000 --- a/src/wallet/password_container.h +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) 2014-2016, The Monero Project -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, are -// permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of -// conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list -// of conditions and the following disclaimer in the documentation and/or other -// materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be -// used to endorse or promote products derived from this software without specific -// prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL -// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF -// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers - -#pragma once - -#include -#include - -namespace tools -{ - class password_container - { - public: - static constexpr const size_t max_password_size = 1024; - - //! Empty password - password_container() noexcept; - - //! `password` is used as password - password_container(std::string&& password) noexcept; - - //! \return A password from stdin TTY prompt or `std::cin` pipe. - static boost::optional prompt(bool verify, const char *mesage = "Password"); - - password_container(const password_container&) = delete; - password_container(password_container&& rhs) = default; - - //! Wipes internal password - ~password_container() noexcept; - - password_container& operator=(const password_container&) = delete; - password_container& operator=(password_container&&) = default; - - const std::string& password() const noexcept { return m_password; } - - private: - //! TODO Custom allocator that locks to RAM? - std::string m_password; - }; -} diff --git a/src/wallet/wallet2.cpp b/src/wallet/wallet2.cpp index 9bdfc7b04..0c6d23cc4 100644 --- a/src/wallet/wallet2.cpp +++ b/src/wallet/wallet2.cpp @@ -108,6 +108,7 @@ struct options { const command_line::arg_descriptor password = {"password", tools::wallet2::tr("Wallet password"), "", true}; const command_line::arg_descriptor password_file = {"password-file", tools::wallet2::tr("Wallet password file"), "", true}; const command_line::arg_descriptor daemon_port = {"daemon-port", tools::wallet2::tr("Use daemon instance at port instead of 18081"), 0}; + const command_line::arg_descriptor daemon_login = {"daemon-login", tools::wallet2::tr("Specify username[:password] for daemon RPC client"), "", true}; const command_line::arg_descriptor testnet = {"testnet", tools::wallet2::tr("For testnet. Daemon must also be launched with --testnet flag"), false}; const command_line::arg_descriptor restricted = {"restricted-rpc", tools::wallet2::tr("Restricts to view-only commands"), false}; }; @@ -152,6 +153,18 @@ std::unique_ptr make_basic(const boost::program_options::variabl return nullptr; } + boost::optional login{}; + if (command_line::has_arg(vm, opts.daemon_login)) + { + auto parsed = tools::login::parse( + command_line::get_arg(vm, opts.daemon_login), false, "Daemon client password" + ); + if (!parsed) + return nullptr; + + login.emplace(std::move(parsed->username), std::move(parsed->password).password()); + } + if (daemon_host.empty()) daemon_host = "localhost"; @@ -164,7 +177,7 @@ std::unique_ptr make_basic(const boost::program_options::variabl daemon_address = std::string("http://") + daemon_host + ":" + std::to_string(daemon_port); std::unique_ptr wallet(new tools::wallet2(testnet, restricted)); - wallet->init(std::move(daemon_address)); + wallet->init(std::move(daemon_address), std::move(login)); return wallet; } @@ -434,6 +447,7 @@ void wallet2::init_options(boost::program_options::options_description& desc_par command_line::add_arg(desc_params, opts.password); command_line::add_arg(desc_params, opts.password_file); command_line::add_arg(desc_params, opts.daemon_port); + command_line::add_arg(desc_params, opts.daemon_login); command_line::add_arg(desc_params, opts.testnet); command_line::add_arg(desc_params, opts.restricted); } @@ -485,11 +499,12 @@ std::pair, password_container> wallet2::make_new(const } //---------------------------------------------------------------------------------------------------- -bool wallet2::init(std::string daemon_address, uint64_t upper_transaction_size_limit) +bool wallet2::init(std::string daemon_address, boost::optional daemon_login, uint64_t upper_transaction_size_limit) { m_upper_transaction_size_limit = upper_transaction_size_limit; m_daemon_address = std::move(daemon_address); - return m_http_client.set_server(get_daemon_address()); + m_daemon_login = std::move(daemon_login); + return m_http_client.set_server(get_daemon_address(), get_daemon_login()); } //---------------------------------------------------------------------------------------------------- bool wallet2::is_deterministic() const diff --git a/src/wallet/wallet2.h b/src/wallet/wallet2.h index 567292d30..9842ddf32 100644 --- a/src/wallet/wallet2.h +++ b/src/wallet/wallet2.h @@ -53,7 +53,7 @@ #include "ringct/rctOps.h" #include "wallet_errors.h" -#include "password_container.h" +#include "common/password.h" #include "node_rpc_proxy.h" #include @@ -343,7 +343,8 @@ namespace tools // into account the current median block size rather than // the minimum block size. bool deinit(); - bool init(std::string daemon_address = "http://localhost:8080", uint64_t upper_transaction_size_limit = 0); + bool init(std::string daemon_address = "http://localhost:8080", + boost::optional daemon_login = boost::none, uint64_t upper_transaction_size_limit = 0); void stop() { m_run.store(false, std::memory_order_relaxed); } @@ -527,6 +528,7 @@ namespace tools std::string get_wallet_file() const; std::string get_keys_file() const; std::string get_daemon_address() const; + const boost::optional& get_daemon_login() const { return m_daemon_login; } uint64_t get_daemon_blockchain_height(std::string& err); uint64_t get_daemon_blockchain_target_height(std::string& err); /*! @@ -619,6 +621,7 @@ namespace tools crypto::public_key get_tx_pub_key_from_received_outs(const tools::wallet2::transfer_details &td) const; cryptonote::account_base m_account; + boost::optional m_daemon_login; std::string m_daemon_address; std::string m_wallet_file; std::string m_keys_file; diff --git a/src/wallet/wallet_rpc_server.cpp b/src/wallet/wallet_rpc_server.cpp index 22f5f8bb6..76520c185 100644 --- a/src/wallet/wallet_rpc_server.cpp +++ b/src/wallet/wallet_rpc_server.cpp @@ -45,6 +45,7 @@ using namespace epee; #include "string_coding.h" #include "string_tools.h" #include "crypto/hash.h" +#include "rpc/rpc_args.h" #undef MONERO_DEFAULT_LOG_CATEGORY #define MONERO_DEFAULT_LOG_CATEGORY "wallet.rpc" @@ -52,10 +53,7 @@ using namespace epee; namespace { const command_line::arg_descriptor arg_rpc_bind_port = {"rpc-bind-port", "Sets bind port for server"}; - const command_line::arg_descriptor arg_rpc_bind_ip = {"rpc-bind-ip", "Specify ip to bind rpc server", "127.0.0.1"}; - const command_line::arg_descriptor arg_rpc_login = {"rpc-login", "Specify username[:password] required for RPC connection"}; - const command_line::arg_descriptor arg_disable_rpc_login = {"disable-rpc-login", "Disable HTTP authentication for RPC"}; - const command_line::arg_descriptor arg_confirm_external_bind = {"confirm-external-bind", "Confirm rcp-bind-ip value is NOT a loopback (local) IP"}; + const command_line::arg_descriptor arg_disable_rpc_login = {"disable-rpc-login", "Disable HTTP authentication for RPC connections served by this process"}; constexpr const char default_rpc_username[] = "monero"; } @@ -107,75 +105,41 @@ namespace tools //------------------------------------------------------------------------------------------------------------------------------ bool wallet_rpc_server::init(const boost::program_options::variables_map& vm) { - std::string bind_ip = command_line::get_arg(vm, arg_rpc_bind_ip); - if (!bind_ip.empty()) - { - // always parse IP here for error consistency - boost::system::error_code ec{}; - const auto parsed_ip = boost::asio::ip::address::from_string(bind_ip, ec); - if (ec) - { - LOG_ERROR(tr("Invalid IP address given for rpc-bind-ip argument")); - return false; - } - - if (!parsed_ip.is_loopback() && !command_line::get_arg(vm, arg_confirm_external_bind)) - { - LOG_ERROR( - tr("The rpc-bind-ip value is listening for unencrypted external connections. Consider SSH tunnel or SSL proxy instead. Override with --confirm-external-bind") - ); - return false; - } - } - - epee::net_utils::http::login login{}; + auto rpc_config = cryptonote::rpc_args::process(vm); + if (!rpc_config) + return false; + boost::optional http_login{}; + std::string bind_port = command_line::get_arg(vm, arg_rpc_bind_port); const bool disable_auth = command_line::get_arg(vm, arg_disable_rpc_login); - const std::string user_pass = command_line::get_arg(vm, arg_rpc_login); - const std::string bind_port = command_line::get_arg(vm, arg_rpc_bind_port); if (disable_auth) { - if (!user_pass.empty()) + if (rpc_config->login) { - LOG_ERROR(tr("Cannot specify --") << arg_disable_rpc_login.name << tr(" and --") << arg_rpc_login.name); + const cryptonote::rpc_args::descriptors arg{}; + LOG_ERROR(tr("Cannot specify --") << arg_disable_rpc_login.name << tr(" and --") << arg.rpc_login.name); return false; } } else // auth enabled { - if (user_pass.empty()) + if (!rpc_config->login) { - login.username = default_rpc_username; - std::array rand_128bit{{}}; crypto::rand(rand_128bit.size(), rand_128bit.data()); - login.password = string_encoding::base64_encode(rand_128bit.data(), rand_128bit.size()); + http_login.emplace( + default_rpc_username, + string_encoding::base64_encode(rand_128bit.data(), rand_128bit.size()) + ); } - else // user password + else { - const auto loc = user_pass.find(':'); - login.username = user_pass.substr(0, loc); - if (loc != std::string::npos) - { - login.password = user_pass.substr(loc + 1); - } - else - { - login.password = tools::password_container::prompt(true, "RPC password").value_or( - tools::password_container{} - ).password(); - } - - if (login.username.empty() || login.password.empty()) - { - LOG_ERROR(tr("Blank username or password not permitted for RPC authenticaion")); - return false; - } + http_login.emplace( + std::move(rpc_config->login->username), std::move(rpc_config->login->password).password() + ); } - - assert(!login.username.empty()); - assert(!login.password.empty()); + assert(bool(http_login)); std::string temp = "monero-wallet-rpc." + bind_port + ".login"; const auto cookie = tools::create_private_file(temp); @@ -186,9 +150,9 @@ namespace tools } rpc_login_filename.swap(temp); // nothrow guarantee destructor cleanup temp = rpc_login_filename; - std::fputs(login.username.c_str(), cookie.get()); + std::fputs(http_login->username.c_str(), cookie.get()); std::fputc(':', cookie.get()); - std::fputs(login.password.c_str(), cookie.get()); + std::fputs(http_login->password.c_str(), cookie.get()); std::fflush(cookie.get()); if (std::ferror(cookie.get())) { @@ -200,7 +164,7 @@ namespace tools m_net_server.set_threads_prefix("RPC"); return epee::http_server_impl_base::init( - std::move(bind_port), std::move(bind_ip), std::string{}, boost::make_optional(!disable_auth, std::move(login)) + std::move(bind_port), std::move(rpc_config->bind_ip), std::move(http_login) ); } //------------------------------------------------------------------------------------------------------------------------------ @@ -1410,14 +1374,13 @@ int main(int argc, char** argv) { po::options_description desc_params(wallet_args::tr("Wallet options")); tools::wallet2::init_options(desc_params); - command_line::add_arg(desc_params, arg_rpc_bind_ip); command_line::add_arg(desc_params, arg_rpc_bind_port); - command_line::add_arg(desc_params, arg_rpc_login); command_line::add_arg(desc_params, arg_disable_rpc_login); - command_line::add_arg(desc_params, arg_confirm_external_bind); + cryptonote::rpc_args::init_options(desc_params); command_line::add_arg(desc_params, arg_wallet_file); command_line::add_arg(desc_params, arg_from_json); + const auto vm = wallet_args::main( argc, argv, "monero-wallet-rpc [--wallet-file=|--generate-from-json=] [--rpc-bind-port=]", diff --git a/tests/functional_tests/transactions_flow_test.cpp b/tests/functional_tests/transactions_flow_test.cpp index 5666f49bf..8e7e494c9 100644 --- a/tests/functional_tests/transactions_flow_test.cpp +++ b/tests/functional_tests/transactions_flow_test.cpp @@ -159,7 +159,7 @@ bool transactions_flow_test(std::string& working_folder, epee::net_utils::http::http_simple_client http_client; COMMAND_RPC_STOP_MINING::request daemon1_req = AUTO_VAL_INIT(daemon1_req); COMMAND_RPC_STOP_MINING::response daemon1_rsp = AUTO_VAL_INIT(daemon1_rsp); - bool r = http_client.set_server(daemon_addr_a) && net_utils::invoke_http_json("/stop_mine", daemon1_req, daemon1_rsp, http_client, std::chrono::seconds(10)); + bool r = http_client.set_server(daemon_addr_a, boost::none) && net_utils::invoke_http_json("/stop_mine", daemon1_req, daemon1_rsp, http_client, std::chrono::seconds(10)); CHECK_AND_ASSERT_MES(r, false, "failed to stop mining"); COMMAND_RPC_START_MINING::request daemon_req = AUTO_VAL_INIT(daemon_req); diff --git a/tests/unit_tests/CMakeLists.txt b/tests/unit_tests/CMakeLists.txt index 08c8213e4..b36766803 100644 --- a/tests/unit_tests/CMakeLists.txt +++ b/tests/unit_tests/CMakeLists.txt @@ -42,7 +42,7 @@ set(unit_tests_sources epee_levin_protocol_handler_async.cpp fee.cpp get_xtype_from_string.cpp - http_auth.cpp + http.cpp main.cpp mnemonics.cpp mul_div.cpp diff --git a/tests/unit_tests/http.cpp b/tests/unit_tests/http.cpp new file mode 100644 index 000000000..3513fa327 --- /dev/null +++ b/tests/unit_tests/http.cpp @@ -0,0 +1,738 @@ +// Copyright (c) 2014-2016, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, this list +// of conditions and the following disclaimer in the documentation and/or other +// materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its contributors may be +// used to endorse or promote products derived from this software without specific +// prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include "gtest/gtest.h" +#include "net/http_auth.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "md5_l.h" +#include "string_tools.h" + +namespace { +namespace http = epee::net_utils::http; +using fields = std::unordered_map; +using auth_responses = std::vector; + +std::string quoted(std::string str) +{ + str.insert(str.begin(), '"'); + str.push_back('"'); + return str; +} + +void write_fields(std::string& out, const fields& args) +{ + namespace karma = boost::spirit::karma; + karma::generate( + std::back_inserter(out), + (karma::string << " = " << karma::string) % " , ", + args); +} + +std::string write_fields(const fields& args) +{ + std::string out{}; + write_fields(out, args); + return out; +} + +http::http_request_info make_request(const fields& args) +{ + std::string out{" DIGEST "}; + write_fields(out, args); + + http::http_request_info request{}; + request.m_http_method_str = "NOP"; + request.m_header_info.m_etc_fields.push_back( + std::make_pair(u8"authorization", std::move(out)) + ); + return request; +} + +http::http_response_info make_response(const auth_responses& choices) +{ + http::http_response_info response{}; + for (const auto& choice : choices) + { + std::string out{" DIGEST "}; + write_fields(out, choice); + + response.m_header_info.m_etc_fields.push_back( + std::make_pair(u8"WWW-authenticate", std::move(out)) + ); + } + return response; +} + +bool has_same_fields(const auth_responses& in) +{ + const std::vector check{u8"nonce", u8"qop", u8"realm", u8"stale"}; + + auto current = in.begin(); + const auto end = in.end(); + if (current == end) + return true; + + ++current; + for ( ; current != end; ++current ) + { + for (const auto& field : check) + { + const std::string& expected = in[0].at(field); + const std::string& actual = current->at(field); + EXPECT_EQ(expected, actual); + if (expected != actual) + return false; + } + } + return true; +} + +bool is_unauthorized(const http::http_response_info& response) +{ + EXPECT_EQ(401, response.m_response_code); + EXPECT_STREQ(u8"Unauthorized", response.m_response_comment.c_str()); + EXPECT_STREQ(u8"text/html", response.m_mime_tipe.c_str()); + return response.m_response_code == 401 && + response.m_response_comment == u8"Unauthorized" && + response.m_mime_tipe == u8"text/html"; +} + +fields parse_fields(const std::string& value) +{ + namespace qi = boost::spirit::qi; + + fields out{}; + const bool rc = qi::parse( + value.begin(), value.end(), + qi::lit(u8"Digest ") >> (( + +qi::ascii::alpha >> + qi::lit('=') >> ( + (qi::lit('"') >> +(qi::ascii::char_ - '"') >> qi::lit('"')) | + +(qi::ascii::graph - qi::ascii::char_(u8"()<>@,;:\\\"/[]?={}")) + ) + ) % ',' + ) >> qi::eoi, + out + ); + if (!rc) + throw std::runtime_error{"Bad field given in HTTP header"}; + + return out; +} + +auth_responses parse_response(const http::http_response_info& response) +{ + auth_responses result{}; + + const auto end = response.m_additional_fields.end(); + for (auto current = response.m_additional_fields.begin();; ++current) + { + current = std::find_if(current, end, [] (const std::pair& field) { + return boost::equals(u8"WWW-authenticate", field.first); + }); + + if (current == end) + return result; + + result.push_back(parse_fields(current->second)); + } + return result; +} + +std::string md5_hex(const std::string& in) +{ + md5::MD5_CTX ctx{}; + md5::MD5Init(std::addressof(ctx)); + md5::MD5Update( + std::addressof(ctx), + reinterpret_cast(in.data()), + in.size() + ); + + std::array digest{{}}; + md5::MD5Final(digest.data(), std::addressof(ctx)); + return epee::string_tools::pod_to_hex(digest); +} + +std::string get_a1(const http::login& user, const fields& src) +{ + const std::string& realm = src.at(u8"realm"); + return boost::join( + std::vector{user.username, realm, user.password}, u8":" + ); +} + +std::string get_a1(const http::login& user, const auth_responses& responses) +{ + return get_a1(user, responses.at(0)); +} + +std::string get_a1_sess(const http::login& user, const std::string& cnonce, const auth_responses& responses) +{ + const std::string& nonce = responses.at(0).at(u8"nonce"); + return boost::join( + std::vector{md5_hex(get_a1(user, responses)), nonce, cnonce}, u8":" + ); +} + +std::string get_a2(const std::string& uri) +{ + return boost::join(std::vector{"NOP", uri}, u8":"); +} + +std::string get_nc(std::uint32_t count) +{ + namespace karma = boost::spirit::karma; + std::string out; + karma::generate( + std::back_inserter(out), + karma::right_align(8, '0')[karma::uint_generator{}], + count + ); + + return out; +} +} + +TEST(HTTP_Server_Auth, NotRequired) +{ + http::http_server_auth auth{}; + EXPECT_FALSE(auth.get_response(http::http_request_info{})); +} + +TEST(HTTP_Server_Auth, MissingAuth) +{ + http::http_server_auth auth{{"foo", "bar"}}; + EXPECT_TRUE(bool(auth.get_response(http::http_request_info{}))); + { + http::http_request_info request{}; + request.m_header_info.m_etc_fields.push_back({"\xFF", "\xFF"}); + EXPECT_TRUE(bool(auth.get_response(request))); + } +} + +TEST(HTTP_Server_Auth, BadSyntax) +{ + http::http_server_auth auth{{"foo", "bar"}}; + EXPECT_TRUE(bool(auth.get_response(make_request({{u8"algorithm", "fo\xFF"}})))); + EXPECT_TRUE(bool(auth.get_response(make_request({{u8"cnonce", "\"000\xFF\""}})))); + EXPECT_TRUE(bool(auth.get_response(make_request({{u8"cnonce \xFF =", "\"000\xFF\""}})))); + EXPECT_TRUE(bool(auth.get_response(make_request({{u8" \xFF cnonce", "\"000\xFF\""}})))); +} + +TEST(HTTP_Server_Auth, MD5) +{ + http::login user{"foo", "bar"}; + http::http_server_auth auth{user}; + + const auto response = auth.get_response(make_request(fields{})); + ASSERT_TRUE(bool(response)); + EXPECT_TRUE(is_unauthorized(*response)); + + const auto fields = parse_response(*response); + ASSERT_LE(2u, fields.size()); + EXPECT_TRUE(has_same_fields(fields)); + + const std::string& nonce = fields[0].at(u8"nonce"); + EXPECT_EQ(24, nonce.size()); + + const std::string uri{"/some_foo_thing"}; + + const std::string a1 = get_a1(user, fields); + const std::string a2 = get_a2(uri); + + const std::string auth_code = md5_hex( + boost::join(std::vector{md5_hex(a1), nonce, md5_hex(a2)}, u8":") + ); + + const auto request = make_request({ + {u8"nonce", quoted(nonce)}, + {u8"realm", quoted(fields[0].at(u8"realm"))}, + {u8"response", quoted(auth_code)}, + {u8"uri", quoted(uri)}, + {u8"username", quoted(user.username)} + }); + + EXPECT_FALSE(bool(auth.get_response(request))); + + const auto response2 = auth.get_response(request); + ASSERT_TRUE(bool(response2)); + EXPECT_TRUE(is_unauthorized(*response2)); + + const auto fields2 = parse_response(*response2); + ASSERT_LE(2u, fields2.size()); + EXPECT_TRUE(has_same_fields(fields2)); + + EXPECT_NE(nonce, fields2[0].at(u8"nonce")); + EXPECT_STREQ(u8"true", fields2[0].at(u8"stale").c_str()); +} + +TEST(HTTP_Server_Auth, MD5_sess) +{ + constexpr const char cnonce[] = "not a good cnonce"; + + http::login user{"foo", "bar"}; + http::http_server_auth auth{user}; + + const auto response = auth.get_response(make_request(fields{})); + ASSERT_TRUE(bool(response)); + EXPECT_TRUE(is_unauthorized(*response)); + + const auto fields = parse_response(*response); + ASSERT_LE(2u, fields.size()); + EXPECT_TRUE(has_same_fields(fields)); + + const std::string& nonce = fields[0].at(u8"nonce"); + EXPECT_EQ(24, nonce.size()); + + const std::string uri{"/some_foo_thing"}; + + const std::string a1 = get_a1_sess(user, cnonce, fields); + const std::string a2 = get_a2(uri); + + const std::string auth_code = md5_hex( + boost::join(std::vector{md5_hex(a1), nonce, md5_hex(a2)}, u8":") + ); + + const auto request = make_request({ + {u8"algorithm", u8"md5-sess"}, + {u8"cnonce", quoted(cnonce)}, + {u8"nonce", quoted(nonce)}, + {u8"realm", quoted(fields[0].at(u8"realm"))}, + {u8"response", quoted(auth_code)}, + {u8"uri", quoted(uri)}, + {u8"username", quoted(user.username)} + }); + + EXPECT_FALSE(bool(auth.get_response(request))); + + const auto response2 = auth.get_response(request); + ASSERT_TRUE(bool(response2)); + EXPECT_TRUE(is_unauthorized(*response2)); + + const auto fields2 = parse_response(*response2); + ASSERT_LE(2u, fields2.size()); + EXPECT_TRUE(has_same_fields(fields2)); + + EXPECT_NE(nonce, fields2[0].at(u8"nonce")); + EXPECT_STREQ(u8"true", fields2[0].at(u8"stale").c_str()); +} + +TEST(HTTP_Server_Auth, MD5_auth) +{ + constexpr const char cnonce[] = "not a nonce"; + constexpr const char qop[] = "auth"; + + http::login user{"foo", "bar"}; + http::http_server_auth auth{user}; + + const auto response = auth.get_response(make_request(fields{})); + ASSERT_TRUE(bool(response)); + EXPECT_TRUE(is_unauthorized(*response)); + + const auto parsed = parse_response(*response); + ASSERT_LE(2u, parsed.size()); + EXPECT_TRUE(has_same_fields(parsed)); + + const std::string& nonce = parsed[0].at(u8"nonce"); + EXPECT_EQ(24, nonce.size()); + + const std::string uri{"/some_foo_thing"}; + + const std::string a1 = get_a1(user, parsed); + const std::string a2 = get_a2(uri); + std::string nc = get_nc(1); + + const auto generate_auth = [&] { + return md5_hex( + boost::join( + std::vector{md5_hex(a1), nonce, nc, cnonce, qop, md5_hex(a2)}, u8":" + ) + ); + }; + + fields args{ + {u8"algorithm", quoted(u8"md5")}, + {u8"cnonce", quoted(cnonce)}, + {u8"nc", nc}, + {u8"nonce", quoted(nonce)}, + {u8"qop", quoted(qop)}, + {u8"realm", quoted(parsed[0].at(u8"realm"))}, + {u8"response", quoted(generate_auth())}, + {u8"uri", quoted(uri)}, + {u8"username", quoted(user.username)} + }; + + const auto request = make_request(args); + EXPECT_FALSE(bool(auth.get_response(request))); + + for (unsigned i = 2; i < 20; ++i) + { + nc = get_nc(i); + args.at(u8"nc") = nc; + args.at(u8"response") = quoted(generate_auth()); + EXPECT_FALSE(auth.get_response(make_request(args))); + } + + const auto replay = auth.get_response(request); + ASSERT_TRUE(bool(replay)); + EXPECT_TRUE(is_unauthorized(*replay)); + + const auto parsed_replay = parse_response(*replay); + ASSERT_LE(2u, parsed_replay.size()); + EXPECT_TRUE(has_same_fields(parsed_replay)); + + EXPECT_NE(nonce, parsed_replay[0].at(u8"nonce")); + EXPECT_STREQ(u8"true", parsed_replay[0].at(u8"stale").c_str()); +} + +TEST(HTTP_Server_Auth, MD5_sess_auth) +{ + constexpr const char cnonce[] = "not a nonce"; + constexpr const char qop[] = "auth"; + + http::login user{"foo", "bar"}; + http::http_server_auth auth{user}; + + const auto response = auth.get_response(make_request(fields{})); + ASSERT_TRUE(bool(response)); + EXPECT_TRUE(is_unauthorized(*response)); + + const auto parsed = parse_response(*response); + ASSERT_LE(2u, parsed.size()); + EXPECT_TRUE(has_same_fields(parsed)); + + const std::string& nonce = parsed[0].at(u8"nonce"); + EXPECT_EQ(24, nonce.size()); + + const std::string uri{"/some_foo_thing"}; + + const std::string a1 = get_a1_sess(user, cnonce, parsed); + const std::string a2 = get_a2(uri); + std::string nc = get_nc(1); + + const auto generate_auth = [&] { + return md5_hex( + boost::join( + std::vector{md5_hex(a1), nonce, nc, cnonce, qop, md5_hex(a2)}, u8":" + ) + ); + }; + + fields args{ + {u8"algorithm", u8"md5-sess"}, + {u8"cnonce", quoted(cnonce)}, + {u8"nc", nc}, + {u8"nonce", quoted(nonce)}, + {u8"qop", qop}, + {u8"realm", quoted(parsed[0].at(u8"realm"))}, + {u8"response", quoted(generate_auth())}, + {u8"uri", quoted(uri)}, + {u8"username", quoted(user.username)} + }; + + const auto request = make_request(args); + EXPECT_FALSE(bool(auth.get_response(request))); + + for (unsigned i = 2; i < 20; ++i) + { + nc = get_nc(i); + args.at(u8"nc") = nc; + args.at(u8"response") = quoted(generate_auth()); + EXPECT_FALSE(auth.get_response(make_request(args))); + } + + const auto replay = auth.get_response(request); + ASSERT_TRUE(bool(replay)); + EXPECT_TRUE(is_unauthorized(*replay)); + + const auto parsed_replay = parse_response(*replay); + ASSERT_LE(2u, parsed_replay.size()); + EXPECT_TRUE(has_same_fields(parsed_replay)); + + EXPECT_NE(nonce, parsed_replay[0].at(u8"nonce")); + EXPECT_STREQ(u8"true", parsed_replay[0].at(u8"stale").c_str()); +} + + +TEST(HTTP_Auth, DogFood) +{ + const auto add_auth_field = [] (http::http_request_info& request, http::http_client_auth& client) + { + auto field = client.get_auth_field(request.m_http_method_str, request.m_URI); + EXPECT_TRUE(bool(field)); + if (!field) + return false; + request.m_header_info.m_etc_fields.push_back(std::move(*field)); + return true; + }; + + const http::login user{"some_user", "ultimate password"}; + + http::http_server_auth server{user}; + http::http_client_auth client{user}; + + http::http_request_info request{}; + request.m_http_method_str = "GET"; + request.m_URI = "/FOO"; + + auto response = server.get_response(request); + ASSERT_TRUE(bool(response)); + EXPECT_TRUE(is_unauthorized(*response)); + EXPECT_TRUE(response->m_header_info.m_etc_fields.empty()); + response->m_header_info.m_etc_fields = response->m_additional_fields; + + EXPECT_EQ(http::http_client_auth::kSuccess, client.handle_401(*response)); + EXPECT_TRUE(add_auth_field(request, client)); + EXPECT_FALSE(bool(server.get_response(request))); + + for (unsigned i = 0; i < 1000; ++i) + { + request.m_http_method_str += std::to_string(i); + request.m_header_info.m_etc_fields.clear(); + EXPECT_TRUE(add_auth_field(request, client)); + EXPECT_FALSE(bool(server.get_response(request))); + } + + // resetting counter should be rejected by server + request.m_header_info.m_etc_fields.clear(); + client = http::http_client_auth{user}; + EXPECT_EQ(http::http_client_auth::kSuccess, client.handle_401(*response)); + EXPECT_TRUE(add_auth_field(request, client)); + + auto response2 = server.get_response(request); + ASSERT_TRUE(bool(response2)); + EXPECT_TRUE(is_unauthorized(*response2)); + EXPECT_TRUE(response2->m_header_info.m_etc_fields.empty()); + response2->m_header_info.m_etc_fields = response2->m_additional_fields; + + const auth_responses parsed1 = parse_response(*response); + const auth_responses parsed2 = parse_response(*response2); + ASSERT_LE(1u, parsed1.size()); + ASSERT_LE(1u, parsed2.size()); + EXPECT_NE(parsed1[0].at(u8"nonce"), parsed2[0].at(u8"nonce")); + + // with stale=true client should reset + request.m_header_info.m_etc_fields.clear(); + EXPECT_EQ(http::http_client_auth::kSuccess, client.handle_401(*response2)); + EXPECT_TRUE(add_auth_field(request, client)); + EXPECT_FALSE(bool(server.get_response(request))); + + // client should give up if stale=false + EXPECT_EQ(http::http_client_auth::kBadPassword, client.handle_401(*response)); +} + +TEST(HTTP_Client_Auth, Unavailable) +{ + http::http_client_auth auth{}; + EXPECT_EQ(http::http_client_auth::kBadPassword, auth.handle_401(http::http_response_info{})); + EXPECT_FALSE(bool(auth.get_auth_field("GET", "/file"))); +} + +TEST(HTTP_Client_Auth, MissingAuthenticate) +{ + http::http_client_auth auth{{"foo", "bar"}}; + EXPECT_EQ(http::http_client_auth::kParseFailure, auth.handle_401(http::http_response_info{})); + EXPECT_FALSE(bool(auth.get_auth_field("POST", "/\xFFname"))); + { + http::http_response_info response{}; + response.m_additional_fields.push_back({"\xFF", "\xFF"}); + EXPECT_EQ(http::http_client_auth::kParseFailure, auth.handle_401(response)); + } + EXPECT_FALSE(bool(auth.get_auth_field("DELETE", "/file/does/not/exist"))); +} + +TEST(HTTP_Client_Auth, BadSyntax) +{ + http::http_client_auth auth{{"foo", "bar"}}; + EXPECT_EQ(http::http_client_auth::kParseFailure, auth.handle_401(make_response({{{u8"realm", "fo\xFF"}}}))); + EXPECT_EQ(http::http_client_auth::kParseFailure, auth.handle_401(make_response({{{u8"domain", "fo\xFF"}}}))); + EXPECT_EQ(http::http_client_auth::kParseFailure, auth.handle_401(make_response({{{u8"nonce", "fo\xFF"}}}))); + EXPECT_EQ(http::http_client_auth::kParseFailure, auth.handle_401(make_response({{{u8"nonce \xFF =", "fo\xFF"}}}))); + EXPECT_EQ(http::http_client_auth::kParseFailure, auth.handle_401(make_response({{{u8" \xFF nonce", "fo\xFF"}}}))); +} + +TEST(HTTP_Client_Auth, MD5) +{ + constexpr char method[] = "NOP"; + constexpr char nonce[] = "some crazy nonce"; + constexpr char realm[] = "the only realm"; + constexpr char uri[] = "/some_file"; + + const http::login user{"foo", "bar"}; + http::http_client_auth auth{user}; + + auto response = make_response({ + { + {u8"domain", quoted("ignored")}, + {u8"nonce", quoted(nonce)}, + {u8"REALM", quoted(realm)} + }, + { + {u8"algorithm", "null"}, + {u8"domain", quoted("ignored")}, + {u8"nonce", quoted(std::string{"e"} + nonce)}, + {u8"realm", quoted(std::string{"e"} + realm)} + }, + }); + + EXPECT_EQ(http::http_client_auth::kSuccess, auth.handle_401(response)); + const auto auth_field = auth.get_auth_field(method, uri); + ASSERT_TRUE(bool(auth_field)); + + const auto parsed = parse_fields(auth_field->second); + EXPECT_STREQ(u8"Authorization", auth_field->first.c_str()); + EXPECT_EQ(parsed.end(), parsed.find(u8"opaque")); + EXPECT_EQ(parsed.end(), parsed.find(u8"qop")); + EXPECT_EQ(parsed.end(), parsed.find(u8"nc")); + EXPECT_STREQ(u8"MD5", parsed.at(u8"algorithm").c_str()); + EXPECT_STREQ(nonce, parsed.at(u8"nonce").c_str()); + EXPECT_STREQ(uri, parsed.at(u8"uri").c_str()); + EXPECT_EQ(user.username, parsed.at(u8"username")); + EXPECT_STREQ(realm, parsed.at(u8"realm").c_str()); + + const std::string a1 = get_a1(user, parsed); + const std::string a2 = get_a2(uri); + const std::string auth_code = md5_hex( + boost::join(std::vector{md5_hex(a1), nonce, md5_hex(a2)}, u8":") + ); + EXPECT_TRUE(boost::iequals(auth_code, parsed.at(u8"response"))); + { + const auto auth_field_dup = auth.get_auth_field(method, uri); + ASSERT_TRUE(bool(auth_field_dup)); + EXPECT_EQ(*auth_field, *auth_field_dup); + } + + + EXPECT_EQ(http::http_client_auth::kBadPassword, auth.handle_401(response)); + response.m_header_info.m_etc_fields.front().second.append(u8"," + write_fields({{u8"stale", u8"TRUE"}})); + EXPECT_EQ(http::http_client_auth::kSuccess, auth.handle_401(response)); +} + +TEST(HTTP_Client_Auth, MD5_auth) +{ + constexpr char cnonce[] = ""; + constexpr char method[] = "NOP"; + constexpr char nonce[] = "some crazy nonce"; + constexpr char opaque[] = "this is the opaque"; + constexpr char qop[] = u8"ignore,auth,ignore"; + constexpr char realm[] = "the only realm"; + constexpr char uri[] = "/some_file"; + + const http::login user{"foo", "bar"}; + http::http_client_auth auth{user}; + + auto response = make_response({ + { + {u8"algorithm", u8"MD5"}, + {u8"domain", quoted("ignored")}, + {u8"nonce", quoted(std::string{"e"} + nonce)}, + {u8"realm", quoted(std::string{"e"} + realm)}, + {u8"qop", quoted("some,thing,to,ignore")} + }, + { + {u8"algorIthm", quoted(u8"md5")}, + {u8"domain", quoted("ignored")}, + {u8"noNce", quoted(nonce)}, + {u8"opaque", quoted(opaque)}, + {u8"realm", quoted(realm)}, + {u8"QoP", quoted(qop)} + } + }); + + EXPECT_EQ(http::http_client_auth::kSuccess, auth.handle_401(response)); + + for (unsigned i = 1; i < 1000; ++i) + { + const std::string nc = get_nc(i); + + const auto auth_field = auth.get_auth_field(method, uri); + ASSERT_TRUE(bool(auth_field)); + + const auto parsed = parse_fields(auth_field->second); + EXPECT_STREQ(u8"Authorization", auth_field->first.c_str()); + EXPECT_STREQ(u8"MD5", parsed.at(u8"algorithm").c_str()); + EXPECT_STREQ(nonce, parsed.at(u8"nonce").c_str()); + EXPECT_STREQ(opaque, parsed.at(u8"opaque").c_str()); + EXPECT_STREQ(u8"auth", parsed.at(u8"qop").c_str()); + EXPECT_STREQ(uri, parsed.at(u8"uri").c_str()); + EXPECT_EQ(user.username, parsed.at(u8"username")); + EXPECT_STREQ(realm, parsed.at(u8"realm").c_str()); + EXPECT_EQ(nc, parsed.at(u8"nc")); + + const std::string a1 = get_a1(user, parsed); + const std::string a2 = get_a2(uri); + const std::string auth_code = md5_hex( + boost::join(std::vector{md5_hex(a1), nonce, nc, cnonce, u8"auth", md5_hex(a2)}, u8":") + ); + EXPECT_TRUE(boost::iequals(auth_code, parsed.at(u8"response"))); + } + + EXPECT_EQ(http::http_client_auth::kBadPassword, auth.handle_401(response)); + response.m_header_info.m_etc_fields.back().second.append(u8"," + write_fields({{u8"stale", u8"trUe"}})); + EXPECT_EQ(http::http_client_auth::kSuccess, auth.handle_401(response)); +} + + +TEST(HTTP, Add_Field) +{ + std::string str{"leading text"}; + epee::net_utils::http::add_field(str, "foo", "bar"); + epee::net_utils::http::add_field(str, std::string("bar"), std::string("foo")); + epee::net_utils::http::add_field(str, {"moarbars", "moarfoo"}); + + EXPECT_STREQ("leading textfoo: bar\r\nbar: foo\r\nmoarbars: moarfoo\r\n", str.c_str()); +} diff --git a/tests/unit_tests/http_auth.cpp b/tests/unit_tests/http_auth.cpp deleted file mode 100644 index 97954642f..000000000 --- a/tests/unit_tests/http_auth.cpp +++ /dev/null @@ -1,724 +0,0 @@ -// Copyright (c) 2014-2016, The Monero Project -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, are -// permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of -// conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list -// of conditions and the following disclaimer in the documentation and/or other -// materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be -// used to endorse or promote products derived from this software without specific -// prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL -// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF -// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#include "gtest/gtest.h" -#include "net/http_auth.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "md5_l.h" -#include "string_tools.h" - -namespace { -namespace http = epee::net_utils::http; -using fields = std::unordered_map; -using auth_responses = std::vector; - -std::string quoted(std::string str) -{ - str.insert(str.begin(), '"'); - str.push_back('"'); - return str; -} - -void write_fields(std::string& out, const fields& args) -{ - namespace karma = boost::spirit::karma; - karma::generate( - std::back_inserter(out), - (karma::string << " = " << karma::string) % " , ", - args); -} - -std::string write_fields(const fields& args) -{ - std::string out{}; - write_fields(out, args); - return out; -} - -http::http_request_info make_request(const fields& args) -{ - std::string out{" DIGEST "}; - write_fields(out, args); - - http::http_request_info request{}; - request.m_http_method_str = "NOP"; - request.m_header_info.m_etc_fields.push_back( - std::make_pair(u8"authorization", std::move(out)) - ); - return request; -} - -http::http_response_info make_response(const auth_responses& choices) -{ - http::http_response_info response{}; - for (const auto& choice : choices) - { - std::string out{" DIGEST "}; - write_fields(out, choice); - - response.m_additional_fields.push_back( - std::make_pair(u8"WWW-authenticate", std::move(out)) - ); - } - return response; -} - -bool has_same_fields(const auth_responses& in) -{ - const std::vector check{u8"nonce", u8"qop", u8"realm", u8"stale"}; - - auto current = in.begin(); - const auto end = in.end(); - if (current == end) - return true; - - ++current; - for ( ; current != end; ++current ) - { - for (const auto& field : check) - { - const std::string& expected = in[0].at(field); - const std::string& actual = current->at(field); - EXPECT_EQ(expected, actual); - if (expected != actual) - return false; - } - } - return true; -} - -bool is_unauthorized(const http::http_response_info& response) -{ - EXPECT_EQ(401, response.m_response_code); - EXPECT_STREQ(u8"Unauthorized", response.m_response_comment.c_str()); - EXPECT_STREQ(u8"text/html", response.m_mime_tipe.c_str()); - return response.m_response_code == 401 && - response.m_response_comment == u8"Unauthorized" && - response.m_mime_tipe == u8"text/html"; -} - -fields parse_fields(const std::string& value) -{ - namespace qi = boost::spirit::qi; - - fields out{}; - const bool rc = qi::parse( - value.begin(), value.end(), - qi::lit(u8"Digest ") >> (( - +qi::ascii::alpha >> - qi::lit('=') >> ( - (qi::lit('"') >> +(qi::ascii::char_ - '"') >> qi::lit('"')) | - +(qi::ascii::graph - qi::ascii::char_(u8"()<>@,;:\\\"/[]?={}")) - ) - ) % ',' - ) >> qi::eoi, - out - ); - if (!rc) - throw std::runtime_error{"Bad field given in HTTP header"}; - - return out; -} - -auth_responses parse_response(const http::http_response_info& response) -{ - auth_responses result{}; - - const auto end = response.m_additional_fields.end(); - for (auto current = response.m_additional_fields.begin();; ++current) - { - current = std::find_if(current, end, [] (const std::pair& field) { - return boost::equals(u8"WWW-authenticate", field.first); - }); - - if (current == end) - return result; - - result.push_back(parse_fields(current->second)); - } - return result; -} - -std::string md5_hex(const std::string& in) -{ - md5::MD5_CTX ctx{}; - md5::MD5Init(std::addressof(ctx)); - md5::MD5Update( - std::addressof(ctx), - reinterpret_cast(in.data()), - in.size() - ); - - std::array digest{{}}; - md5::MD5Final(digest.data(), std::addressof(ctx)); - return epee::string_tools::pod_to_hex(digest); -} - -std::string get_a1(const http::login& user, const fields& src) -{ - const std::string& realm = src.at(u8"realm"); - return boost::join( - std::vector{user.username, realm, user.password}, u8":" - ); -} - -std::string get_a1(const http::login& user, const auth_responses& responses) -{ - return get_a1(user, responses.at(0)); -} - -std::string get_a1_sess(const http::login& user, const std::string& cnonce, const auth_responses& responses) -{ - const std::string& nonce = responses.at(0).at(u8"nonce"); - return boost::join( - std::vector{md5_hex(get_a1(user, responses)), nonce, cnonce}, u8":" - ); -} - -std::string get_a2(const std::string& uri) -{ - return boost::join(std::vector{"NOP", uri}, u8":"); -} - -std::string get_nc(std::uint32_t count) -{ - namespace karma = boost::spirit::karma; - std::string out; - karma::generate( - std::back_inserter(out), - karma::right_align(8, '0')[karma::uint_generator{}], - count - ); - - return out; -} -} - -TEST(HTTP_Server_Auth, NotRequired) -{ - http::http_server_auth auth{}; - EXPECT_FALSE(auth.get_response(http::http_request_info{})); -} - -TEST(HTTP_Server_Auth, MissingAuth) -{ - http::http_server_auth auth{{"foo", "bar"}}; - EXPECT_TRUE(bool(auth.get_response(http::http_request_info{}))); - { - http::http_request_info request{}; - request.m_header_info.m_etc_fields.push_back({"\xFF", "\xFF"}); - EXPECT_TRUE(bool(auth.get_response(request))); - } -} - -TEST(HTTP_Server_Auth, BadSyntax) -{ - http::http_server_auth auth{{"foo", "bar"}}; - EXPECT_TRUE(bool(auth.get_response(make_request({{u8"algorithm", "fo\xFF"}})))); - EXPECT_TRUE(bool(auth.get_response(make_request({{u8"cnonce", "\"000\xFF\""}})))); - EXPECT_TRUE(bool(auth.get_response(make_request({{u8"cnonce \xFF =", "\"000\xFF\""}})))); - EXPECT_TRUE(bool(auth.get_response(make_request({{u8" \xFF cnonce", "\"000\xFF\""}})))); -} - -TEST(HTTP_Server_Auth, MD5) -{ - http::login user{"foo", "bar"}; - http::http_server_auth auth{user}; - - const auto response = auth.get_response(make_request(fields{})); - ASSERT_TRUE(bool(response)); - EXPECT_TRUE(is_unauthorized(*response)); - - const auto fields = parse_response(*response); - ASSERT_LE(2u, fields.size()); - EXPECT_TRUE(has_same_fields(fields)); - - const std::string& nonce = fields[0].at(u8"nonce"); - EXPECT_EQ(24, nonce.size()); - - const std::string uri{"/some_foo_thing"}; - - const std::string a1 = get_a1(user, fields); - const std::string a2 = get_a2(uri); - - const std::string auth_code = md5_hex( - boost::join(std::vector{md5_hex(a1), nonce, md5_hex(a2)}, u8":") - ); - - const auto request = make_request({ - {u8"nonce", quoted(nonce)}, - {u8"realm", quoted(fields[0].at(u8"realm"))}, - {u8"response", quoted(auth_code)}, - {u8"uri", quoted(uri)}, - {u8"username", quoted(user.username)} - }); - - EXPECT_FALSE(bool(auth.get_response(request))); - - const auto response2 = auth.get_response(request); - ASSERT_TRUE(bool(response2)); - EXPECT_TRUE(is_unauthorized(*response2)); - - const auto fields2 = parse_response(*response2); - ASSERT_LE(2u, fields2.size()); - EXPECT_TRUE(has_same_fields(fields2)); - - EXPECT_NE(nonce, fields2[0].at(u8"nonce")); - EXPECT_STREQ(u8"true", fields2[0].at(u8"stale").c_str()); -} - -TEST(HTTP_Server_Auth, MD5_sess) -{ - constexpr const char cnonce[] = "not a good cnonce"; - - http::login user{"foo", "bar"}; - http::http_server_auth auth{user}; - - const auto response = auth.get_response(make_request(fields{})); - ASSERT_TRUE(bool(response)); - EXPECT_TRUE(is_unauthorized(*response)); - - const auto fields = parse_response(*response); - ASSERT_LE(2u, fields.size()); - EXPECT_TRUE(has_same_fields(fields)); - - const std::string& nonce = fields[0].at(u8"nonce"); - EXPECT_EQ(24, nonce.size()); - - const std::string uri{"/some_foo_thing"}; - - const std::string a1 = get_a1_sess(user, cnonce, fields); - const std::string a2 = get_a2(uri); - - const std::string auth_code = md5_hex( - boost::join(std::vector{md5_hex(a1), nonce, md5_hex(a2)}, u8":") - ); - - const auto request = make_request({ - {u8"algorithm", u8"md5-sess"}, - {u8"cnonce", quoted(cnonce)}, - {u8"nonce", quoted(nonce)}, - {u8"realm", quoted(fields[0].at(u8"realm"))}, - {u8"response", quoted(auth_code)}, - {u8"uri", quoted(uri)}, - {u8"username", quoted(user.username)} - }); - - EXPECT_FALSE(bool(auth.get_response(request))); - - const auto response2 = auth.get_response(request); - ASSERT_TRUE(bool(response2)); - EXPECT_TRUE(is_unauthorized(*response2)); - - const auto fields2 = parse_response(*response2); - ASSERT_LE(2u, fields2.size()); - EXPECT_TRUE(has_same_fields(fields2)); - - EXPECT_NE(nonce, fields2[0].at(u8"nonce")); - EXPECT_STREQ(u8"true", fields2[0].at(u8"stale").c_str()); -} - -TEST(HTTP_Server_Auth, MD5_auth) -{ - constexpr const char cnonce[] = "not a nonce"; - constexpr const char qop[] = "auth"; - - http::login user{"foo", "bar"}; - http::http_server_auth auth{user}; - - const auto response = auth.get_response(make_request(fields{})); - ASSERT_TRUE(bool(response)); - EXPECT_TRUE(is_unauthorized(*response)); - - const auto parsed = parse_response(*response); - ASSERT_LE(2u, parsed.size()); - EXPECT_TRUE(has_same_fields(parsed)); - - const std::string& nonce = parsed[0].at(u8"nonce"); - EXPECT_EQ(24, nonce.size()); - - const std::string uri{"/some_foo_thing"}; - - const std::string a1 = get_a1(user, parsed); - const std::string a2 = get_a2(uri); - std::string nc = get_nc(1); - - const auto generate_auth = [&] { - return md5_hex( - boost::join( - std::vector{md5_hex(a1), nonce, nc, cnonce, qop, md5_hex(a2)}, u8":" - ) - ); - }; - - fields args{ - {u8"algorithm", quoted(u8"md5")}, - {u8"cnonce", quoted(cnonce)}, - {u8"nc", nc}, - {u8"nonce", quoted(nonce)}, - {u8"qop", quoted(qop)}, - {u8"realm", quoted(parsed[0].at(u8"realm"))}, - {u8"response", quoted(generate_auth())}, - {u8"uri", quoted(uri)}, - {u8"username", quoted(user.username)} - }; - - const auto request = make_request(args); - EXPECT_FALSE(bool(auth.get_response(request))); - - for (unsigned i = 2; i < 20; ++i) - { - nc = get_nc(i); - args.at(u8"nc") = nc; - args.at(u8"response") = quoted(generate_auth()); - EXPECT_FALSE(auth.get_response(make_request(args))); - } - - const auto replay = auth.get_response(request); - ASSERT_TRUE(bool(replay)); - EXPECT_TRUE(is_unauthorized(*replay)); - - const auto parsed_replay = parse_response(*replay); - ASSERT_LE(2u, parsed_replay.size()); - EXPECT_TRUE(has_same_fields(parsed_replay)); - - EXPECT_NE(nonce, parsed_replay[0].at(u8"nonce")); - EXPECT_STREQ(u8"true", parsed_replay[0].at(u8"stale").c_str()); -} - -TEST(HTTP_Server_Auth, MD5_sess_auth) -{ - constexpr const char cnonce[] = "not a nonce"; - constexpr const char qop[] = "auth"; - - http::login user{"foo", "bar"}; - http::http_server_auth auth{user}; - - const auto response = auth.get_response(make_request(fields{})); - ASSERT_TRUE(bool(response)); - EXPECT_TRUE(is_unauthorized(*response)); - - const auto parsed = parse_response(*response); - ASSERT_LE(2u, parsed.size()); - EXPECT_TRUE(has_same_fields(parsed)); - - const std::string& nonce = parsed[0].at(u8"nonce"); - EXPECT_EQ(24, nonce.size()); - - const std::string uri{"/some_foo_thing"}; - - const std::string a1 = get_a1_sess(user, cnonce, parsed); - const std::string a2 = get_a2(uri); - std::string nc = get_nc(1); - - const auto generate_auth = [&] { - return md5_hex( - boost::join( - std::vector{md5_hex(a1), nonce, nc, cnonce, qop, md5_hex(a2)}, u8":" - ) - ); - }; - - fields args{ - {u8"algorithm", u8"md5-sess"}, - {u8"cnonce", quoted(cnonce)}, - {u8"nc", nc}, - {u8"nonce", quoted(nonce)}, - {u8"qop", qop}, - {u8"realm", quoted(parsed[0].at(u8"realm"))}, - {u8"response", quoted(generate_auth())}, - {u8"uri", quoted(uri)}, - {u8"username", quoted(user.username)} - }; - - const auto request = make_request(args); - EXPECT_FALSE(bool(auth.get_response(request))); - - for (unsigned i = 2; i < 20; ++i) - { - nc = get_nc(i); - args.at(u8"nc") = nc; - args.at(u8"response") = quoted(generate_auth()); - EXPECT_FALSE(auth.get_response(make_request(args))); - } - - const auto replay = auth.get_response(request); - ASSERT_TRUE(bool(replay)); - EXPECT_TRUE(is_unauthorized(*replay)); - - const auto parsed_replay = parse_response(*replay); - ASSERT_LE(2u, parsed_replay.size()); - EXPECT_TRUE(has_same_fields(parsed_replay)); - - EXPECT_NE(nonce, parsed_replay[0].at(u8"nonce")); - EXPECT_STREQ(u8"true", parsed_replay[0].at(u8"stale").c_str()); -} - - -TEST(HTTP_Auth, DogFood) -{ - const auto add_field = [] (http::http_request_info& request, http::http_client_auth& client) - { - auto field = client.get_auth_field(request.m_http_method_str, request.m_URI); - EXPECT_TRUE(bool(field)); - if (!field) - return false; - request.m_header_info.m_etc_fields.push_back(std::move(*field)); - return true; - }; - - const http::login user{"some_user", "ultimate password"}; - - http::http_server_auth server{user}; - http::http_client_auth client{user}; - - http::http_request_info request{}; - request.m_http_method_str = "GET"; - request.m_URI = "/FOO"; - - const auto response = server.get_response(request); - ASSERT_TRUE(bool(response)); - EXPECT_TRUE(is_unauthorized(*response)); - - EXPECT_EQ(http::http_client_auth::kSuccess, client.handle_401(*response)); - EXPECT_TRUE(add_field(request, client)); - EXPECT_FALSE(bool(server.get_response(request))); - - for (unsigned i = 0; i < 1000; ++i) - { - request.m_http_method_str += std::to_string(i); - request.m_header_info.m_etc_fields.clear(); - EXPECT_TRUE(add_field(request, client)); - EXPECT_FALSE(bool(server.get_response(request))); - } - - // resetting counter should be rejected by server - request.m_header_info.m_etc_fields.clear(); - client = http::http_client_auth{user}; - EXPECT_EQ(http::http_client_auth::kSuccess, client.handle_401(*response)); - EXPECT_TRUE(add_field(request, client)); - - const auto response2 = server.get_response(request); - ASSERT_TRUE(bool(response2)); - EXPECT_TRUE(is_unauthorized(*response2)); - - const auth_responses parsed1 = parse_response(*response); - const auth_responses parsed2 = parse_response(*response2); - ASSERT_LE(1u, parsed1.size()); - ASSERT_LE(1u, parsed2.size()); - EXPECT_NE(parsed1[0].at(u8"nonce"), parsed2[0].at(u8"nonce")); - - // with stale=true client should reset - request.m_header_info.m_etc_fields.clear(); - EXPECT_EQ(http::http_client_auth::kSuccess, client.handle_401(*response2)); - EXPECT_TRUE(add_field(request, client)); - EXPECT_FALSE(bool(server.get_response(request))); - - // client should give up if stale=false - EXPECT_EQ(http::http_client_auth::kBadPassword, client.handle_401(*response)); -} - -TEST(HTTP_Client_Auth, Unavailable) -{ - http::http_client_auth auth{}; - EXPECT_EQ(http::http_client_auth::kBadPassword, auth.handle_401(http::http_response_info{})); - EXPECT_FALSE(bool(auth.get_auth_field("GET", "/file"))); -} - -TEST(HTTP_Client_Auth, MissingAuthenticate) -{ - http::http_client_auth auth{{"foo", "bar"}}; - EXPECT_EQ(http::http_client_auth::kParseFailure, auth.handle_401(http::http_response_info{})); - EXPECT_FALSE(bool(auth.get_auth_field("POST", "/\xFFname"))); - { - http::http_response_info response{}; - response.m_additional_fields.push_back({"\xFF", "\xFF"}); - EXPECT_EQ(http::http_client_auth::kParseFailure, auth.handle_401(response)); - } - EXPECT_FALSE(bool(auth.get_auth_field("DELETE", "/file/does/not/exist"))); -} - -TEST(HTTP_Client_Auth, BadSyntax) -{ - http::http_client_auth auth{{"foo", "bar"}}; - EXPECT_EQ(http::http_client_auth::kParseFailure, auth.handle_401(make_response({{{u8"realm", "fo\xFF"}}}))); - EXPECT_EQ(http::http_client_auth::kParseFailure, auth.handle_401(make_response({{{u8"domain", "fo\xFF"}}}))); - EXPECT_EQ(http::http_client_auth::kParseFailure, auth.handle_401(make_response({{{u8"nonce", "fo\xFF"}}}))); - EXPECT_EQ(http::http_client_auth::kParseFailure, auth.handle_401(make_response({{{u8"nonce \xFF =", "fo\xFF"}}}))); - EXPECT_EQ(http::http_client_auth::kParseFailure, auth.handle_401(make_response({{{u8" \xFF nonce", "fo\xFF"}}}))); -} - -TEST(HTTP_Client_Auth, MD5) -{ - constexpr char method[] = "NOP"; - constexpr char nonce[] = "some crazy nonce"; - constexpr char realm[] = "the only realm"; - constexpr char uri[] = "/some_file"; - - const http::login user{"foo", "bar"}; - http::http_client_auth auth{user}; - - auto response = make_response({ - { - {u8"domain", quoted("ignored")}, - {u8"nonce", quoted(nonce)}, - {u8"REALM", quoted(realm)} - }, - { - {u8"algorithm", "null"}, - {u8"domain", quoted("ignored")}, - {u8"nonce", quoted(std::string{"e"} + nonce)}, - {u8"realm", quoted(std::string{"e"} + realm)} - }, - }); - - EXPECT_EQ(http::http_client_auth::kSuccess, auth.handle_401(response)); - const auto auth_field = auth.get_auth_field(method, uri); - ASSERT_TRUE(bool(auth_field)); - - const auto parsed = parse_fields(auth_field->second); - EXPECT_STREQ(u8"Authorization", auth_field->first.c_str()); - EXPECT_EQ(parsed.end(), parsed.find(u8"opaque")); - EXPECT_EQ(parsed.end(), parsed.find(u8"qop")); - EXPECT_EQ(parsed.end(), parsed.find(u8"nc")); - EXPECT_STREQ(u8"MD5", parsed.at(u8"algorithm").c_str()); - EXPECT_STREQ(nonce, parsed.at(u8"nonce").c_str()); - EXPECT_STREQ(uri, parsed.at(u8"uri").c_str()); - EXPECT_EQ(user.username, parsed.at(u8"username")); - EXPECT_STREQ(realm, parsed.at(u8"realm").c_str()); - - const std::string a1 = get_a1(user, parsed); - const std::string a2 = get_a2(uri); - const std::string auth_code = md5_hex( - boost::join(std::vector{md5_hex(a1), nonce, md5_hex(a2)}, u8":") - ); - EXPECT_TRUE(boost::iequals(auth_code, parsed.at(u8"response"))); - { - const auto auth_field_dup = auth.get_auth_field(method, uri); - ASSERT_TRUE(bool(auth_field_dup)); - EXPECT_EQ(*auth_field, *auth_field_dup); - } - - - EXPECT_EQ(http::http_client_auth::kBadPassword, auth.handle_401(response)); - response.m_additional_fields.front().second.append(u8"," + write_fields({{u8"stale", u8"TRUE"}})); - EXPECT_EQ(http::http_client_auth::kSuccess, auth.handle_401(response)); -} - -TEST(HTTP_Client_Auth, MD5_auth) -{ - constexpr char cnonce[] = ""; - constexpr char method[] = "NOP"; - constexpr char nonce[] = "some crazy nonce"; - constexpr char opaque[] = "this is the opaque"; - constexpr char qop[] = u8"ignore,auth,ignore"; - constexpr char realm[] = "the only realm"; - constexpr char uri[] = "/some_file"; - - const http::login user{"foo", "bar"}; - http::http_client_auth auth{user}; - - auto response = make_response({ - { - {u8"algorithm", u8"MD5"}, - {u8"domain", quoted("ignored")}, - {u8"nonce", quoted(std::string{"e"} + nonce)}, - {u8"realm", quoted(std::string{"e"} + realm)}, - {u8"qop", quoted("some,thing,to,ignore")} - }, - { - {u8"algorIthm", quoted(u8"md5")}, - {u8"domain", quoted("ignored")}, - {u8"noNce", quoted(nonce)}, - {u8"opaque", quoted(opaque)}, - {u8"realm", quoted(realm)}, - {u8"QoP", quoted(qop)} - } - }); - - EXPECT_EQ(http::http_client_auth::kSuccess, auth.handle_401(response)); - - for (unsigned i = 1; i < 1000; ++i) - { - const std::string nc = get_nc(i); - - const auto auth_field = auth.get_auth_field(method, uri); - ASSERT_TRUE(bool(auth_field)); - - const auto parsed = parse_fields(auth_field->second); - EXPECT_STREQ(u8"Authorization", auth_field->first.c_str()); - EXPECT_STREQ(u8"MD5", parsed.at(u8"algorithm").c_str()); - EXPECT_STREQ(nonce, parsed.at(u8"nonce").c_str()); - EXPECT_STREQ(opaque, parsed.at(u8"opaque").c_str()); - EXPECT_STREQ(u8"auth", parsed.at(u8"qop").c_str()); - EXPECT_STREQ(uri, parsed.at(u8"uri").c_str()); - EXPECT_EQ(user.username, parsed.at(u8"username")); - EXPECT_STREQ(realm, parsed.at(u8"realm").c_str()); - EXPECT_EQ(nc, parsed.at(u8"nc")); - - const std::string a1 = get_a1(user, parsed); - const std::string a2 = get_a2(uri); - const std::string auth_code = md5_hex( - boost::join(std::vector{md5_hex(a1), nonce, nc, cnonce, u8"auth", md5_hex(a2)}, u8":") - ); - EXPECT_TRUE(boost::iequals(auth_code, parsed.at(u8"response"))); - } - - EXPECT_EQ(http::http_client_auth::kBadPassword, auth.handle_401(response)); - response.m_additional_fields.back().second.append(u8"," + write_fields({{u8"stale", u8"trUe"}})); - EXPECT_EQ(http::http_client_auth::kSuccess, auth.handle_401(response)); -} - -- cgit v1.2.3