diff options
-rw-r--r-- | contrib/epee/include/net/http_auth.h | 115 | ||||
-rw-r--r-- | contrib/epee/include/net/http_protocol_handler.h | 6 | ||||
-rw-r--r-- | contrib/epee/include/net/http_server_impl_base.h | 2 | ||||
-rw-r--r-- | contrib/epee/src/http_auth.cpp | 503 | ||||
-rw-r--r-- | src/cryptonote_core/blockchain.cpp | 2 | ||||
-rw-r--r-- | src/rpc/core_rpc_server.cpp | 2 | ||||
-rw-r--r-- | src/rpc/core_rpc_server_commands_defs.h | 10 | ||||
-rw-r--r-- | src/simplewallet/simplewallet.cpp | 164 | ||||
-rw-r--r-- | src/simplewallet/simplewallet.h | 4 | ||||
-rw-r--r-- | src/wallet/api/wallet_manager.cpp | 38 | ||||
-rw-r--r-- | src/wallet/api/wallet_manager.h | 3 | ||||
-rw-r--r-- | src/wallet/wallet2.cpp | 6 | ||||
-rw-r--r-- | src/wallet/wallet2.h | 7 | ||||
-rw-r--r-- | src/wallet/wallet2_api.h | 9 | ||||
-rw-r--r-- | src/wallet/wallet_rpc_server.cpp | 2 | ||||
-rw-r--r-- | tests/unit_tests/http_auth.cpp | 351 |
16 files changed, 1015 insertions, 209 deletions
diff --git a/contrib/epee/include/net/http_auth.h b/contrib/epee/include/net/http_auth.h index 795d213d9..bdbfa7524 100644 --- a/contrib/epee/include/net/http_auth.h +++ b/contrib/epee/include/net/http_auth.h @@ -28,32 +28,35 @@ #pragma once #include <boost/optional/optional.hpp> +#include <boost/utility/string_ref.hpp> #include <cstdint> -#include "http_base.h" +#include <functional> #include <string> #include <utility> +#include "http_base.h" + namespace epee { namespace net_utils { namespace http { - //! Implements RFC 2617 digest auth. Digests from RFC 7616 can be added. - class http_auth + struct login { - public: - struct login - { - login() : username(), password() {} - login(std::string username_, std::string password_) - : username(std::move(username_)), password(std::move(password_)) - {} + login() : username(), password() {} + login(std::string username_, std::string password_) + : username(std::move(username_)), password(std::move(password_)) + {} - std::string username; - std::string password; - }; + std::string username; + std::string password; + }; + //! Implements RFC 2617 digest auth. Digests from RFC 7616 can be added. + class http_server_auth + { + public: struct session { session(login credentials_) @@ -65,21 +68,97 @@ namespace net_utils std::uint32_t counter; }; - http_auth() : user() {} - http_auth(login credentials); + http_server_auth() : user() {} + http_server_auth(login credentials); //! \return Auth response, or `boost::none` iff `request` had valid auth. boost::optional<http_response_info> get_response(const http_request_info& request) { if (user) + return do_get_response(request); + return boost::none; + } + private: + boost::optional<http_response_info> do_get_response(const http_request_info& request); + + boost::optional<session> user; + }; + + //! Implements RFC 2617 digest auth. Digests from RFC 7616 can be added. + class http_client_auth + { + public: + enum status : std::uint8_t { kSuccess = 0, kBadPassword, kParseFailure }; + + struct session + { + session(login credentials_) + : credentials(std::move(credentials_)), server(), counter(0) + {} + + struct keys { - return process(request); - } + using algorithm = + std::function<std::string(const session&, boost::string_ref, boost::string_ref)>; + + keys() : nonce(), opaque(), realm(), generator() {} + keys(std::string nonce_, std::string opaque_, std::string realm_, algorithm generator_) + : nonce(std::move(nonce_)) + , opaque(std::move(opaque_)) + , realm(std::move(realm_)) + , generator(std::move(generator_)) + {} + + std::string nonce; + std::string opaque; + std::string realm; + algorithm generator; + }; + + login credentials; + keys server; + std::uint32_t counter; + }; + + http_client_auth() : user() {} + http_client_auth(login credentials); + + /*! + Clients receiving a 401 response code from the server should call this + function to process the server auth. Then, before every client request, + `get_auth_field()` should be called to retrieve the newest + authorization request. + + \return `kBadPassword` if client will never be able to authenticate, + `kParseFailure` if all server authentication responses were invalid, + and `kSuccess` if `get_auth_field` is ready to generate authorization + fields. + */ + status handle_401(const http_response_info& response) + { + if (user) + return do_handle_401(response); + return kBadPassword; + } + + /*! + After calling `handle_401`, clients should call this function to + generate an authentication field for every request. + + \return A HTTP "Authorization" field if `handle_401(...)` previously + returned `kSuccess`. + */ + boost::optional<std::pair<std::string, std::string>> get_auth_field( + const boost::string_ref method, const boost::string_ref uri) + { + if (user) + return do_get_auth_field(method, uri); return boost::none; } private: - boost::optional<http_response_info> process(const http_request_info& request); + status do_handle_401(const http_response_info&); + boost::optional<std::pair<std::string, std::string>> do_get_auth_field(boost::string_ref, boost::string_ref); boost::optional<session> user; }; diff --git a/contrib/epee/include/net/http_protocol_handler.h b/contrib/epee/include/net/http_protocol_handler.h index 3813f9d7c..69ea04fbe 100644 --- a/contrib/epee/include/net/http_protocol_handler.h +++ b/contrib/epee/include/net/http_protocol_handler.h @@ -52,7 +52,7 @@ namespace net_utils { std::string m_folder; std::string m_required_user_agent; - boost::optional<http_auth::login> m_user; + boost::optional<login> m_user; critical_section m_lock; }; @@ -173,7 +173,7 @@ namespace net_utils : simple_http_connection_handler<t_connection_context>(psnd_hndlr, config), m_config(config), m_conn_context(conn_context), - m_auth(m_config.m_user ? http_auth{*m_config.m_user} : http_auth{}) + m_auth(m_config.m_user ? http_server_auth{*m_config.m_user} : http_server_auth{}) {} inline bool handle_request(const http_request_info& query_info, http_response_info& response) { @@ -214,7 +214,7 @@ namespace net_utils //simple_http_connection_handler::config_type m_stub_config; config_type& m_config; t_connection_context& m_conn_context; - http_auth m_auth; + http_server_auth m_auth; }; } } diff --git a/contrib/epee/include/net/http_server_impl_base.h b/contrib/epee/include/net/http_server_impl_base.h index f6b2d6941..a5cc1a917 100644 --- a/contrib/epee/include/net/http_server_impl_base.h +++ b/contrib/epee/include/net/http_server_impl_base.h @@ -53,7 +53,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<net_utils::http::http_auth::login> user = boost::none) + std::string user_agent = "", boost::optional<net_utils::http::login> user = boost::none) { //set self as callback handler diff --git a/contrib/epee/src/http_auth.cpp b/contrib/epee/src/http_auth.cpp index 98870a7a9..7fd32dabc 100644 --- a/contrib/epee/src/http_auth.cpp +++ b/contrib/epee/src/http_auth.cpp @@ -28,34 +28,41 @@ #include "net/http_auth.h" #include <array> +#include <boost/algorithm/string/find_iterator.hpp> #include <boost/algorithm/string/predicate.hpp> #include <boost/fusion/adapted/std_tuple.hpp> #include <boost/fusion/algorithm/iteration/for_each.hpp> +#include <boost/fusion/algorithm/iteration/iter_fold.hpp> #include <boost/fusion/algorithm/query/any.hpp> +#include <boost/fusion/iterator/distance.hpp> +#include <boost/fusion/iterator/value_of.hpp> +#include <boost/fusion/sequence/intrinsic/begin.hpp> +#include <boost/fusion/sequence/intrinsic/size.hpp> #include <boost/range/algorithm/copy.hpp> #include <boost/range/algorithm/find_if.hpp> #include <boost/range/iterator_range_core.hpp> #include <boost/range/join.hpp> +#include <boost/spirit/include/karma_generate.hpp> +#include <boost/spirit/include/karma_uint.hpp> #include <boost/spirit/include/qi_alternative.hpp> #include <boost/spirit/include/qi_and_predicate.hpp> #include <boost/spirit/include/qi_char.hpp> #include <boost/spirit/include/qi_char_class.hpp> #include <boost/spirit/include/qi_difference.hpp> #include <boost/spirit/include/qi_kleene.hpp> -#include <boost/spirit/include/qi_optional.hpp> #include <boost/spirit/include/qi_parse.hpp> #include <boost/spirit/include/qi_plus.hpp> #include <boost/spirit/include/qi_no_case.hpp> +#include <boost/spirit/include/qi_not_predicate.hpp> #include <boost/spirit/include/qi_raw.hpp> #include <boost/spirit/include/qi_rule.hpp> #include <boost/spirit/include/qi_sequence.hpp> #include <boost/spirit/include/qi_string.hpp> #include <boost/spirit/include/qi_symbols.hpp> #include <boost/spirit/include/qi_uint.hpp> -#include <boost/utility/string_ref.hpp> #include <cassert> -#include <functional> #include <iterator> +#include <limits> #include <tuple> #include <type_traits> @@ -75,6 +82,8 @@ characters without "consuming" the input character. */ namespace { + namespace http = epee::net_utils::http; + // string_ref is only constexpr if length is given template<std::size_t N> constexpr boost::string_ref ceref(const char (&arg)[N]) @@ -82,12 +91,17 @@ namespace return boost::string_ref(arg, N - 1); } - constexpr const auto auth_realm = ceref(u8"monero-wallet-rpc"); + constexpr const auto client_auth_field = ceref(u8"Authorization"); + constexpr const auto server_auth_field = ceref(u8"WWW-authenticate"); + constexpr const auto auth_realm = ceref(u8"monero-rpc"); constexpr const char comma = 44; constexpr const char equal_sign = 61; constexpr const char quote = 34; + constexpr const char zero = 48; constexpr const auto sess_algo = ceref(u8"-sess"); + constexpr const unsigned client_reserve_size = 512; //!< std::string::reserve size for clients + //// Digest Algorithms template<std::size_t N> @@ -147,15 +161,15 @@ namespace }; constexpr const boost::string_ref md5_::name; - //! Digest Algorithms available for HTTP Digest Auth. + //! Digest Algorithms available for HTTP Digest Auth. Sort better algos to the left constexpr const std::tuple<md5_> digest_algorithms{}; - //// Various String Parsing Utilities + //// Various String Utilities struct ascii_tolower_ { template<typename Char> - Char operator()(Char value) const noexcept + constexpr Char operator()(Char value) const noexcept { static_assert(std::is_integral<Char>::value, "only integral types supported"); return (65 <= value && value <= 90) ? (value + 32) : value; @@ -166,34 +180,243 @@ namespace struct ascii_iequal_ { template<typename Char> - bool operator()(Char left, Char right) const noexcept + constexpr bool operator()(Char left, Char right) const noexcept { return ascii_tolower(left) == ascii_tolower(right); } }; constexpr const ascii_iequal_ ascii_iequal{}; + struct http_list_separator_ + { + template<typename Char> + bool operator()(Char value) const noexcept + { + static_assert(std::is_integral<Char>::value, "only integral types supported"); + return boost::spirit::char_encoding::ascii::isascii_(value) && + (value == comma || boost::spirit::char_encoding::ascii::isspace(value)); + } + }; + constexpr const http_list_separator_ http_list_separator{}; + + std::string to_string(boost::iterator_range<const char*> source) + { + return {source.begin(), source.size()}; + } + + template<typename T> + void add_first_field(std::string& str, const char* const name, const T& value) + { + str.append(name); + str.push_back(equal_sign); + boost::copy(value, std::back_inserter(str)); + } + + template<typename T> + void add_field(std::string& str, const char* const name, const T& value) + { + str.push_back(comma); + add_first_field(str, name, value); + } + + template<typename T> + using quoted_result = boost::joined_range< + const boost::joined_range<const boost::string_ref, const T>, const boost::string_ref + >; + + template<typename T> + quoted_result<T> quoted(const T& arg) + { + return boost::range::join(boost::range::join(ceref(u8"\""), arg), ceref(u8"\"")); + } + //// Digest Authentication - - struct auth_request + + template<typename Digest> + typename std::result_of<Digest()>::type generate_a1( + Digest digest, const http::login& creds, const boost::string_ref realm) + { + return digest(creds.username, u8":", realm, u8":", creds.password); + } + + template<typename Digest> + typename std::result_of<Digest()>::type generate_a1( + Digest digest, const http::http_client_auth::session& user) + { + return generate_a1(std::move(digest), user.credentials, user.server.realm); + } + + template<typename T> + void init_client_value(std::string& str, + const boost::string_ref algorithm, const http::http_client_auth::session& user, + const boost::string_ref uri, const T& response) + { + str.append(u8"Digest "); + add_first_field(str, u8"algorithm", algorithm); + add_field(str, u8"nonce", quoted(user.server.nonce)); + add_field(str, u8"realm", quoted(user.server.realm)); + add_field(str, u8"response", quoted(response)); + add_field(str, u8"uri", quoted(uri)); + add_field(str, u8"username", quoted(user.credentials.username)); + if (!user.server.opaque.empty()) + add_field(str, u8"opaque", quoted(user.server.opaque)); + } + + //! Implements superseded algorithm specified in RFC 2069 + template<typename Digest> + struct old_algorithm + { + explicit old_algorithm(Digest digest_) : digest(std::move(digest_)) {} + + std::string operator()(const http::http_client_auth::session& user, + const boost::string_ref method, const boost::string_ref uri) const + { + const auto response = digest( + generate_a1(digest, user), u8":", user.server.nonce, u8":", digest(method, u8":", uri) + ); + std::string out{}; + out.reserve(client_reserve_size); + init_client_value(out, Digest::name, user, uri, response); + return out; + } + private: + Digest digest; + }; + + //! Implements the `qop=auth` algorithm specified in RFC 2617 + template<typename Digest> + struct auth_algorithm + { + explicit auth_algorithm(Digest digest_) : digest(std::move(digest_)) {} + + std::string operator()(const http::http_client_auth::session& user, + const boost::string_ref method, const boost::string_ref uri) const + { + namespace karma = boost::spirit::karma; + using counter_type = decltype(user.counter); + static_assert( + std::numeric_limits<counter_type>::radix == 2, "unexpected radix for counter" + ); + static_assert( + std::numeric_limits<counter_type>::digits <= 32, + "number of digits will cause underflow on padding below" + ); + + std::string out{}; + out.reserve(client_reserve_size); + + karma::generate(std::back_inserter(out), karma::hex(user.counter)); + out.insert(out.begin(), 8 - out.size(), zero); // zero left pad + if (out.size() != 8) + return {}; + + std::array<char, 8> nc{{}}; + boost::copy(out, nc.data()); + const auto response = digest( + generate_a1(digest, user), u8":", user.server.nonce, u8":", nc, u8"::auth:", digest(method, u8":", uri) + ); + out.clear(); + init_client_value(out, Digest::name, user, uri, response); + add_field(out, u8"qop", ceref(u8"auth")); + add_field(out, u8"nc", nc); + return out; + } + + private: + Digest digest; + }; + + //! Processes client "Authorization" and server "WWW-authenticate" HTTP fields + struct auth_message { using iterator = const char*; enum status{ kFail = 0, kStale, kPass }; - static status verify(const std::string& method, const std::string& request, - const epee::net_utils::http::http_auth::session& user) + //! \return Status of the `response` field from the client + static status verify(const boost::string_ref method, const boost::string_ref request, + const http::http_server_auth::session& user) + { + const auto parsed = parse(request); + if (parsed && + boost::equals(parsed->username, user.credentials.username) && + boost::fusion::any(digest_algorithms, has_valid_response{*parsed, user, method})) + { + if (boost::equals(parsed->nonce, user.nonce)) + { + // RFC 2069 format does not verify nc value - allow just once + if (user.counter == 1 || (!parsed->qop.empty() && parsed->counter() == user.counter)) + { + return kPass; + } + } + return kStale; + } + return kFail; + } + + //! \return Information needed to generate client authentication `response`s. + static http::http_client_auth::session::keys extract( + const http::http_response_info& response, const bool is_first) + { + using field = std::pair<std::string, std::string>; + + server_parameters best{}; + + const std::list<field>& fields = response.m_additional_fields; + auto current = fields.begin(); + const auto end = fields.end(); + while (true) + { + current = std::find_if(current, end, [] (const field& value) { + return boost::equals(server_auth_field, value.first, ascii_iequal); + }); + if (current == end) + break; + + const auto parsed = parse(current->second); + if (parsed) + { + server_parameters local_best = parsed->algorithm.empty() ? + server_parameters{*parsed, boost::fusion::find<md5_>(digest_algorithms)} : + boost::fusion::iter_fold(digest_algorithms, server_parameters{}, matches_algorithm{*parsed}); + + if (local_best.index < best.index) + best = std::move(local_best); + } + ++current; + } + if (is_first || boost::equals(best.stale, ceref(u8"true"), ascii_iequal)) + return best.take(); + return {}; // authentication failed with bad user/pass + } + + private: + explicit auth_message() + : algorithm() + , cnonce() + , nc() + , nonce() + , qop() + , realm() + , response() + , stale() + , uri() + , username() { + } + + static boost::optional<auth_message> parse(const boost::string_ref request) { struct parser { - using field_parser = std::function<bool(const parser&, iterator&, iterator, auth_request&)>; + using field_parser = std::function<bool(const parser&, iterator&, iterator, auth_message&)>; - explicit parser() : field_table(), skip_whitespace(), header(), token(), fields() { + explicit parser() : field_table(), skip_whitespace(), header(), quoted_string(), token(), fields() { using namespace std::placeholders; namespace qi = boost::spirit::qi; struct parse_nc { - bool operator()(const parser&, iterator& current, const iterator end, auth_request& result) const + bool operator()(const parser&, iterator& current, const iterator end, auth_message& result) const { return qi::parse( current, end, @@ -212,19 +435,19 @@ namespace }; struct parse_string { - bool operator()(const parser&, iterator& current, const iterator end, + bool operator()(const parser& parse, iterator& current, const iterator end, boost::iterator_range<iterator>& result) const { - return qi::parse( - current, end, - (qi::lit(quote) >> qi::raw[+(u8"\\\"" | (qi::ascii::char_ - quote))] >> qi::lit(quote)), - result - ); + return qi::parse(current, end, parse.quoted_string, result); + } + bool operator()(const parser& parse, iterator& current, const iterator end) const + { + return qi::parse(current, end, parse.quoted_string); } }; struct parse_response { - bool operator()(const parser&, iterator& current, const iterator end, auth_request& result) const + bool operator()(const parser&, iterator& current, const iterator end, auth_message& result) const { using byte = qi::uint_parser<std::uint8_t, 16, 2, 2>; return qi::parse( @@ -236,38 +459,41 @@ namespace }; field_table.add - (u8"algorithm", std::bind(parse_token{}, _1, _2, _3, std::bind(&auth_request::algorithm, _4))) - (u8"cnonce", std::bind(parse_string{}, _1, _2, _3, std::bind(&auth_request::cnonce, _4))) + (u8"algorithm", std::bind(parse_token{}, _1, _2, _3, std::bind(&auth_message::algorithm, _4))) + (u8"cnonce", std::bind(parse_string{}, _1, _2, _3, std::bind(&auth_message::cnonce, _4))) + (u8"domain", std::bind(parse_string{}, _1, _2, _3)) // ignore field (u8"nc", parse_nc{}) - (u8"nonce", std::bind(parse_string{}, _1, _2, _3, std::bind(&auth_request::nonce, _4))) - (u8"qop", std::bind(parse_token{}, _1, _2, _3, std::bind(&auth_request::qop, _4))) - (u8"realm", std::bind(parse_string{}, _1, _2, _3, std::bind(&auth_request::realm, _4))) + (u8"nonce", std::bind(parse_string{}, _1, _2, _3, std::bind(&auth_message::nonce, _4))) + (u8"opaque", std::bind(parse_string{}, _1, _2, _3, std::bind(&auth_message::opaque, _4))) + (u8"qop", std::bind(parse_token{}, _1, _2, _3, std::bind(&auth_message::qop, _4))) + (u8"realm", std::bind(parse_string{}, _1, _2, _3, std::bind(&auth_message::realm, _4))) (u8"response", parse_response{}) - (u8"uri", std::bind(parse_string{}, _1, _2, _3, std::bind(&auth_request::uri, _4))) - (u8"username", std::bind(parse_string{}, _1, _2, _3, std::bind(&auth_request::username, _4))); + (u8"stale", std::bind(parse_token{}, _1, _2, _3, std::bind(&auth_message::stale, _4))) + (u8"uri", std::bind(parse_string{}, _1, _2, _3, std::bind(&auth_message::uri, _4))) + (u8"username", std::bind(parse_string{}, _1, _2, _3, std::bind(&auth_message::username, _4))); skip_whitespace = *(&qi::ascii::char_ >> qi::ascii::space); header = skip_whitespace >> qi::ascii::no_case[u8"digest"] >> skip_whitespace; + quoted_string = (qi::lit(quote) >> qi::raw[+(u8"\\\"" | (qi::ascii::char_ - quote))] >> qi::lit(quote)); token = - -qi::lit(quote) >> - qi::raw[+(&qi::ascii::char_ >> (qi::ascii::graph - qi::ascii::char_(u8"()<>@,;:\\\"/[]?={}")))] >> - -qi::lit(quote); + (!qi::lit(quote) >> qi::raw[+(&qi::ascii::char_ >> (qi::ascii::graph - qi::ascii::char_(u8"()<>@,;:\\\"/[]?={}")))]) | + quoted_string; fields = field_table >> skip_whitespace >> equal_sign >> skip_whitespace; } - boost::optional<auth_request> operator()(const std::string& method, const std::string& request) const + boost::optional<auth_message> operator()(const boost::string_ref request) const { namespace qi = boost::spirit::qi; - iterator current = request.data(); - const iterator end = current + request.size(); + iterator current = request.begin(); + const iterator end = request.end(); if (!qi::parse(current, end, header)) { return boost::none; } - auth_request info(method); + auth_message info{}; field_parser null_parser{}; std::reference_wrapper<const field_parser> field = null_parser; @@ -288,26 +514,13 @@ namespace > field_table; boost::spirit::qi::rule<iterator> skip_whitespace; boost::spirit::qi::rule<iterator> header; + boost::spirit::qi::rule<iterator, boost::iterator_range<iterator>()> quoted_string; boost::spirit::qi::rule<iterator, boost::iterator_range<iterator>()> token; boost::spirit::qi::rule<iterator, std::reference_wrapper<const field_parser>()> fields; }; // parser - static const parser parse; - return do_verify(parse(method, request), user); - } - - private: - explicit auth_request(const std::string& method_) - : algorithm() - , cnonce() - , method(method_) - , nc() - , nonce() - , qop() - , realm() - , response() - , uri() - , username() { + static const parser parse_; + return parse_(request); } struct has_valid_response @@ -326,12 +539,6 @@ namespace ); } - template<typename Digest> - typename std::result_of<Digest()>::type generate_auth(Digest digest) const - { - return digest(request.method, u8":", request.uri); - } - template<typename Result> bool check(const Result& result) const { @@ -344,96 +551,130 @@ namespace if (boost::starts_with(request.algorithm, Digest::name, ascii_iequal) || (request.algorithm.empty() && std::is_same<md5_, Digest>::value)) { - auto key = digest(user.credentials.username, u8":", auth_realm, u8":", user.credentials.password); - + auto key = generate_a1(digest, user.credentials, auth_realm); if (boost::ends_with(request.algorithm, sess_algo, ascii_iequal)) { key = digest(key, u8":", request.nonce, u8":", request.cnonce); } + auto auth = digest(method, u8":", request.uri); if (request.qop.empty()) { - return check(generate_old_response(digest, std::move(key), generate_auth(digest))); + return check(generate_old_response(std::move(digest), std::move(key), std::move(auth))); } else if (boost::equals(ceref(u8"auth"), request.qop, ascii_iequal)) { - return check(generate_new_response(digest, std::move(key), generate_auth(digest))); + return check(generate_new_response(std::move(digest), std::move(key), std::move(auth))); } } return false; } - const auth_request& request; - const epee::net_utils::http::http_auth::session& user; + const auth_message& request; + const http::http_server_auth::session& user; + const boost::string_ref method; }; - static status do_verify(const boost::optional<auth_request>& request, - const epee::net_utils::http::http_auth::session& user) + boost::optional<std::uint32_t> counter() const + { + namespace qi = boost::spirit::qi; + using hex = qi::uint_parser<std::uint32_t, 16>; + std::uint32_t value = 0; + const bool converted = qi::parse(nc.begin(), nc.end(), hex{}, value); + return boost::make_optional(converted, value); + } + + struct server_parameters { - if (request && - boost::equals(request->username, user.credentials.username) && - boost::fusion::any(digest_algorithms, has_valid_response{*request, user})) + server_parameters() + : nonce(), opaque(), realm(), stale(), value_generator() + , index(boost::fusion::size(digest_algorithms)) + {} + + template<typename DigestIter> + explicit server_parameters(const auth_message& request, const DigestIter& digest) + : nonce(request.nonce) + , opaque(request.opaque) + , stale(request.stale) + , realm(request.realm) + , value_generator() + , index(boost::fusion::distance(boost::fusion::begin(digest_algorithms), digest)) { - if (boost::equals(request->nonce, user.nonce)) + using digest_type = typename boost::fusion::result_of::value_of<DigestIter>::type; + + // debug check internal state of the auth_message class + assert( + (std::is_same<digest_type, md5_>::value) || + boost::equals((*digest).name, request.algorithm, ascii_iequal) + ); + if (request.qop.empty()) + value_generator = old_algorithm<digest_type>{*digest}; + else { - // RFC 2069 format does not verify nc value - allow just once - if (user.counter == 1 || (!request->qop.empty() && request->counter() == user.counter)) + for (auto elem = boost::make_split_iterator(request.qop, boost::token_finder(http_list_separator)); + !elem.eof(); + ++elem) { - return kPass; + if (boost::equals(ceref(u8"auth"), *elem, ascii_iequal)) + { + value_generator = auth_algorithm<digest_type>{*digest}; + break; + } } + if (!value_generator) // no supported qop mode + index = boost::fusion::size(digest_algorithms); } - return kStale; } - return kFail; - } - boost::optional<std::uint32_t> counter() const + http::http_client_auth::session::keys take() + { + return {to_string(nonce), to_string(opaque), to_string(realm), std::move(value_generator)}; + } + + boost::iterator_range<iterator> nonce; + boost::iterator_range<iterator> opaque; + boost::iterator_range<iterator> realm; + boost::iterator_range<iterator> stale; + http::http_client_auth::session::keys::algorithm value_generator; + unsigned index; + }; + + struct matches_algorithm { - namespace qi = boost::spirit::qi; - using hex = qi::uint_parser<std::uint32_t, 16>; - std::uint32_t value = 0; - const bool converted = qi::parse(nc.begin(), nc.end(), hex{}, value); - return boost::make_optional(converted, value); - } + template<typename DigestIter> + server_parameters operator()(server_parameters current, const DigestIter& digest) const + { + if (!current.value_generator) + { + if (boost::equals(response.algorithm, (*digest).name, ascii_iequal)) + { + current = server_parameters{response, digest}; + } + } + return current; + } + const auth_message& response; + }; + boost::iterator_range<iterator> algorithm; boost::iterator_range<iterator> cnonce; - boost::string_ref method; boost::iterator_range<iterator> nc; boost::iterator_range<iterator> nonce; + boost::iterator_range<iterator> opaque; boost::iterator_range<iterator> qop; boost::iterator_range<iterator> realm; boost::iterator_range<iterator> response; + boost::iterator_range<iterator> stale; boost::iterator_range<iterator> uri; boost::iterator_range<iterator> username; - }; // auth_request + }; // auth_message struct add_challenge { - template<typename T> - static void add_field(std::string& str, const char* const name, const T& value) - { - str.push_back(comma); - str.append(name); - str.push_back(equal_sign); - boost::range::copy(value, std::back_inserter(str)); - } - - template<typename T> - using quoted_result = boost::joined_range< - const boost::joined_range<const boost::string_ref, const T>, const boost::string_ref - >; - - template<typename T> - static quoted_result<T> quoted(const T& arg) - { - return boost::range::join(boost::range::join(ceref(u8"\""), arg), ceref(u8"\"")); - } - template<typename Digest> void operator()(const Digest& digest) const { - static constexpr const auto fname = ceref(u8"WWW-authenticate"); static constexpr const auto fvalue = ceref(u8"Digest qop=\"auth\""); for (unsigned i = 0; i < 2; ++i) @@ -448,17 +689,16 @@ namespace add_field(out, u8"nonce", quoted(nonce)); add_field(out, u8"stale", is_stale ? ceref("true") : ceref("false")); - fields.push_back(std::make_pair(std::string(fname), std::move(out))); + fields.push_back(std::make_pair(std::string(server_auth_field), std::move(out))); } } - const std::string& nonce; + const boost::string_ref nonce; std::list<std::pair<std::string, std::string>>& fields; const bool is_stale; }; - epee::net_utils::http::http_response_info create_digest_response( - const std::string& nonce, const bool is_stale) + http::http_response_info create_digest_response(const boost::string_ref nonce, const bool is_stale) { epee::net_utils::http::http_response_info rc{}; rc.m_response_code = 401; @@ -481,35 +721,35 @@ namespace epee { namespace http { - http_auth::http_auth(login credentials) + http_server_auth::http_server_auth(login credentials) : user(session{std::move(credentials)}) { } - boost::optional<http_response_info> http_auth::process(const http_request_info& request) + boost::optional<http_response_info> http_server_auth::do_get_response(const http_request_info& request) { assert(user); using field = std::pair<std::string, std::string>; const std::list<field>& fields = request.m_header_info.m_etc_fields; const auto auth = boost::find_if(fields, [] (const field& value) { - return boost::equals(ceref(u8"authorization"), value.first, ascii_iequal); + return boost::equals(client_auth_field, value.first, ascii_iequal); }); bool is_stale = false; if (auth != fields.end()) { ++(user->counter); - switch (auth_request::verify(request.m_http_method_str, auth->second, *user)) + switch (auth_message::verify(request.m_http_method_str, auth->second, *user)) { - case auth_request::kPass: + case auth_message::kPass: return boost::none; - case auth_request::kStale: + case auth_message::kStale: is_stale = true; break; default: - case auth_request::kFail: + case auth_message::kFail: break; } } @@ -521,6 +761,35 @@ namespace epee } return create_digest_response(user->nonce, is_stale); } + + http_client_auth::http_client_auth(login credentials) + : user(session{std::move(credentials)}) { + } + + http_client_auth::status http_client_auth::do_handle_401(const http_response_info& response) + { + assert(user); + const bool first_auth = (user->counter == 0); + user->server = auth_message::extract(response, first_auth); + if (user->server.generator) + { + user->counter = 0; + return kSuccess; + } + return first_auth ? kParseFailure : kBadPassword; + } + + boost::optional<std::pair<std::string, std::string>> http_client_auth::do_get_auth_field( + const boost::string_ref method, const boost::string_ref uri) + { + assert(user); + if (user->server.generator) + { + ++(user->counter); + return std::make_pair(std::string(client_auth_field), user->server.generator(*user, method, uri)); + } + return boost::none; + } } } } diff --git a/src/cryptonote_core/blockchain.cpp b/src/cryptonote_core/blockchain.cpp index 5f9d6937b..e27261c46 100644 --- a/src/cryptonote_core/blockchain.cpp +++ b/src/cryptonote_core/blockchain.cpp @@ -1778,7 +1778,7 @@ bool Blockchain::get_outs(const COMMAND_RPC_GET_OUTPUTS_BIN::request& req, COMMA tx_out_index toi = m_db->get_output_tx_and_index(i.amount, i.index); bool unlocked = is_tx_spendtime_unlocked(m_db->get_tx_unlock_time(toi.first)); - res.outs.push_back({od.pubkey, od.commitment, unlocked}); + res.outs.push_back({od.pubkey, od.commitment, unlocked, od.height, toi.first}); } return true; } diff --git a/src/rpc/core_rpc_server.cpp b/src/rpc/core_rpc_server.cpp index 6ca01ed2c..558031f52 100644 --- a/src/rpc/core_rpc_server.cpp +++ b/src/rpc/core_rpc_server.cpp @@ -300,6 +300,8 @@ namespace cryptonote outkey.key = epee::string_tools::pod_to_hex(i.key); outkey.mask = epee::string_tools::pod_to_hex(i.mask); outkey.unlocked = i.unlocked; + outkey.height = i.height; + outkey.txid = epee::string_tools::pod_to_hex(i.txid); } res.status = CORE_RPC_STATUS_OK; diff --git a/src/rpc/core_rpc_server_commands_defs.h b/src/rpc/core_rpc_server_commands_defs.h index c08e43066..a4edc7538 100644 --- a/src/rpc/core_rpc_server_commands_defs.h +++ b/src/rpc/core_rpc_server_commands_defs.h @@ -49,7 +49,7 @@ namespace cryptonote // advance which version they will stop working with // Don't go over 32767 for any of these #define CORE_RPC_VERSION_MAJOR 1 -#define CORE_RPC_VERSION_MINOR 3 +#define CORE_RPC_VERSION_MINOR 4 #define CORE_RPC_VERSION (((CORE_RPC_VERSION_MAJOR)<<16)|(CORE_RPC_VERSION_MINOR)) struct COMMAND_RPC_GET_HEIGHT @@ -329,11 +329,15 @@ namespace cryptonote crypto::public_key key; rct::key mask; bool unlocked; + uint64_t height; + crypto::hash txid; BEGIN_KV_SERIALIZE_MAP() KV_SERIALIZE_VAL_POD_AS_BLOB(key) KV_SERIALIZE_VAL_POD_AS_BLOB(mask) KV_SERIALIZE(unlocked) + KV_SERIALIZE(height) + KV_SERIALIZE_VAL_POD_AS_BLOB(txid) END_KV_SERIALIZE_MAP() }; @@ -365,11 +369,15 @@ namespace cryptonote std::string key; std::string mask; bool unlocked; + uint64_t height; + std::string txid; BEGIN_KV_SERIALIZE_MAP() KV_SERIALIZE(key) KV_SERIALIZE(mask) KV_SERIALIZE(unlocked) + KV_SERIALIZE(height) + KV_SERIALIZE(txid) END_KV_SERIALIZE_MAP() }; diff --git a/src/simplewallet/simplewallet.cpp b/src/simplewallet/simplewallet.cpp index 088d5e2ac..54c717503 100644 --- a/src/simplewallet/simplewallet.cpp +++ b/src/simplewallet/simplewallet.cpp @@ -371,6 +371,17 @@ bool simple_wallet::set_always_confirm_transfers(const std::vector<std::string> return true; } +bool simple_wallet::set_print_ring_members(const std::vector<std::string> &args/* = std::vector<std::string>()*/) +{ + const auto pwd_container = get_and_verify_password(); + if (pwd_container) + { + m_wallet->print_ring_members(is_it_true(args[1])); + m_wallet->rewrite(m_wallet_file, pwd_container->password()); + } + return true; +} + bool simple_wallet::set_store_tx_info(const std::vector<std::string> &args/* = std::vector<std::string>()*/) { if (m_wallet->watch_only()) @@ -570,7 +581,7 @@ simple_wallet::simple_wallet() m_cmd_binder.set_handler("viewkey", boost::bind(&simple_wallet::viewkey, this, _1), tr("Display private view key")); m_cmd_binder.set_handler("spendkey", boost::bind(&simple_wallet::spendkey, this, _1), tr("Display private spend key")); m_cmd_binder.set_handler("seed", boost::bind(&simple_wallet::seed, this, _1), tr("Display Electrum-style mnemonic seed")); - m_cmd_binder.set_handler("set", boost::bind(&simple_wallet::set_variable, this, _1), tr("Available options: seed language - set wallet seed language; always-confirm-transfers <1|0> - whether to confirm unsplit txes; store-tx-info <1|0> - whether to store outgoing tx info (destination address, payment ID, tx secret key) for future reference; default-mixin <n> - set default mixin (default is 4); auto-refresh <1|0> - whether to automatically sync new blocks from the daemon; refresh-type <full|optimize-coinbase|no-coinbase|default> - set wallet refresh behaviour; priority [1|2|3] - normal/elevated/priority fee; confirm-missing-payment-id <1|0>")); + m_cmd_binder.set_handler("set", boost::bind(&simple_wallet::set_variable, this, _1), tr("Available options: seed language - set wallet seed language; always-confirm-transfers <1|0> - whether to confirm unsplit txes; print-ring-members <1|0> - whether to print detailed information about ring members during confirmation; store-tx-info <1|0> - whether to store outgoing tx info (destination address, payment ID, tx secret key) for future reference; default-mixin <n> - set default mixin (default is 4); auto-refresh <1|0> - whether to automatically sync new blocks from the daemon; refresh-type <full|optimize-coinbase|no-coinbase|default> - set wallet refresh behaviour; priority [1|2|3] - normal/elevated/priority fee; confirm-missing-payment-id <1|0>")); m_cmd_binder.set_handler("rescan_spent", boost::bind(&simple_wallet::rescan_spent, this, _1), tr("Rescan blockchain for spent outputs")); m_cmd_binder.set_handler("get_tx_key", boost::bind(&simple_wallet::get_tx_key, this, _1), tr("Get transaction key (r) for a given <txid>")); m_cmd_binder.set_handler("check_tx_key", boost::bind(&simple_wallet::check_tx_key, this, _1), tr("Check amount going to <address> in <txid>")); @@ -596,6 +607,7 @@ bool simple_wallet::set_variable(const std::vector<std::string> &args) { success_msg_writer() << "seed = " << m_wallet->get_seed_language(); success_msg_writer() << "always-confirm-transfers = " << m_wallet->always_confirm_transfers(); + success_msg_writer() << "print-ring-members = " << m_wallet->print_ring_members(); success_msg_writer() << "store-tx-info = " << m_wallet->store_tx_info(); success_msg_writer() << "default-mixin = " << m_wallet->default_mixin(); success_msg_writer() << "auto-refresh = " << m_wallet->auto_refresh(); @@ -632,6 +644,19 @@ bool simple_wallet::set_variable(const std::vector<std::string> &args) return true; } } + else if (args[0] == "print-ring-members") + { + if (args.size() <= 1) + { + fail_msg_writer() << tr("set print-ring-members: needs an argument (0 or 1)"); + return true; + } + else + { + set_print_ring_members(args); + return true; + } + } else if (args[0] == "store-tx-info") { if (args.size() <= 1) @@ -1119,10 +1144,12 @@ bool simple_wallet::handle_command_line(const boost::program_options::variables_ return true; } //---------------------------------------------------------------------------------------------------- -bool simple_wallet::try_connect_to_daemon(bool silent) +bool simple_wallet::try_connect_to_daemon(bool silent, uint32_t* version) { - uint32_t version = 0; - if (!m_wallet->check_connection(&version)) + uint32_t version_ = 0; + if (!version) + version = &version_; + if (!m_wallet->check_connection(version)) { if (!silent) fail_msg_writer() << tr("wallet failed to connect to daemon: ") << m_wallet->get_daemon_address() << ". " << @@ -1130,10 +1157,10 @@ bool simple_wallet::try_connect_to_daemon(bool silent) "Please make sure daemon is running or restart the wallet with the correct daemon address."); return false; } - if (!m_allow_mismatched_daemon_version && ((version >> 16) != CORE_RPC_VERSION_MAJOR)) + if (!m_allow_mismatched_daemon_version && ((*version >> 16) != CORE_RPC_VERSION_MAJOR)) { if (!silent) - fail_msg_writer() << boost::format(tr("Daemon uses a different RPC major version (%u) than the wallet (%u): %s. Either update one of them, or use --allow-mismatched-daemon-version.")) % (version>>16) % CORE_RPC_VERSION_MAJOR % m_wallet->get_daemon_address(); + fail_msg_writer() << boost::format(tr("Daemon uses a different RPC major version (%u) than the wallet (%u): %s. Either update one of them, or use --allow-mismatched-daemon-version.")) % (*version>>16) % CORE_RPC_VERSION_MAJOR % m_wallet->get_daemon_address(); return false; } return true; @@ -1865,6 +1892,108 @@ bool simple_wallet::rescan_spent(const std::vector<std::string> &args) return true; } //---------------------------------------------------------------------------------------------------- +bool simple_wallet::print_ring_members(const std::vector<tools::wallet2::pending_tx>& ptx_vector, std::ostream& ostr) +{ + uint32_t version; + if (!try_connect_to_daemon(false, &version)) + { + fail_msg_writer() << tr("failed to connect to the daemon"); + return false; + } + // available for RPC version 1.4 or higher + if (version < 0x10004) + return true; + std::string err; + uint64_t blockchain_height = get_daemon_blockchain_height(err); + if (!err.empty()) + { + fail_msg_writer() << tr("failed to get blockchain height: ") << err; + return false; + } + // for each transaction + for (size_t n = 0; n < ptx_vector.size(); ++n) + { + const cryptonote::transaction& tx = ptx_vector[n].tx; + const tools::wallet2::tx_construction_data& construction_data = ptx_vector[n].construction_data; + ostr << boost::format(tr("\nTransaction %llu/%llu: txid=%s")) % (n + 1) % ptx_vector.size() % cryptonote::get_transaction_hash(tx); + // for each input + std::vector<int> spent_key_height(tx.vin.size()); + std::vector<crypto::hash> spent_key_txid (tx.vin.size()); + for (size_t i = 0; i < tx.vin.size(); ++i) + { + if (tx.vin[i].type() != typeid(cryptonote::txin_to_key)) + continue; + const cryptonote::txin_to_key& in_key = boost::get<cryptonote::txin_to_key>(tx.vin[i]); + const cryptonote::tx_source_entry& source = construction_data.sources[i]; + ostr << boost::format(tr("\nInput %llu/%llu: amount=%s")) % (i + 1) % tx.vin.size() % print_money(source.amount); + // convert relative offsets of ring member keys into absolute offsets (indices) associated with the amount + std::vector<uint64_t> absolute_offsets = cryptonote::relative_output_offsets_to_absolute(in_key.key_offsets); + // get block heights from which those ring member keys originated + COMMAND_RPC_GET_OUTPUTS_BIN::request req = AUTO_VAL_INIT(req); + req.outputs.resize(absolute_offsets.size()); + for (size_t j = 0; j < absolute_offsets.size(); ++j) + { + req.outputs[j].amount = in_key.amount; + req.outputs[j].index = absolute_offsets[j]; + } + COMMAND_RPC_GET_OUTPUTS_BIN::response res = AUTO_VAL_INIT(res); + bool r = net_utils::invoke_http_bin_remote_command2(m_wallet->get_daemon_address() + "/get_outs.bin", req, res, m_http_client); + err = interpret_rpc_response(r, res.status); + if (!err.empty()) + { + fail_msg_writer() << tr("failed to get output: ") << err; + return false; + } + // make sure that returned block heights are less than blockchain height + for (auto& res_out : res.outs) + { + if (res_out.height >= blockchain_height) + { + fail_msg_writer() << tr("output key's originating block height shouldn't be higher than the blockchain height"); + return false; + } + } + ostr << tr("\nOriginating block heights: "); + for (size_t j = 0; j < absolute_offsets.size(); ++j) + ostr << tr(j == source.real_output ? " *" : " ") << res.outs[j].height; + spent_key_height[i] = res.outs[source.real_output].height; + spent_key_txid [i] = res.outs[source.real_output].txid; + // visualize the distribution, using the code by moneroexamples onion-monero-viewer + const uint64_t resolution = 79; + std::string ring_str(resolution, '_'); + for (size_t j = 0; j < absolute_offsets.size(); ++j) + { + uint64_t pos = (res.outs[j].height * resolution) / blockchain_height; + ring_str[pos] = 'o'; + } + uint64_t pos = (res.outs[source.real_output].height * resolution) / blockchain_height; + ring_str[pos] = '*'; + ostr << tr("\n|") << ring_str << tr("|\n"); + } + // warn if rings contain keys originating from the same tx or temporally very close block heights + bool are_keys_from_same_tx = false; + bool are_keys_from_close_height = false; + for (size_t i = 0; i < tx.vin.size(); ++i) { + for (size_t j = i + 1; j < tx.vin.size(); ++j) + { + if (spent_key_txid[i] == spent_key_txid[j]) + are_keys_from_same_tx = true; + if (std::abs(spent_key_height[i] - spent_key_height[j]) < 5) + are_keys_from_close_height = true; + } + } + if (are_keys_from_same_tx || are_keys_from_close_height) + { + ostr + << tr("\nWarning: Some input keys being spent are from ") + << tr(are_keys_from_same_tx ? "the same transaction" : "blocks that are temporally very close") + << tr(", which can break the anonymity of ring signature. Make sure this is intentional!"); + } + ostr << ENDL; + } + return true; +} +//---------------------------------------------------------------------------------------------------- bool simple_wallet::transfer_main(int transfer_type, const std::vector<std::string> &args_) { if (!try_connect_to_daemon()) @@ -2075,7 +2204,12 @@ bool simple_wallet::transfer_main(int transfer_type, const std::vector<std::stri float days = locked_blocks / 720.0f; prompt << boost::format(tr(".\nThis transaction will unlock on block %llu, in approximately %s days (assuming 2 minutes per block)")) % ((unsigned long long)unlock_block) % days; } - prompt << tr(".") << ENDL << tr("Is this okay? (Y/Yes/N/No): "); + if (m_wallet->print_ring_members()) + { + if (!print_ring_members(ptx_vector, prompt)) + return true; + } + prompt << ENDL << tr("Is this okay? (Y/Yes/N/No): "); std::string accepted = command_line::input_line(prompt.str()); if (std::cin.eof()) @@ -2503,19 +2637,21 @@ bool simple_wallet::sweep_all(const std::vector<std::string> &args_) total_sent += m_wallet->get_transfer_details(i).amount(); } - std::string prompt_str; + std::ostringstream prompt; + if (!print_ring_members(ptx_vector, prompt)) + return true; if (ptx_vector.size() > 1) { - prompt_str = (boost::format(tr("Sweeping %s in %llu transactions for a total fee of %s. Is this okay? (Y/Yes/N/No): ")) % + prompt << boost::format(tr("Sweeping %s in %llu transactions for a total fee of %s. Is this okay? (Y/Yes/N/No): ")) % print_money(total_sent) % ((unsigned long long)ptx_vector.size()) % - print_money(total_fee)).str(); + print_money(total_fee); } else { - prompt_str = (boost::format(tr("Sweeping %s for a total fee of %s. Is this okay? (Y/Yes/N/No)")) % + prompt << boost::format(tr("Sweeping %s for a total fee of %s. Is this okay? (Y/Yes/N/No)")) % print_money(total_sent) % - print_money(total_fee)).str(); + print_money(total_fee); } - std::string accepted = command_line::input_line(prompt_str); + std::string accepted = command_line::input_line(prompt.str()); if (std::cin.eof()) return true; if (!command_line::is_yes(accepted)) @@ -3541,7 +3677,7 @@ bool simple_wallet::address_book(const std::vector<std::string> &args/* = std::v cryptonote::account_public_address address; bool has_payment_id; crypto::hash8 payment_id8; - if (!get_address_from_str(args[1], address, has_payment_id, payment_id8)) + if(!tools::dns_utils::get_account_address_from_str_or_url(address, has_payment_id, payment_id8, m_wallet->testnet(), args[1])) { fail_msg_writer() << tr("failed to parse address"); return true; diff --git a/src/simplewallet/simplewallet.h b/src/simplewallet/simplewallet.h index 753bca74d..318d8d7e0 100644 --- a/src/simplewallet/simplewallet.h +++ b/src/simplewallet/simplewallet.h @@ -106,6 +106,7 @@ namespace cryptonote */ bool seed_set_language(const std::vector<std::string> &args = std::vector<std::string>()); bool set_always_confirm_transfers(const std::vector<std::string> &args = std::vector<std::string>()); + bool set_print_ring_members(const std::vector<std::string> &args = std::vector<std::string>()); bool set_store_tx_info(const std::vector<std::string> &args = std::vector<std::string>()); bool set_default_mixin(const std::vector<std::string> &args = std::vector<std::string>()); bool set_auto_refresh(const std::vector<std::string> &args = std::vector<std::string>()); @@ -160,11 +161,12 @@ namespace cryptonote bool show_transfer(const std::vector<std::string> &args); uint64_t get_daemon_blockchain_height(std::string& err); - bool try_connect_to_daemon(bool silent = false); + bool try_connect_to_daemon(bool silent = false, uint32_t* version = nullptr); bool ask_wallet_create_if_needed(); bool accept_loaded_tx(const std::function<size_t()> get_num_txes, const std::function<const tools::wallet2::tx_construction_data&(size_t)> &get_tx, const std::string &extra_message = std::string()); bool accept_loaded_tx(const tools::wallet2::unsigned_tx_set &txs); bool accept_loaded_tx(const tools::wallet2::signed_tx_set &txs); + bool print_ring_members(const std::vector<tools::wallet2::pending_tx>& ptx_vector, std::ostream& ostr); /*! * \brief Prints the seed with a nice message diff --git a/src/wallet/api/wallet_manager.cpp b/src/wallet/api/wallet_manager.cpp index 6b48caf1d..48faa3183 100644 --- a/src/wallet/api/wallet_manager.cpp +++ b/src/wallet/api/wallet_manager.cpp @@ -346,7 +346,7 @@ double WalletManagerImpl::miningHashRate() const cryptonote::COMMAND_RPC_MINING_STATUS::response mres; epee::net_utils::http::http_simple_client http_client; - if (!epee::net_utils::invoke_http_json_remote_command2(m_daemonAddress + "/getinfo", mreq, mres, http_client)) + if (!epee::net_utils::invoke_http_json_remote_command2(m_daemonAddress + "/mining_status", mreq, mres, http_client)) return 0.0; if (!mres.active) return 0.0; @@ -384,6 +384,42 @@ uint64_t WalletManagerImpl::blockTarget() const return ires.target; } +bool WalletManagerImpl::isMining() const +{ + cryptonote::COMMAND_RPC_MINING_STATUS::request mreq; + cryptonote::COMMAND_RPC_MINING_STATUS::response mres; + + epee::net_utils::http::http_simple_client http_client; + if (!epee::net_utils::invoke_http_json_remote_command2(m_daemonAddress + "/mining_status", mreq, mres, http_client)) + return false; + return mres.active; +} + +bool WalletManagerImpl::startMining(const std::string &address, uint32_t threads) +{ + cryptonote::COMMAND_RPC_START_MINING::request mreq; + cryptonote::COMMAND_RPC_START_MINING::response mres; + + mreq.miner_address = address; + mreq.threads_count = threads; + + epee::net_utils::http::http_simple_client http_client; + if (!epee::net_utils::invoke_http_json_remote_command2(m_daemonAddress + "/start_mining", mreq, mres, http_client)) + return false; + return mres.status == CORE_RPC_STATUS_OK; +} + +bool WalletManagerImpl::stopMining() +{ + cryptonote::COMMAND_RPC_STOP_MINING::request mreq; + cryptonote::COMMAND_RPC_STOP_MINING::response mres; + + epee::net_utils::http::http_simple_client http_client; + if (!epee::net_utils::invoke_http_json_remote_command2(m_daemonAddress + "/stop_mining", mreq, mres, http_client)) + return false; + return mres.status == CORE_RPC_STATUS_OK; +} + std::string WalletManagerImpl::resolveOpenAlias(const std::string &address, bool &dnssec_valid) const { std::vector<std::string> addresses = tools::dns_utils::addresses_from_url(address, dnssec_valid); diff --git a/src/wallet/api/wallet_manager.h b/src/wallet/api/wallet_manager.h index 01752f69b..ca9570254 100644 --- a/src/wallet/api/wallet_manager.h +++ b/src/wallet/api/wallet_manager.h @@ -54,6 +54,9 @@ public: double miningHashRate() const; void hardForkInfo(uint8_t &version, uint64_t &earliest_height) const; uint64_t blockTarget() const; + bool isMining() const; + bool startMining(const std::string &address, uint32_t threads = 1); + bool stopMining(); std::string resolveOpenAlias(const std::string &address, bool &dnssec_valid) const; private: diff --git a/src/wallet/wallet2.cpp b/src/wallet/wallet2.cpp index 1550787e5..b98d6a97a 100644 --- a/src/wallet/wallet2.cpp +++ b/src/wallet/wallet2.cpp @@ -1808,6 +1808,9 @@ bool wallet2::store_keys(const std::string& keys_file_name, const std::string& p value2.SetInt(m_always_confirm_transfers ? 1 :0); json.AddMember("always_confirm_transfers", value2, json.GetAllocator()); + value2.SetInt(m_print_ring_members ? 1 :0); + json.AddMember("print_ring_members", value2, json.GetAllocator()); + value2.SetInt(m_store_tx_info ? 1 :0); json.AddMember("store_tx_info", value2, json.GetAllocator()); @@ -1890,6 +1893,7 @@ bool wallet2::load_keys(const std::string& keys_file_name, const std::string& pa is_old_file_format = true; m_watch_only = false; m_always_confirm_transfers = false; + m_print_ring_members = false; m_default_mixin = 0; m_default_priority = 0; m_auto_refresh = true; @@ -1920,6 +1924,8 @@ bool wallet2::load_keys(const std::string& keys_file_name, const std::string& pa m_watch_only = field_watch_only; GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, always_confirm_transfers, int, Int, false, true); m_always_confirm_transfers = field_always_confirm_transfers; + GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, print_ring_members, int, Int, false, true); + m_print_ring_members = field_print_ring_members; GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, store_tx_keys, int, Int, false, true); GET_FIELD_FROM_JSON_RETURN_ON_ERROR(json, store_tx_info, int, Int, false, true); m_store_tx_info = ((field_store_tx_keys != 0) || (field_store_tx_info != 0)); diff --git a/src/wallet/wallet2.h b/src/wallet/wallet2.h index d0739ba06..37609cd2f 100644 --- a/src/wallet/wallet2.h +++ b/src/wallet/wallet2.h @@ -98,7 +98,7 @@ namespace tools }; private: - wallet2(const wallet2&) : m_run(true), m_callback(0), m_testnet(false), m_always_confirm_transfers(true), m_store_tx_info(true), m_default_mixin(0), m_default_priority(0), m_refresh_type(RefreshOptimizeCoinbase), m_auto_refresh(true), m_refresh_from_block_height(0), m_confirm_missing_payment_id(true) {} + wallet2(const wallet2&) : m_run(true), m_callback(0), m_testnet(false), m_always_confirm_transfers(true), m_print_ring_members(false), m_store_tx_info(true), m_default_mixin(0), m_default_priority(0), m_refresh_type(RefreshOptimizeCoinbase), m_auto_refresh(true), m_refresh_from_block_height(0), m_confirm_missing_payment_id(true) {} public: static const char* tr(const char* str);// { return i18n_translate(str, "cryptonote::simple_wallet"); } @@ -119,7 +119,7 @@ namespace tools //! Uses stdin and stdout. Returns a wallet2 and password for wallet with no file if no errors. static std::pair<std::unique_ptr<wallet2>, password_container> make_new(const boost::program_options::variables_map& vm); - wallet2(bool testnet = false, bool restricted = false) : m_run(true), m_callback(0), m_testnet(testnet), m_always_confirm_transfers(true), m_store_tx_info(true), m_default_mixin(0), m_default_priority(0), m_refresh_type(RefreshOptimizeCoinbase), m_auto_refresh(true), m_refresh_from_block_height(0), m_confirm_missing_payment_id(true), m_restricted(restricted), is_old_file_format(false) {} + wallet2(bool testnet = false, bool restricted = false) : m_run(true), m_callback(0), m_testnet(testnet), m_always_confirm_transfers(true), m_print_ring_members(false), m_store_tx_info(true), m_default_mixin(0), m_default_priority(0), m_refresh_type(RefreshOptimizeCoinbase), m_auto_refresh(true), m_refresh_from_block_height(0), m_confirm_missing_payment_id(true), m_restricted(restricted), is_old_file_format(false) {} struct transfer_details { uint64_t m_block_height; @@ -477,6 +477,8 @@ namespace tools bool always_confirm_transfers() const { return m_always_confirm_transfers; } void always_confirm_transfers(bool always) { m_always_confirm_transfers = always; } + bool print_ring_members() const { return m_print_ring_members; } + void print_ring_members(bool value) { m_print_ring_members = value; } bool store_tx_info() const { return m_store_tx_info; } void store_tx_info(bool store) { m_store_tx_info = store; } uint32_t default_mixin() const { return m_default_mixin; } @@ -625,6 +627,7 @@ namespace tools bool is_old_file_format; /*!< Whether the wallet file is of an old file format */ bool m_watch_only; /*!< no spend key */ bool m_always_confirm_transfers; + bool m_print_ring_members; bool m_store_tx_info; /*!< request txkey to be returned in RPC, and store in the wallet cache file */ uint32_t m_default_mixin; uint32_t m_default_priority; diff --git a/src/wallet/wallet2_api.h b/src/wallet/wallet2_api.h index d049baac6..d4c0388a6 100644 --- a/src/wallet/wallet2_api.h +++ b/src/wallet/wallet2_api.h @@ -592,6 +592,15 @@ struct WalletManager //! returns current block target virtual uint64_t blockTarget() const = 0; + //! returns true iff mining + virtual bool isMining() const = 0; + + //! starts mining with the set number of threads + virtual bool startMining(const std::string &address, uint32_t threads = 1) = 0; + + //! stops mining + virtual bool stopMining() = 0; + //! resolves an OpenAlias address to a monero address virtual std::string resolveOpenAlias(const std::string &address, bool &dnssec_valid) const = 0; }; diff --git a/src/wallet/wallet_rpc_server.cpp b/src/wallet/wallet_rpc_server.cpp index 21965c4c8..d61b11f8a 100644 --- a/src/wallet/wallet_rpc_server.cpp +++ b/src/wallet/wallet_rpc_server.cpp @@ -125,7 +125,7 @@ namespace tools } } - epee::net_utils::http::http_auth::login login{}; + epee::net_utils::http::login login{}; 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); diff --git a/tests/unit_tests/http_auth.cpp b/tests/unit_tests/http_auth.cpp index 7158850b6..97954642f 100644 --- a/tests/unit_tests/http_auth.cpp +++ b/tests/unit_tests/http_auth.cpp @@ -61,6 +61,7 @@ #include "string_tools.h" namespace { +namespace http = epee::net_utils::http; using fields = std::unordered_map<std::string, std::string>; using auth_responses = std::vector<fields>; @@ -71,17 +72,28 @@ std::string quoted(std::string str) return str; } -epee::net_utils::http::http_request_info make_request(const fields& args) +void write_fields(std::string& out, const fields& args) { namespace karma = boost::spirit::karma; - - std::string out{" DIGEST "}; 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; +} - epee::net_utils::http::http_request_info request{}; +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)) @@ -89,6 +101,21 @@ epee::net_utils::http::http_request_info make_request(const fields& args) 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<std::string> check{u8"nonce", u8"qop", u8"realm", u8"stale"}; @@ -113,7 +140,7 @@ bool has_same_fields(const auth_responses& in) return true; } -bool is_unauthorized(const epee::net_utils::http::http_response_info& response) +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()); @@ -123,39 +150,44 @@ bool is_unauthorized(const epee::net_utils::http::http_response_info& response) response.m_mime_tipe == u8"text/html"; } - -auth_responses parse_response(const epee::net_utils::http::http_response_info& response) +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 != end; ++current) + for (auto current = response.m_additional_fields.begin();; ++current) { current = std::find_if(current, end, [] (const std::pair<std::string, std::string>& field) { - return boost::iequals(u8"www-authenticate", field.first); + return boost::equals(u8"WWW-authenticate", field.first); }); if (current == end) return result; - std::unordered_map<std::string, std::string> fields{}; - const bool rc = qi::parse( - current->second.begin(), current->second.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, - fields - ); - - if (rc) - result.push_back(std::move(fields)); + result.push_back(parse_fields(current->second)); } return result; } @@ -175,15 +207,20 @@ std::string md5_hex(const std::string& in) return epee::string_tools::pod_to_hex(digest); } -std::string get_a1(const epee::net_utils::http::http_auth::login& user, const auth_responses& responses) +std::string get_a1(const http::login& user, const fields& src) { - const std::string& realm = responses.at(0).at(u8"realm"); + const std::string& realm = src.at(u8"realm"); return boost::join( std::vector<std::string>{user.username, realm, user.password}, u8":" ); } -std::string get_a1_sess(const epee::net_utils::http::http_auth::login& user, const std::string& cnonce, const auth_responses& responses) +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( @@ -210,36 +247,36 @@ std::string get_nc(std::uint32_t count) } } -TEST(HTTP_Auth, NotRequired) +TEST(HTTP_Server_Auth, NotRequired) { - epee::net_utils::http::http_auth auth{}; - EXPECT_FALSE(auth.get_response(epee::net_utils::http::http_request_info{})); + http::http_server_auth auth{}; + EXPECT_FALSE(auth.get_response(http::http_request_info{})); } -TEST(HTTP_Auth, MissingAuth) +TEST(HTTP_Server_Auth, MissingAuth) { - epee::net_utils::http::http_auth auth{{"foo", "bar"}}; - EXPECT_TRUE(bool(auth.get_response(epee::net_utils::http::http_request_info{}))); + http::http_server_auth auth{{"foo", "bar"}}; + EXPECT_TRUE(bool(auth.get_response(http::http_request_info{}))); { - epee::net_utils::http::http_request_info request{}; + 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_Auth, BadSyntax) +TEST(HTTP_Server_Auth, BadSyntax) { - epee::net_utils::http::http_auth auth{{"foo", "bar"}}; + 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_Auth, MD5) +TEST(HTTP_Server_Auth, MD5) { - epee::net_utils::http::http_auth::login user{"foo", "bar"}; - epee::net_utils::http::http_auth auth{user}; + http::login user{"foo", "bar"}; + http::http_server_auth auth{user}; const auto response = auth.get_response(make_request(fields{})); ASSERT_TRUE(bool(response)); @@ -283,12 +320,12 @@ TEST(HTTP_Auth, MD5) EXPECT_STREQ(u8"true", fields2[0].at(u8"stale").c_str()); } -TEST(HTTP_Auth, MD5_sess) +TEST(HTTP_Server_Auth, MD5_sess) { constexpr const char cnonce[] = "not a good cnonce"; - epee::net_utils::http::http_auth::login user{"foo", "bar"}; - epee::net_utils::http::http_auth auth{user}; + http::login user{"foo", "bar"}; + http::http_server_auth auth{user}; const auto response = auth.get_response(make_request(fields{})); ASSERT_TRUE(bool(response)); @@ -334,13 +371,13 @@ TEST(HTTP_Auth, MD5_sess) EXPECT_STREQ(u8"true", fields2[0].at(u8"stale").c_str()); } -TEST(HTTP_Auth, MD5_auth) +TEST(HTTP_Server_Auth, MD5_auth) { constexpr const char cnonce[] = "not a nonce"; constexpr const char qop[] = "auth"; - epee::net_utils::http::http_auth::login user{"foo", "bar"}; - epee::net_utils::http::http_auth auth{user}; + http::login user{"foo", "bar"}; + http::http_server_auth auth{user}; const auto response = auth.get_response(make_request(fields{})); ASSERT_TRUE(bool(response)); @@ -402,13 +439,13 @@ TEST(HTTP_Auth, MD5_auth) EXPECT_STREQ(u8"true", parsed_replay[0].at(u8"stale").c_str()); } -TEST(HTTP_Auth, MD5_sess_auth) +TEST(HTTP_Server_Auth, MD5_sess_auth) { constexpr const char cnonce[] = "not a nonce"; constexpr const char qop[] = "auth"; - epee::net_utils::http::http_auth::login user{"foo", "bar"}; - epee::net_utils::http::http_auth auth{user}; + http::login user{"foo", "bar"}; + http::http_server_auth auth{user}; const auto response = auth.get_response(make_request(fields{})); ASSERT_TRUE(bool(response)); @@ -469,3 +506,219 @@ TEST(HTTP_Auth, MD5_sess_auth) 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<std::string>{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<std::string>{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)); +} + |