1 /*
2  * Copyright (C) 2019 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 required 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 #pragma once
19 
20 #include <arpa/nameser.h>
21 #include <netdb.h>
22 
23 #include <string>
24 #include <vector>
25 
26 #include <aidl/android/net/INetd.h>
27 #include <gtest/gtest.h>
28 #include <netdutils/InternetAddresses.h>
29 
30 #include "dns_responder/dns_responder.h"
31 
32 class ScopeBlockedUIDRule {
33     using INetd = aidl::android::net::INetd;
34 
35   public:
ScopeBlockedUIDRule(INetd * netSrv,uid_t testUid)36     ScopeBlockedUIDRule(INetd* netSrv, uid_t testUid)
37         : mNetSrv(netSrv), mTestUid(testUid), mSavedUid(getuid()) {
38         // Add drop rule for testUid. Also enable the standby chain because it might not be
39         // enabled. Unfortunately we cannot use FIREWALL_CHAIN_NONE, or custom iptables rules, for
40         // this purpose because netd calls fchown() on the DNS query sockets, and "iptables -m
41         // owner" matches the UID of the socket creator, not the UID set by fchown().
42         // TODO: migrate FIREWALL_CHAIN_NONE to eBPF as well.
43         EXPECT_TRUE(mNetSrv->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true).isOk());
44         EXPECT_TRUE(mNetSrv->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, mTestUid,
45                                                 INetd::FIREWALL_RULE_DENY)
46                             .isOk());
47         EXPECT_TRUE(seteuid(mTestUid) == 0);
48     };
~ScopeBlockedUIDRule()49     ~ScopeBlockedUIDRule() {
50         // Restore uid
51         EXPECT_TRUE(seteuid(mSavedUid) == 0);
52         // Remove drop rule for testUid, and disable the standby chain.
53         EXPECT_TRUE(mNetSrv->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, mTestUid,
54                                                 INetd::FIREWALL_RULE_ALLOW)
55                             .isOk());
56         EXPECT_TRUE(mNetSrv->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false).isOk());
57     }
58 
59   private:
60     INetd* mNetSrv;
61     const uid_t mTestUid;
62     const uid_t mSavedUid;
63 };
64 
65 class ScopedChangeUID {
66   public:
ScopedChangeUID(uid_t testUid)67     ScopedChangeUID(uid_t testUid) : mTestUid(testUid), mSavedUid(getuid()) {
68         EXPECT_TRUE(seteuid(mTestUid) == 0);
69     };
~ScopedChangeUID()70     ~ScopedChangeUID() { EXPECT_TRUE(seteuid(mSavedUid) == 0); }
71 
72   private:
73     const uid_t mTestUid;
74     const uid_t mSavedUid;
75 };
76 
77 struct DnsRecord {
78     std::string host_name;  // host name
79     ns_type type;           // record type
80     std::string addr;       // ipv4/v6 address
81 };
82 
83 // TODO: make this dynamic and stop depending on implementation details.
84 constexpr int TEST_NETID = 30;
85 // Use maximum reserved appId for applications to avoid conflict with existing uids.
86 constexpr int TEST_UID = 99999;
87 
88 static constexpr char kLocalHost[] = "localhost";
89 static constexpr char kLocalHostAddr[] = "127.0.0.1";
90 static constexpr char kIp6LocalHost[] = "ip6-localhost";
91 static constexpr char kIp6LocalHostAddr[] = "::1";
92 static constexpr char kHelloExampleCom[] = "hello.example.com.";
93 static constexpr char kHelloExampleComAddrV4[] = "1.2.3.4";
94 static constexpr char kHelloExampleComAddrV6[] = "::1.2.3.4";
95 static constexpr char kExampleComDomain[] = ".example.com";
96 
97 constexpr size_t kMaxmiumLabelSize = 63;  // see RFC 1035 section 2.3.4.
98 
99 static const std::vector<uint8_t> kHelloExampleComQueryV4 = {
100         /* Header */
101         0x00, 0x00, /* Transaction ID: 0x0000 */
102         0x01, 0x00, /* Flags: rd */
103         0x00, 0x01, /* Questions: 1 */
104         0x00, 0x00, /* Answer RRs: 0 */
105         0x00, 0x00, /* Authority RRs: 0 */
106         0x00, 0x00, /* Additional RRs: 0 */
107         /* Queries */
108         0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x03,
109         0x63, 0x6f, 0x6d, 0x00, /* Name: hello.example.com */
110         0x00, 0x01,             /* Type: A */
111         0x00, 0x01              /* Class: IN */
112 };
113 
114 static const std::vector<uint8_t> kHelloExampleComResponseV4 = {
115         /* Header */
116         0x00, 0x00, /* Transaction ID: 0x0000 */
117         0x81, 0x80, /* Flags: qr rd ra */
118         0x00, 0x01, /* Questions: 1 */
119         0x00, 0x01, /* Answer RRs: 1 */
120         0x00, 0x00, /* Authority RRs: 0 */
121         0x00, 0x00, /* Additional RRs: 0 */
122         /* Queries */
123         0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x03,
124         0x63, 0x6f, 0x6d, 0x00, /* Name: hello.example.com */
125         0x00, 0x01,             /* Type: A */
126         0x00, 0x01,             /* Class: IN */
127         /* Answers */
128         0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x03,
129         0x63, 0x6f, 0x6d, 0x00, /* Name: hello.example.com */
130         0x00, 0x01,             /* Type: A */
131         0x00, 0x01,             /* Class: IN */
132         0x00, 0x00, 0x00, 0x00, /* Time to live: 0 */
133         0x00, 0x04,             /* Data length: 4 */
134         0x01, 0x02, 0x03, 0x04  /* Address: 1.2.3.4 */
135 };
136 
137 // Illegal hostnames
138 static constexpr char kBadCharAfterPeriodHost[] = "hello.example.^com.";
139 static constexpr char kBadCharBeforePeriodHost[] = "hello.example^.com.";
140 static constexpr char kBadCharAtTheEndHost[] = "hello.example.com^.";
141 static constexpr char kBadCharInTheMiddleOfLabelHost[] = "hello.ex^ample.com.";
142 
143 static const test::DNSHeader kDefaultDnsHeader = {
144         // Don't need to initialize the flag "id" and "rd" because DNS responder assigns them from
145         // query to response. See RFC 1035 section 4.1.1.
146         .id = 0,                // unused. should be assigned from query to response
147         .ra = false,            // recursive query support is not available
148         .rcode = ns_r_noerror,  // no error
149         .qr = true,             // message is a response
150         .opcode = QUERY,        // a standard query
151         .aa = false,            // answer/authority portion was not authenticated by the server
152         .tr = false,            // message is not truncated
153         .rd = false,            // unused. should be assigned from query to response
154         .ad = false,            // non-authenticated data is unacceptable
155 };
156 
157 // The CNAME chain records for building a response message which exceeds 512 bytes.
158 //
159 // Ignoring the other fields of the message, the response message has 8 CNAMEs in 5 answer RRs
160 // and each CNAME has 77 bytes as the follows. The response message at least has 616 bytes in
161 // answer section and has already exceeded 512 bytes totally.
162 //
163 // The CNAME is presented as:
164 //   0   1            64  65                          72  73          76  77
165 //   +---+--........--+---+---+---+---+---+---+---+---+---+---+---+---+---+
166 //   | 63| {x, .., x} | 7 | e | x | a | m | p | l | e | 3 | c | o | m | 0 |
167 //   +---+--........--+---+---+---+---+---+---+---+---+---+---+---+---+---+
168 //          ^-- x = {a, b, c, d}
169 //
170 const std::string kCnameA = std::string(kMaxmiumLabelSize, 'a') + kExampleComDomain + ".";
171 const std::string kCnameB = std::string(kMaxmiumLabelSize, 'b') + kExampleComDomain + ".";
172 const std::string kCnameC = std::string(kMaxmiumLabelSize, 'c') + kExampleComDomain + ".";
173 const std::string kCnameD = std::string(kMaxmiumLabelSize, 'd') + kExampleComDomain + ".";
174 const std::vector<DnsRecord> kLargeCnameChainRecords = {
175         {kHelloExampleCom, ns_type::ns_t_cname, kCnameA},
176         {kCnameA, ns_type::ns_t_cname, kCnameB},
177         {kCnameB, ns_type::ns_t_cname, kCnameC},
178         {kCnameC, ns_type::ns_t_cname, kCnameD},
179         {kCnameD, ns_type::ns_t_a, kHelloExampleComAddrV4},
180 };
181 
182 // TODO: Integrate GetNumQueries relevent functions
183 size_t GetNumQueries(const test::DNSResponder& dns, const char* name);
184 size_t GetNumQueriesForProtocol(const test::DNSResponder& dns, const int protocol,
185                                 const char* name);
186 size_t GetNumQueriesForType(const test::DNSResponder& dns, ns_type type, const char* name);
187 std::string ToString(const hostent* he);
188 std::string ToString(const addrinfo* ai);
189 std::string ToString(const android::netdutils::ScopedAddrinfo& ai);
190 std::string ToString(const sockaddr_storage* addr);
191 std::vector<std::string> ToStrings(const hostent* he);
192 std::vector<std::string> ToStrings(const addrinfo* ai);
193 std::vector<std::string> ToStrings(const android::netdutils::ScopedAddrinfo& ai);
194 
195 // Wait for |condition| to be met until |timeout|.
196 bool PollForCondition(const std::function<bool()>& condition,
197                       std::chrono::milliseconds timeout = std::chrono::milliseconds(1000));
198