Debian Codegraph @

monero/contrib/epee/src/http_auth.cpp

raw symbols SCIP
1 // Copyright (c) 2014-2022, The Monero Project
2 //
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without modification, are
6 // permitted provided that the following conditions are met:
7 //
8 // 1. Redistributions of source code must retain the above copyright notice, this list of
9 // conditions and the following disclaimer.
10 //
11 // 2. Redistributions in binary form must reproduce the above copyright notice, this list
12 // of conditions and the following disclaimer in the documentation and/or other
13 // materials provided with the distribution.
14 //
15 // 3. Neither the name of the copyright holder nor the names of its contributors may be
16 // used to endorse or promote products derived from this software without specific
17 // prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
20 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
22 // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27 // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "net/http_auth.h"
29
30 #include <array>
31 #include <boost/algorithm/string/find_iterator.hpp>
32 #include <boost/algorithm/string/predicate.hpp>
33 #include <boost/fusion/adapted/std_tuple.hpp>
34 #include <boost/fusion/algorithm/iteration/for_each.hpp>
35 #include <boost/fusion/algorithm/iteration/iter_fold.hpp>
36 #include <boost/fusion/algorithm/query/any.hpp>
37 #include <boost/fusion/iterator/distance.hpp>
38 #include <boost/fusion/iterator/value_of.hpp>
39 #include <boost/fusion/sequence/intrinsic/begin.hpp>
40 #include <boost/fusion/sequence/intrinsic/size.hpp>
41 #include <boost/range/algorithm/copy.hpp>
42 #include <boost/range/algorithm/find_if.hpp>
43 #include <boost/range/iterator_range_core.hpp>
44 #include <boost/range/join.hpp>
45 #include <boost/spirit/include/karma_generate.hpp>
46 #include <boost/spirit/include/karma_uint.hpp>
47 #include <boost/spirit/include/qi_alternative.hpp>
48 #include <boost/spirit/include/qi_and_predicate.hpp>
49 #include <boost/spirit/include/qi_char.hpp>
50 #include <boost/spirit/include/qi_char_class.hpp>
51 #include <boost/spirit/include/qi_difference.hpp>
52 #include <boost/spirit/include/qi_kleene.hpp>
53 #include <boost/spirit/include/qi_parse.hpp>
54 #include <boost/spirit/include/qi_plus.hpp>
55 #include <boost/spirit/include/qi_no_case.hpp>
56 #include <boost/spirit/include/qi_not_predicate.hpp>
57 #include <boost/spirit/include/qi_raw.hpp>
58 #include <boost/spirit/include/qi_rule.hpp>
59 #include <boost/spirit/include/qi_sequence.hpp>
60 #include <boost/spirit/include/qi_string.hpp>
61 #include <boost/spirit/include/qi_symbols.hpp>
62 #include <boost/spirit/include/qi_uint.hpp>
63 #include <cassert>
64 #include <iterator>
65 #include <limits>
66 #include <openssl/evp.h>
67 #include <tuple>
68 #include <type_traits>
69
70 #include "hex.h"
71 #include "string_coding.h"
72
73 /* This file uses the `u8` prefix and specifies all chars by ASCII numeric
74 value. This is for maximum portability - C++ does not actually specify ASCII
75 as the encoding type for unprefixed string literals, etc. Although rare, the
76 effort required to support rare compiler encoding types is low.
77
78 Also be careful of qi::ascii character classes (`qi::asci::alpha`, etc.) -
79 non-ASCII characters will cause undefined behavior in the table lookup until
80 boost 1.60. The expression `&qi::ascii::char_` will fail on non-ASCII
81 characters without "consuming" the input character. */
82
83 namespace
84 {
85 namespace http = epee::net_utils::http;
86
87 // string_ref is only constexpr if length is given
88 template<std::size_t N>
89 constexpr boost::string_ref ceref(const char (&arg)[N])
90 {
91 return boost::string_ref(arg, N - 1);
92 }
93
94 constexpr const auto client_auth_field = ceref(u8"Authorization");
95 constexpr const auto server_auth_field = ceref(u8"WWW-authenticate");
96 constexpr const auto auth_realm = ceref(u8"monero-rpc");
97 constexpr const char comma = 44;
98 constexpr const char equal_sign = 61;
99 constexpr const char quote = 34;
100 constexpr const char zero = 48;
101 constexpr const auto sess_algo = ceref(u8"-sess");
102
103 constexpr const unsigned client_reserve_size = 512; //!< std::string::reserve size for clients
104
105 //// Digest Algorithms
106
107 struct md5_
108 {
109 static constexpr const boost::string_ref name = ceref(u8"MD5");
110
111 struct update
112 {
113 template<typename T>
114 void operator()(const T& arg) const
115 {
116 const boost::iterator_range<const char*> data(boost::as_literal(arg));
117 EVP_DigestUpdate(
118 ctx,
119 reinterpret_cast<const std::uint8_t*>(data.begin()),
120 data.size()
121 );
122 }
123 void operator()(const std::string& arg) const
124 {
125 (*this)(boost::string_ref(arg));
126 }
127 void operator()(const epee::wipeable_string& arg) const
128 {
129 EVP_DigestUpdate(
130 ctx,
131 reinterpret_cast<const std::uint8_t*>(arg.data()),
132 arg.size()
133 );
134 }
135
136 EVP_MD_CTX *ctx;
137 };
138
139 template<typename... T>
140 std::array<char, 32> operator()(const T&... args) const
141 {
142 std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)> ctx(EVP_MD_CTX_new(), &EVP_MD_CTX_free);
143 EVP_DigestInit(ctx.get(), EVP_md5());
144 boost::fusion::for_each(std::tie(args...), update{ctx.get()});
145
146 std::array<std::uint8_t, 16> digest{{}};
147 EVP_DigestFinal(ctx.get(), digest.data(), NULL);
148 return epee::to_hex::array(digest);
149 }
150 };
151 constexpr const boost::string_ref md5_::name;
152
153 //! Digest Algorithms available for HTTP Digest Auth. Sort better algos to the left
154 constexpr const std::tuple<md5_> digest_algorithms{};
155
156 //// Various String Utilities
157
158 struct ascii_tolower_
159 {
160 template<typename Char>
161 constexpr Char operator()(Char value) const noexcept
162 {
163 static_assert(std::is_integral<Char>::value, "only integral types supported");
164 return (65 <= value && value <= 90) ? (value + 32) : value;
165 }
166 };
167 constexpr const ascii_tolower_ ascii_tolower{};
168
169 struct ascii_iequal_
170 {
171 template<typename Char>
172 constexpr bool operator()(Char left, Char right) const noexcept
173 {
174 return ascii_tolower(left) == ascii_tolower(right);
175 }
176 };
177 constexpr const ascii_iequal_ ascii_iequal{};
178
179 struct http_list_separator_
180 {
181 template<typename Char>
182 bool operator()(Char value) const noexcept
183 {
184 static_assert(std::is_integral<Char>::value, "only integral types supported");
185 return boost::spirit::char_encoding::ascii::isascii_(value) &&
186 (value == comma || boost::spirit::char_encoding::ascii::isspace(value));
187 }
188 };
189 constexpr const http_list_separator_ http_list_separator{};
190
191 std::string to_string(boost::iterator_range<const char*> source)
192 {
193 return {source.begin(), source.size()};
194 }
195
196 template<typename T>
197 void add_first_field(std::string& str, const char* const name, const T& value)
198 {
199 str.append(name);
200 str.push_back(equal_sign);
201 boost::copy(value, std::back_inserter(str));
202 }
203
204 template<typename T>
205 void add_field(std::string& str, const char* const name, const T& value)
206 {
207 str.push_back(comma);
208 add_first_field(str, name, value);
209 }
210
211 template<typename T>
212 auto quoted_(const T& arg) // avoid ADL selecting C++14 std::quoted
213 {
214 return boost::range::join(boost::range::join(ceref(u8"\""), arg), ceref(u8"\""));
215 }
216
217 //// Digest Authentication
218
219 template<typename Digest>
220 typename std::result_of<Digest()>::type generate_a1(
221 Digest digest, const http::login& creds, const boost::string_ref realm)
222 {
223 return digest(creds.username, u8":", realm, u8":", creds.password);
224 }
225
226 template<typename Digest>
227 typename std::result_of<Digest()>::type generate_a1(
228 Digest digest, const http::http_client_auth::session& user)
229 {
230 return generate_a1(std::move(digest), user.credentials, user.server.realm);
231 }
232
233 template<typename T>
234 void init_client_value(std::string& str,
235 const boost::string_ref algorithm, const http::http_client_auth::session& user,
236 const boost::string_ref uri, const T& response)
237 {
238 str.append(u8"Digest ");
239 add_first_field(str, u8"algorithm", algorithm);
240 add_field(str, u8"nonce", quoted_(user.server.nonce));
241 add_field(str, u8"realm", quoted_(user.server.realm));
242 add_field(str, u8"response", quoted_(response));
243 add_field(str, u8"uri", quoted_(uri));
244 add_field(str, u8"username", quoted_(user.credentials.username));
245 if (!user.server.opaque.empty())
246 add_field(str, u8"opaque", quoted_(user.server.opaque));
247 }
248
249 //! Implements superseded algorithm specified in RFC 2069
250 template<typename Digest>
251 struct old_algorithm
252 {
253 explicit old_algorithm(Digest digest_) : digest(std::move(digest_)) {}
254
255 std::string operator()(const http::http_client_auth::session& user,
256 const boost::string_ref method, const boost::string_ref uri) const
257 {
258 const auto response = digest(
259 generate_a1(digest, user), u8":", user.server.nonce, u8":", digest(method, u8":", uri)
260 );
261 std::string out{};
262 out.reserve(client_reserve_size);
263 init_client_value(out, Digest::name, user, uri, response);
264 return out;
265 }
266 private:
267 Digest digest;
268 };
269
270 //! Implements the `qop=auth` algorithm specified in RFC 2617
271 template<typename Digest>
272 struct auth_algorithm
273 {
274 explicit auth_algorithm(Digest digest_) : digest(std::move(digest_)) {}
275
276 std::string operator()(const http::http_client_auth::session& user,
277 const boost::string_ref method, const boost::string_ref uri) const
278 {
279 namespace karma = boost::spirit::karma;
280 using counter_type = decltype(user.counter);
281 static_assert(
282 std::numeric_limits<counter_type>::radix == 2, "unexpected radix for counter"
283 );
284 static_assert(
285 std::numeric_limits<counter_type>::digits <= 32,
286 "number of digits will cause underflow on padding below"
287 );
288
289 std::string out{};
290 out.reserve(client_reserve_size);
291
292 karma::generate(std::back_inserter(out), karma::hex(user.counter));
293 out.insert(out.begin(), 8 - out.size(), zero); // zero left pad
294 if (out.size() != 8)
295 return {};
296
297 std::array<char, 8> nc{{}};
298 boost::copy(out, nc.data());
299 const auto response = digest(
300 generate_a1(digest, user), u8":", user.server.nonce, u8":", nc, u8"::auth:", digest(method, u8":", uri)
301 );
302 out.clear();
303 init_client_value(out, Digest::name, user, uri, response);
304 add_field(out, u8"qop", ceref(u8"auth"));
305 add_field(out, u8"nc", nc);
306 return out;
307 }
308
309 private:
310 Digest digest;
311 };
312
313 //! Processes client "Authorization" and server "WWW-authenticate" HTTP fields
314 struct auth_message
315 {
316 using iterator = const char*;
317 enum status{ kFail = 0, kStale, kPass };
318
319 //! \return Status of the `response` field from the client
320 static status verify(const boost::string_ref method, const boost::string_ref request,
321 const http::http_server_auth::session& user)
322 {
323 const auto parsed = parse(request);
324 if (parsed &&
325 boost::equals(parsed->username, user.credentials.username) &&
326 boost::fusion::any(digest_algorithms, has_valid_response{*parsed, user, method}))
327 {
328 if (boost::equals(parsed->nonce, user.nonce))
329 {
330 // RFC 2069 format does not verify nc value - allow just once
331 if (user.counter == 1 || (!parsed->qop.empty() && parsed->counter() == user.counter))
332 {
333 return kPass;
334 }
335 }
336 return kStale;
337 }
338 return kFail;
339 }
340
341 //! \return Information needed to generate client authentication `response`s.
342 static http::http_client_auth::session::keys extract(
343 const http::http_response_info& response, const bool is_first)
344 {
345 using field = std::pair<std::string, std::string>;
346
347 server_parameters best{};
348
349 const std::list<field>& fields = response.m_header_info.m_etc_fields;
350 auto current = fields.begin();
351 const auto end = fields.end();
352 while (true)
353 {
354 current = std::find_if(current, end, [] (const field& value) {
355 return boost::equals(server_auth_field, value.first, ascii_iequal);
356 });
357 if (current == end)
358 break;
359
360 const auto parsed = parse(current->second);
361 if (parsed)
362 {
363 server_parameters local_best = parsed->algorithm.empty() ?
364 server_parameters{*parsed, boost::fusion::find<md5_>(digest_algorithms)} :
365 boost::fusion::iter_fold(digest_algorithms, server_parameters{}, matches_algorithm{*parsed});
366
367 if (local_best.index < best.index)
368 best = std::move(local_best);
369 }
370 ++current;
371 }
372 if (is_first || boost::equals(best.stale, ceref(u8"true"), ascii_iequal))
373 return best.take();
374 return {}; // authentication failed with bad user/pass
375 }
376
377 private:
378 explicit auth_message()
379 : algorithm()
380 , cnonce()
381 , nc()
382 , nonce()
383 , qop()
384 , realm()
385 , response()
386 , stale()
387 , uri()
388 , username() {
389 }
390
391 static boost::optional<auth_message> parse(const boost::string_ref request)
392 {
393 struct parser
394 {
395 using field_parser = std::function<bool(const parser&, iterator&, iterator, auth_message&)>;
396
397 explicit parser() : field_table(), skip_whitespace(), header(), quoted_string(), token(), fields() {
398 using namespace std::placeholders;
399 namespace qi = boost::spirit::qi;
400
401 struct parse_nc
402 {
403 bool operator()(const parser&, iterator& current, const iterator end, auth_message& result) const
404 {
405 return qi::parse(
406 current, end,
407 (qi::raw[qi::uint_parser<std::uint32_t, 16, 8, 8>{}]),
408 result.nc
409 );
410 }
411 };
412 struct parse_token
413 {
414 bool operator()(const parser& parse, iterator& current, const iterator end,
415 boost::iterator_range<iterator>& result) const
416 {
417 return qi::parse(current, end, parse.token, result);
418 }
419 };
420 struct parse_string
421 {
422 bool operator()(const parser& parse, iterator& current, const iterator end,
423 boost::iterator_range<iterator>& result) const
424 {
425 return qi::parse(current, end, parse.quoted_string, result);
426 }
427 bool operator()(const parser& parse, iterator& current, const iterator end) const
428 {
429 return qi::parse(current, end, parse.quoted_string);
430 }
431 };
432 struct parse_response
433 {
434 bool operator()(const parser&, iterator& current, const iterator end, auth_message& result) const
435 {
436 using byte = qi::uint_parser<std::uint8_t, 16, 2, 2>;
437 return qi::parse(
438 current, end,
439 (qi::lit(quote) >> qi::raw[+(byte{})] >> qi::lit(quote)),
440 result.response
441 );
442 }
443 };
444
445 field_table.add
446 (u8"algorithm", std::bind(parse_token{}, _1, _2, _3, std::bind(&auth_message::algorithm, _4)))
447 (u8"cnonce", std::bind(parse_string{}, _1, _2, _3, std::bind(&auth_message::cnonce, _4)))
448 (u8"domain", std::bind(parse_string{}, _1, _2, _3)) // ignore field
449 (u8"nc", parse_nc{})
450 (u8"nonce", std::bind(parse_string{}, _1, _2, _3, std::bind(&auth_message::nonce, _4)))
451 (u8"opaque", std::bind(parse_string{}, _1, _2, _3, std::bind(&auth_message::opaque, _4)))
452 (u8"qop", std::bind(parse_token{}, _1, _2, _3, std::bind(&auth_message::qop, _4)))
453 (u8"realm", std::bind(parse_string{}, _1, _2, _3, std::bind(&auth_message::realm, _4)))
454 (u8"response", parse_response{})
455 (u8"stale", std::bind(parse_token{}, _1, _2, _3, std::bind(&auth_message::stale, _4)))
456 (u8"uri", std::bind(parse_string{}, _1, _2, _3, std::bind(&auth_message::uri, _4)))
457 (u8"username", std::bind(parse_string{}, _1, _2, _3, std::bind(&auth_message::username, _4)));
458
459 skip_whitespace = *(&qi::ascii::char_ >> qi::ascii::space);
460 header = skip_whitespace >> qi::ascii::no_case[u8"digest"] >> skip_whitespace;
461 quoted_string = (qi::lit(quote) >> qi::raw[+(u8"\\\"" | (qi::ascii::char_ - quote))] >> qi::lit(quote));
462 token =
463 (!qi::lit(quote) >> qi::raw[+(&qi::ascii::char_ >> (qi::ascii::graph - qi::ascii::char_(u8"()<>@,;:\\\"/[]?={}")))]) |
464 quoted_string;
465 fields = field_table >> skip_whitespace >> equal_sign >> skip_whitespace;
466 }
467
468 boost::optional<auth_message> operator()(const boost::string_ref request) const
469 {
470 namespace qi = boost::spirit::qi;
471
472 iterator current = request.begin();
473 const iterator end = request.end();
474
475 if (!qi::parse(current, end, header))
476 {
477 return boost::none;
478 }
479
480 auth_message info{};
481 field_parser null_parser{};
482 std::reference_wrapper<const field_parser> field = null_parser;
483
484 do // require at least one field; require field after `,` character
485 {
486 if (!qi::parse(current, end, fields, field) || !field(*this, current, end, info))
487 {
488 return boost::none;
489 }
490 qi::parse(current, end, skip_whitespace);
491 } while (qi::parse(current, end, qi::char_(comma) >> skip_whitespace));
492 return boost::make_optional(current == end, info);
493 }
494
495 private:
496 boost::spirit::qi::symbols<
497 char, field_parser, boost::spirit::qi::tst<char, field_parser>, ascii_tolower_
498 > field_table;
499 boost::spirit::qi::rule<iterator> skip_whitespace;
500 boost::spirit::qi::rule<iterator> header;
501 boost::spirit::qi::rule<iterator, boost::iterator_range<iterator>()> quoted_string;
502 boost::spirit::qi::rule<iterator, boost::iterator_range<iterator>()> token;
503 boost::spirit::qi::rule<iterator, std::reference_wrapper<const field_parser>()> fields;
504 }; // parser
505
506 static const parser parse_;
507 return parse_(request);
508 }
509
510 struct has_valid_response
511 {
512 template<typename Digest, typename Result>
513 Result generate_old_response(Digest digest, const Result& key, const Result& auth) const
514 {
515 return digest(key, u8":", request.nonce, u8":", auth);
516 }
517
518 template<typename Digest, typename Result>
519 Result generate_new_response(Digest digest, const Result& key, const Result& auth) const
520 {
521 return digest(
522 key, u8":", request.nonce, u8":", request.nc, u8":", request.cnonce, u8":", request.qop, u8":", auth
523 );
524 }
525
526 template<typename Result>
527 bool check(const Result& result) const
528 {
529 return boost::equals(request.response, result, ascii_iequal);
530 }
531
532 template<typename Digest>
533 bool operator()(const Digest& digest) const
534 {
535 if (boost::starts_with(request.algorithm, Digest::name, ascii_iequal) ||
536 (request.algorithm.empty() && std::is_same<md5_, Digest>::value))
537 {
538 auto key = generate_a1(digest, user.credentials, auth_realm);
539 if (boost::ends_with(request.algorithm, sess_algo, ascii_iequal))
540 {
541 key = digest(key, u8":", request.nonce, u8":", request.cnonce);
542 }
543
544 auto auth = digest(method, u8":", request.uri);
545 if (request.qop.empty())
546 {
547 return check(generate_old_response(std::move(digest), std::move(key), std::move(auth)));
548 }
549 else if (boost::equals(ceref(u8"auth"), request.qop, ascii_iequal))
550 {
551 return check(generate_new_response(std::move(digest), std::move(key), std::move(auth)));
552 }
553 }
554 return false;
555 }
556
557 const auth_message& request;
558 const http::http_server_auth::session& user;
559 const boost::string_ref method;
560 };
561
562 boost::optional<std::uint32_t> counter() const
563 {
564 namespace qi = boost::spirit::qi;
565 using hex = qi::uint_parser<std::uint32_t, 16>;
566 std::uint32_t value = 0;
567 const bool converted = qi::parse(nc.begin(), nc.end(), hex{}, value);
568 return boost::make_optional(converted, value);
569 }
570
571 struct server_parameters
572 {
573 server_parameters()
574 : nonce(), opaque(), realm(), stale(), value_generator()
575 , index(boost::fusion::size(digest_algorithms))
576 {}
577
578 template<typename DigestIter>
579 explicit server_parameters(const auth_message& request, const DigestIter& digest)
580 : nonce(request.nonce)
581 , opaque(request.opaque)
582 , realm(request.realm)
583 , stale(request.stale)
584 , value_generator()
585 , index(boost::fusion::distance(boost::fusion::begin(digest_algorithms), digest))
586 {
587 using digest_type = typename boost::fusion::result_of::value_of<DigestIter>::type;
588
589 // debug check internal state of the auth_message class
590 assert(
591 (std::is_same<digest_type, md5_>::value) ||
592 boost::equals((*digest).name, request.algorithm, ascii_iequal)
593 );
594 if (request.qop.empty())
595 value_generator = old_algorithm<digest_type>{*digest};
596 else
597 {
598 for (auto elem = boost::make_split_iterator(request.qop, boost::token_finder(http_list_separator));
599 !elem.eof();
600 ++elem)
601 {
602 if (boost::equals(ceref(u8"auth"), *elem, ascii_iequal))
603 {
604 value_generator = auth_algorithm<digest_type>{*digest};
605 break;
606 }
607 }
608 if (!value_generator) // no supported qop mode
609 index = boost::fusion::size(digest_algorithms);
610 }
611 }
612
613 http::http_client_auth::session::keys take()
614 {
615 return {to_string(nonce), to_string(opaque), to_string(realm), std::move(value_generator)};
616 }
617
618 boost::iterator_range<iterator> nonce;
619 boost::iterator_range<iterator> opaque;
620 boost::iterator_range<iterator> realm;
621 boost::iterator_range<iterator> stale;
622 http::http_client_auth::session::keys::algorithm value_generator;
623 unsigned index;
624 };
625
626 struct matches_algorithm
627 {
628 template<typename DigestIter>
629 server_parameters operator()(server_parameters current, const DigestIter& digest) const
630 {
631 if (!current.value_generator)
632 {
633 if (boost::equals(response.algorithm, (*digest).name, ascii_iequal))
634 {
635 current = server_parameters{response, digest};
636 }
637 }
638 return current;
639 }
640 const auth_message& response;
641 };
642
643
644 boost::iterator_range<iterator> algorithm;
645 boost::iterator_range<iterator> cnonce;
646 boost::iterator_range<iterator> nc;
647 boost::iterator_range<iterator> nonce;
648 boost::iterator_range<iterator> opaque;
649 boost::iterator_range<iterator> qop;
650 boost::iterator_range<iterator> realm;
651 boost::iterator_range<iterator> response;
652 boost::iterator_range<iterator> stale;
653 boost::iterator_range<iterator> uri;
654 boost::iterator_range<iterator> username;
655 }; // auth_message
656
657 struct add_challenge
658 {
659 template<typename Digest>
660 void operator()(const Digest& digest) const
661 {
662 static constexpr const auto fvalue = ceref(u8"Digest qop=\"auth\"");
663
664 for (unsigned i = 0; i < 2; ++i)
665 {
666 std::string out(fvalue);
667
668 const auto algorithm = boost::range::join(
669 Digest::name, (i == 0 ? boost::string_ref{} : sess_algo)
670 );
671 add_field(out, u8"algorithm", algorithm);
672 add_field(out, u8"realm", quoted_(auth_realm));
673 add_field(out, u8"nonce", quoted_(nonce));
674 add_field(out, u8"stale", is_stale ? ceref("true") : ceref("false"));
675
676 fields.push_back(std::make_pair(std::string(server_auth_field), std::move(out)));
677 }
678 }
679
680 const boost::string_ref nonce;
681 std::list<std::pair<std::string, std::string>>& fields;
682 const bool is_stale;
683 };
684
685 http::http_response_info create_digest_response(const boost::string_ref nonce, const bool is_stale)
686 {
687 epee::net_utils::http::http_response_info rc{};
688 rc.m_response_code = 401;
689 rc.m_response_comment = u8"Unauthorized";
690 rc.m_mime_tipe = u8"text/html";
691 rc.m_body =
692 u8"<html><head><title>Unauthorized Access</title></head><body><h1>401 Unauthorized</h1></body></html>";
693
694 boost::fusion::for_each(
695 digest_algorithms, add_challenge{nonce, rc.m_additional_fields, is_stale}
696 );
697
698 return rc;
699 }
700 }
701
702 namespace epee
703 {
704 namespace net_utils
705 {
706 namespace http
707 {
708 http_server_auth::http_server_auth(login credentials, std::function<void(size_t, uint8_t*)> r)
709 : user(session{std::move(credentials)}), rng(std::move(r)) {
710 }
711
712 boost::optional<http_response_info> http_server_auth::do_get_response(const http_request_info& request)
713 {
714 assert(user);
715 using field = std::pair<std::string, std::string>;
716
717 const std::list<field>& fields = request.m_header_info.m_etc_fields;
718 const auto auth = boost::find_if(fields, [] (const field& value) {
719 return boost::equals(client_auth_field, value.first, ascii_iequal);
720 });
721
722 bool is_stale = false;
723 if (auth != fields.end())
724 {
725 ++(user->counter);
726 switch (auth_message::verify(request.m_http_method_str, auth->second, *user))
727 {
728 case auth_message::kPass:
729 return boost::none;
730
731 case auth_message::kStale:
732 is_stale = true;
733 break;
734
735 default:
736 case auth_message::kFail:
737 break;
738 }
739 }
740 user->counter = 0;
741 {
742 std::array<std::uint8_t, 16> rand_128bit{{}};
743 rng(rand_128bit.size(), rand_128bit.data());
744 user->nonce = string_encoding::base64_encode(rand_128bit.data(), rand_128bit.size());
745 }
746 return create_digest_response(user->nonce, is_stale);
747 }
748
749 http_client_auth::http_client_auth(login credentials)
750 : user(session{std::move(credentials)}) {
751 }
752
753 http_client_auth::status http_client_auth::do_handle_401(const http_response_info& response)
754 {
755 assert(user);
756 const bool first_auth = (user->counter == 0);
757 user->server = auth_message::extract(response, first_auth);
758 if (user->server.generator)
759 {
760 user->counter = 0;
761 return kSuccess;
762 }
763 return first_auth ? kParseFailure : kBadPassword;
764 }
765
766 boost::optional<std::pair<std::string, std::string>> http_client_auth::do_get_auth_field(
767 const boost::string_ref method, const boost::string_ref uri)
768 {
769 assert(user);
770 if (user->server.generator)
771 {
772 ++(user->counter);
773 return std::make_pair(std::string(client_auth_field), user->server.generator(*user, method, uri));
774 }
775 return boost::none;
776 }
777 }
778 }
779 }
780