1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless requied by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 * 16 */ 17 18 #ifndef DNS_TLS_FRONTEND_H 19 #define DNS_TLS_FRONTEND_H 20 21 #include <arpa/nameser.h> 22 23 #include <atomic> 24 #include <mutex> 25 #include <string> 26 #include <thread> 27 #include <unordered_map> 28 #include <vector> 29 30 #include <android-base/thread_annotations.h> 31 #include <openssl/ssl.h> 32 33 namespace test { 34 35 constexpr int SHA256_SIZE = 32; 36 37 /* 38 * Simple DNS over TLS reverse proxy that forwards to a UDP backend. 39 * Only handles a single request at a time. 40 */ 41 class DnsTlsFrontend { 42 public: DnsTlsFrontend(const std::string & listen_address,const std::string & listen_service,const std::string & backend_address,const std::string & backend_service)43 DnsTlsFrontend(const std::string& listen_address, const std::string& listen_service, 44 const std::string& backend_address, const std::string& backend_service) : 45 listen_address_(listen_address), listen_service_(listen_service), 46 backend_address_(backend_address), backend_service_(backend_service), 47 queries_(0), terminate_(false) { } ~DnsTlsFrontend()48 ~DnsTlsFrontend() { 49 stopServer(); 50 } listen_address()51 const std::string& listen_address() const { 52 return listen_address_; 53 } listen_service()54 const std::string& listen_service() const { 55 return listen_service_; 56 } running()57 bool running() const { 58 return socket_ != -1; 59 } 60 bool startServer(); 61 bool stopServer(); queries()62 int queries() const { return queries_; } 63 bool waitForQueries(int number, int timeoutMs) const; set_chain_length(int length)64 void set_chain_length(int length) { chain_length_ = length; } 65 // Represents a fingerprint from the middle of the certificate chain. fingerprint()66 const std::vector<uint8_t>& fingerprint() const { return fingerprint_; } 67 68 private: 69 void requestHandler(); 70 bool handleOneRequest(SSL* ssl); 71 72 std::string listen_address_; 73 std::string listen_service_; 74 std::string backend_address_; 75 std::string backend_service_; 76 bssl::UniquePtr<SSL_CTX> ctx_; 77 int socket_ = -1; 78 int backend_socket_ = -1; 79 std::atomic<int> queries_; 80 std::atomic<bool> terminate_; 81 std::thread handler_thread_ GUARDED_BY(update_mutex_); 82 std::mutex update_mutex_; 83 int chain_length_ = 1; 84 std::vector<uint8_t> fingerprint_; 85 }; 86 87 } // namespace test 88 89 #endif // DNS_TLS_FRONTEND_H 90