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 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 #ifndef _XFRM_CONTROLLER_H
17 #define _XFRM_CONTROLLER_H
18 
19 #include <atomic>
20 #include <list>
21 #include <map>
22 #include <string>
23 #include <utility> // for pair
24 
25 #include <linux/if.h>
26 #include <linux/if_link.h>
27 #include <linux/if_tunnel.h>
28 #include <linux/netlink.h>
29 #include <linux/udp.h>
30 #include <linux/xfrm.h>
31 #include <unistd.h>
32 
33 #include "NetdConstants.h"
34 #include "android-base/unique_fd.h"
35 #include "netdutils/DumpWriter.h"
36 #include "netdutils/Slice.h"
37 #include "netdutils/Status.h"
38 #include "sysutils/SocketClient.h"
39 
40 namespace android {
41 namespace net {
42 
43 // Exposed for testing
44 extern const uint32_t ALGO_MASK_AUTH_ALL;
45 // Exposed for testing
46 extern const uint32_t ALGO_MASK_CRYPT_ALL;
47 // Exposed for testing
48 extern const uint32_t ALGO_MASK_AEAD_ALL;
49 // Exposed for testing
50 extern const uint8_t REPLAY_WINDOW_SIZE;
51 
52 // Suggest we avoid the smallest and largest ints
53 class XfrmMessage;
54 class TransportModeSecurityAssociation;
55 
56 class XfrmSocket {
57 public:
58     // called from destructor and thus cannot be virtual
close()59     void close() {
60         if (mSock >= 0) {
61             ::close(mSock);
62         }
63         mSock = -1;
64     }
65 
66     virtual netdutils::Status open() = 0;
67 
~XfrmSocket()68     virtual ~XfrmSocket() { close(); }
69 
70     // Sends the netlink message contained in iovecs. This populates iovecs[0] with
71     // a valid netlink message header.
72     virtual netdutils::Status sendMessage(uint16_t nlMsgType, uint16_t nlMsgFlags,
73                                           uint16_t nlMsgSeqNum,
74                                           std::vector<iovec>* iovecs) const = 0;
75 
76 protected:
77     int mSock;
78 };
79 
80 enum struct XfrmDirection : uint8_t {
81     IN = XFRM_POLICY_IN,
82     OUT = XFRM_POLICY_OUT,
83     FORWARD = XFRM_POLICY_FWD,
84     MASK = XFRM_POLICY_MASK,
85 };
86 
87 enum struct XfrmMode : uint8_t {
88     TRANSPORT = XFRM_MODE_TRANSPORT,
89     TUNNEL = XFRM_MODE_TUNNEL,
90 };
91 
92 enum struct XfrmEncapType : uint16_t {
93     NONE = 0,
94     ESPINUDP_NON_IKE = UDP_ENCAP_ESPINUDP_NON_IKE,
95     ESPINUDP = UDP_ENCAP_ESPINUDP
96 };
97 
98 struct XfrmAlgo {
99     std::string name;
100     std::vector<uint8_t> key;
101     uint16_t truncLenBits;
102 };
103 
104 struct XfrmEncap {
105     XfrmEncapType type;
106     uint16_t srcPort;
107     uint16_t dstPort;
108 };
109 
110 // minimally sufficient structure to match either an SA or a Policy
111 struct XfrmCommonInfo {
112     xfrm_address_t dstAddr; // network order
113     xfrm_address_t srcAddr;
114     int addrFamily;  // AF_INET or AF_INET6
115     int transformId; // requestId
116     int spi;
117     xfrm_mark mark;
118     int xfrm_if_id;
119 };
120 
121 struct XfrmSaInfo : XfrmCommonInfo {
122     XfrmAlgo auth;
123     XfrmAlgo crypt;
124     XfrmAlgo aead;
125     int netId;
126     XfrmMode mode;
127     XfrmEncap encap;
128 };
129 
130 struct XfrmSpInfo : XfrmSaInfo {
131     // Address family in XfrmCommonInfo used for template/SA matching, need separate addrFamily
132     // for selectors
133     int selAddrFamily;  // AF_INET or AF_INET6
134 };
135 
136 /*
137  * This is a workaround for a kernel bug in the 32bit netlink compat layer
138  * that has been present on x86_64 kernels since 2010 with no fix on the
139  * horizon.
140  *
141  * Below is a redefinition of the xfrm_usersa_info struct that is part
142  * of the Linux uapi <linux/xfrm.h> to align the structures to a 64-bit
143  * boundary.
144  *
145  * Note that we turn this on for all x86 32bit targets, under the assumption
146  * that nowadays all x86 targets are running 64bit kernels.
147  */
148 #if defined(__i386__)
149 // Shadow the kernel definition of xfrm_usersa_info with a 64-bit aligned version
150 struct xfrm_usersa_info : ::xfrm_usersa_info {
151 } __attribute__((aligned(8)));
152 // Shadow the kernel's version, using the aligned version of xfrm_usersa_info
153 struct xfrm_userspi_info {
154     struct xfrm_usersa_info info;
155     __u32 min;
156     __u32 max;
157 };
158 struct xfrm_userpolicy_info : ::xfrm_userpolicy_info {
159 } __attribute__((aligned(8)));
160 
161 /*
162  * Anyone who encounters a failure when sending netlink messages should look here
163  * first. Hitting the static_assert() below should be a strong hint that Android
164  * IPsec will probably not work with your current settings.
165  *
166  * Again, experimentally determined, the "flags" field should be the first byte in
167  * the final word of the xfrm_usersa_info struct. The check validates the size of
168  * the padding to be 7.
169  *
170  * This padding is verified to be correct on gcc/x86_64 kernel, and clang/x86 userspace.
171  */
172 static_assert(sizeof(::xfrm_usersa_info) % 8 != 0,
173               "struct xfrm_usersa_info has changed "
174               "alignment. Please consider whether this "
175               "patch is needed.");
176 static_assert(sizeof(xfrm_usersa_info) - offsetof(xfrm_usersa_info, flags) == 8,
177               "struct xfrm_usersa_info probably misaligned with kernel struct.");
178 static_assert(sizeof(xfrm_usersa_info) % 8 == 0,
179               "struct xfrm_usersa_info_t is not 64-bit  "
180               "aligned. Please consider whether this patch "
181               "is needed.");
182 static_assert(sizeof(::xfrm_userspi_info) - sizeof(::xfrm_usersa_info) ==
183                       sizeof(xfrm_userspi_info) - sizeof(xfrm_usersa_info),
184               "struct xfrm_userspi_info has changed and does not match the kernel struct.");
185 static_assert(sizeof(::xfrm_userpolicy_info) % 8 != 0,
186               "struct xfrm_userpolicy_info has changed "
187               "alignment. Please consider whether this "
188               "patch is needed.");
189 static_assert(sizeof(xfrm_userpolicy_info) - offsetof(xfrm_userpolicy_info, share) == 5,
190               "struct xfrm_userpolicy_info probably misaligned with kernel struct.");
191 static_assert(sizeof(xfrm_userpolicy_info) % 8 == 0,
192               "struct xfrm_userpolicy_info is not 64-bit "
193               "aligned. Please consider whether this patch "
194               "is needed.");
195 #endif
196 
197 class XfrmController {
198 public:
199     XfrmController();
200 
201     // Initializer to override XFRM-I support for unit-testing purposes
202     explicit XfrmController(bool xfrmIntfSupport);
203 
204     static netdutils::Status Init();
205 
206     static netdutils::Status ipSecSetEncapSocketOwner(int socketFd, int newUid, uid_t callerUid);
207 
208     static netdutils::Status ipSecAllocateSpi(int32_t transformId, const std::string& localAddress,
209                                               const std::string& remoteAddress, int32_t inSpi,
210                                               int32_t* outSpi);
211 
212     static netdutils::Status ipSecAddSecurityAssociation(
213             int32_t transformId, int32_t mode, const std::string& sourceAddress,
214             const std::string& destinationAddress, int32_t underlyingNetId, int32_t spi,
215             int32_t markValue, int32_t markMask, const std::string& authAlgo,
216             const std::vector<uint8_t>& authKey, int32_t authTruncBits,
217             const std::string& cryptAlgo, const std::vector<uint8_t>& cryptKey,
218             int32_t cryptTruncBits, const std::string& aeadAlgo,
219             const std::vector<uint8_t>& aeadKey, int32_t aeadIcvBits, int32_t encapType,
220             int32_t encapLocalPort, int32_t encapRemotePort, int32_t xfrmInterfaceId);
221 
222     static netdutils::Status ipSecDeleteSecurityAssociation(int32_t transformId,
223                                                             const std::string& sourceAddress,
224                                                             const std::string& destinationAddress,
225                                                             int32_t spi, int32_t markValue,
226                                                             int32_t markMask,
227                                                             int32_t xfrmInterfaceId);
228 
229     static netdutils::Status ipSecApplyTransportModeTransform(int socketFd, int32_t transformId,
230                                                               int32_t direction,
231                                                               const std::string& localAddress,
232                                                               const std::string& remoteAddress,
233                                                               int32_t spi);
234 
235     static netdutils::Status ipSecRemoveTransportModeTransform(int socketFd);
236 
237     static netdutils::Status ipSecAddSecurityPolicy(int32_t transformId, int32_t selAddrFamily,
238                                                     int32_t direction,
239                                                     const std::string& tmplSrcAddress,
240                                                     const std::string& tmplDstAddress, int32_t spi,
241                                                     int32_t markValue, int32_t markMask,
242                                                     int32_t xfrmInterfaceId);
243 
244     static netdutils::Status ipSecUpdateSecurityPolicy(int32_t transformId, int32_t selAddrFamily,
245                                                        int32_t direction,
246                                                        const std::string& tmplSrcAddress,
247                                                        const std::string& tmplDstAddress,
248                                                        int32_t spi, int32_t markValue,
249                                                        int32_t markMask, int32_t xfrmInterfaceId);
250 
251     static netdutils::Status ipSecDeleteSecurityPolicy(int32_t transformId, int32_t selAddrFamily,
252                                                        int32_t direction, int32_t markValue,
253                                                        int32_t markMask, int32_t xfrmInterfaceId);
254 
255     static netdutils::Status ipSecAddTunnelInterface(const std::string& deviceName,
256                                                      const std::string& localAddress,
257                                                      const std::string& remoteAddress, int32_t ikey,
258                                                      int32_t okey, int32_t interfaceId,
259                                                      bool isUpdate);
260 
261     static netdutils::Status ipSecRemoveTunnelInterface(const std::string& deviceName);
262 
263     void dump(netdutils::DumpWriter& dw);
264 
265     // Some XFRM netlink attributes comprise a header, a struct, and some data
266     // after the struct. We wrap all of those in one struct for easier
267     // marshalling. The structs below must be ABI compatible with the kernel and
268     // are composed from kernel structures; thus, they use the kernel naming
269     // convention.
270 
271     // Exposed for testing
272     static constexpr size_t MAX_KEY_LENGTH = 128;
273 
274     // Container for the content of an XFRMA_ALG_CRYPT netlink attribute.
275     // Exposed for testing
276     struct nlattr_algo_crypt {
277         nlattr hdr;
278         xfrm_algo crypt;
279         uint8_t key[MAX_KEY_LENGTH];
280     };
281 
282     // Container for the content of an XFRMA_ALG_AUTH_TRUNC netlink attribute.
283     // Exposed for testing
284     struct nlattr_algo_auth {
285         nlattr hdr;
286         xfrm_algo_auth auth;
287         uint8_t key[MAX_KEY_LENGTH];
288     };
289 
290     // Container for the content of an XFRMA_TMPL netlink attribute.
291     // Exposed for testing
292     struct nlattr_algo_aead {
293         nlattr hdr;
294         xfrm_algo_aead aead;
295         uint8_t key[MAX_KEY_LENGTH];
296     };
297 
298     // Exposed for testing
299     struct nlattr_user_tmpl {
300         nlattr hdr;
301         xfrm_user_tmpl tmpl;
302     };
303 
304     // Container for the content of an XFRMA_ENCAP netlink attribute.
305     // Exposed for testing
306     struct nlattr_encap_tmpl {
307         nlattr hdr;
308         xfrm_encap_tmpl tmpl;
309     };
310 
311     // Container for the content of an XFRMA_MARK netlink attribute.
312     // Exposed for testing
313     struct nlattr_xfrm_mark {
314         nlattr hdr;
315         xfrm_mark mark;
316     };
317 
318     // Container for the content of an XFRMA_OUTPUT_MARK netlink attribute.
319     // Exposed for testing
320     struct nlattr_xfrm_output_mark {
321         nlattr hdr;
322         __u32 outputMark;
323     };
324 
325     // Container for the content of an XFRMA_IF_ID netlink attribute.
326     // Exposed for testing
327     struct nlattr_xfrm_interface_id {
328         nlattr hdr;
329         __u32 if_id;
330     };
331 
332     // Exposed for testing
333     struct nlattr_payload_u32 {
334         nlattr hdr;
335         uint32_t value;
336     };
337 
338   private:
339     static bool isXfrmIntfSupported();
340 
341     // helper functions for filling in the XfrmCommonInfo (and XfrmSaInfo) structure
342     static netdutils::Status fillXfrmCommonInfo(const std::string& sourceAddress,
343                                                 const std::string& destinationAddress, int32_t spi,
344                                                 int32_t markValue, int32_t markMask,
345                                                 int32_t transformId, int32_t xfrmInterfaceId,
346                                                 XfrmCommonInfo* info);
347     static netdutils::Status fillXfrmCommonInfo(int32_t spi, int32_t markValue, int32_t markMask,
348                                                 int32_t transformId, int32_t xfrmInterfaceId,
349                                                 XfrmCommonInfo* info);
350 
351     // Top level functions for managing a Transport Mode Transform
352     static netdutils::Status addTransportModeTransform(const XfrmSaInfo& record);
353     static int removeTransportModeTransform(const XfrmSaInfo& record);
354 
355     // TODO(messagerefactor): FACTOR OUT ALL MESSAGE BUILDING CODE BELOW HERE
356     // Shared between SA and SP
357     static void fillXfrmSelector(const int record, xfrm_selector* selector);
358 
359     // Shared between Transport and Tunnel Mode
360     static int fillNlAttrXfrmAlgoEnc(const XfrmAlgo& in_algo, nlattr_algo_crypt* algo);
361     static int fillNlAttrXfrmAlgoAuth(const XfrmAlgo& in_algo, nlattr_algo_auth* algo);
362     static int fillNlAttrXfrmAlgoAead(const XfrmAlgo& in_algo, nlattr_algo_aead* algo);
363     static int fillNlAttrXfrmEncapTmpl(const XfrmSaInfo& record, nlattr_encap_tmpl* tmpl);
364 
365     // Functions for updating a Transport Mode SA
366     static netdutils::Status updateSecurityAssociation(const XfrmSaInfo& record,
367                                                        const XfrmSocket& sock);
368     static int fillUserSaInfo(const XfrmSaInfo& record, xfrm_usersa_info* usersa);
369 
370     // Functions for deleting a Transport Mode SA
371     static netdutils::Status deleteSecurityAssociation(const XfrmCommonInfo& record,
372                                                        const XfrmSocket& sock);
373     static int fillUserSaId(const XfrmCommonInfo& record, xfrm_usersa_id* said);
374     static void fillUserTemplate(const XfrmSpInfo& record, xfrm_user_tmpl* tmpl);
375 
376     static int fillUserSpInfo(const XfrmSpInfo& record, XfrmDirection direction,
377                               xfrm_userpolicy_info* usersp);
378     static int fillNlAttrUserTemplate(const XfrmSpInfo& record, nlattr_user_tmpl* tmpl);
379     static int fillUserPolicyId(const XfrmSpInfo& record, XfrmDirection direction,
380                                 xfrm_userpolicy_id* policy_id);
381     static int fillNlAttrXfrmMark(const XfrmCommonInfo& record, nlattr_xfrm_mark* mark);
382     static int fillNlAttrXfrmOutputMark(const __u32 underlyingNetId,
383                                         nlattr_xfrm_output_mark* output_mark);
384     static int fillNlAttrXfrmIntfId(const __u32 intf_id_value, nlattr_xfrm_interface_id* intf_id);
385 
386     static netdutils::Status allocateSpi(const XfrmSaInfo& record, uint32_t minSpi, uint32_t maxSpi,
387                                          uint32_t* outSpi, const XfrmSocket& sock);
388 
389     static netdutils::Status processSecurityPolicy(int32_t transformId, int32_t selAddrFamily,
390                                                    int32_t direction,
391                                                    const std::string& tmplSrcAddress,
392                                                    const std::string& tmplDstAddress, int32_t spi,
393                                                    int32_t markValue, int32_t markMask,
394                                                    int32_t xfrmInterfaceId, int32_t msgType);
395     static netdutils::Status updateTunnelModeSecurityPolicy(const XfrmSpInfo& record,
396                                                             const XfrmSocket& sock,
397                                                             XfrmDirection direction,
398                                                             uint16_t msgType);
399     static netdutils::Status deleteTunnelModeSecurityPolicy(const XfrmSpInfo& record,
400                                                             const XfrmSocket& sock,
401                                                             XfrmDirection direction);
402     static netdutils::Status flushInterfaces();
403     static netdutils::Status flushSaDb(const XfrmSocket& s);
404     static netdutils::Status flushPolicyDb(const XfrmSocket& s);
405 
406     static netdutils::Status ipSecAddXfrmInterface(const std::string& deviceName,
407                                                    int32_t interfaceId, uint16_t flags);
408     static netdutils::Status ipSecAddVirtualTunnelInterface(const std::string& deviceName,
409                                                             const std::string& localAddress,
410                                                             const std::string& remoteAddress,
411                                                             int32_t ikey, int32_t okey,
412                                                             uint16_t flags);
413     // END TODO(messagerefactor)
414 };
415 
416 } // namespace net
417 } // namespace android
418 
419 #endif /* !defined(XFRM_CONTROLLER_H) */
420