blob: 599485b11c72ecf95a1879d98715f8aec37893da [file] [log] [blame]
Nathan Harold1afbef42017-03-01 18:55:06 -08001/*
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
17package com.android.server;
18
19import static android.Manifest.permission.DUMP;
Nathan Harold93962f32017-03-07 13:23:36 -080020import static android.net.IpSecManager.INVALID_RESOURCE_ID;
Nathan Harold8dc1fd02017-04-04 19:37:48 -070021import static android.system.OsConstants.AF_INET;
evitayane4259d32018-03-22 17:53:08 -070022import static android.system.OsConstants.AF_INET6;
23import static android.system.OsConstants.AF_UNSPEC;
manojboopathic4be79d2017-11-30 17:11:49 -080024import static android.system.OsConstants.EINVAL;
Nathan Harold8dc1fd02017-04-04 19:37:48 -070025import static android.system.OsConstants.IPPROTO_UDP;
26import static android.system.OsConstants.SOCK_DGRAM;
Benedict Wongab80e1f2018-07-25 18:46:19 -070027
Nathan Harold21208ee2018-03-15 18:06:06 -070028import android.annotation.NonNull;
29import android.app.AppOpsManager;
Nathan Harold1afbef42017-03-01 18:55:06 -080030import android.content.Context;
Benedict Wong24452272019-02-25 12:33:22 -080031import android.content.pm.PackageManager;
Nathan Harold1afbef42017-03-01 18:55:06 -080032import android.net.IIpSecService;
33import android.net.INetd;
Nathan Harold93962f32017-03-07 13:23:36 -080034import android.net.IpSecAlgorithm;
35import android.net.IpSecConfig;
36import android.net.IpSecManager;
Nathan Harold8dc1fd02017-04-04 19:37:48 -070037import android.net.IpSecSpiResponse;
Nathan Harold93962f32017-03-07 13:23:36 -080038import android.net.IpSecTransform;
Nathan Harold8dc1fd02017-04-04 19:37:48 -070039import android.net.IpSecTransformResponse;
Benedict Wong8149f6e2018-01-18 18:31:45 -080040import android.net.IpSecTunnelInterfaceResponse;
Nathan Harold8dc1fd02017-04-04 19:37:48 -070041import android.net.IpSecUdpEncapResponse;
Benedict Wongecc9f7c2018-03-01 18:53:07 -080042import android.net.LinkAddress;
Benedict Wong8149f6e2018-01-18 18:31:45 -080043import android.net.Network;
Nathan Harolda10003d2017-08-23 13:46:33 -070044import android.net.NetworkUtils;
Benedict Wongbabe5d72017-12-03 19:42:36 -080045import android.net.TrafficStats;
Remi NGUYEN VAN231b52b2019-01-29 15:38:52 +090046import android.net.util.NetdService;
Nathan Harold93962f32017-03-07 13:23:36 -080047import android.os.Binder;
Nathan Harold93962f32017-03-07 13:23:36 -080048import android.os.IBinder;
49import android.os.ParcelFileDescriptor;
Nathan Harold1afbef42017-03-01 18:55:06 -080050import android.os.RemoteException;
Nathan Harold93962f32017-03-07 13:23:36 -080051import android.os.ServiceSpecificException;
Nathan Harold8dc1fd02017-04-04 19:37:48 -070052import android.system.ErrnoException;
53import android.system.Os;
54import android.system.OsConstants;
Nathan Harolda10003d2017-08-23 13:46:33 -070055import android.text.TextUtils;
Nathan Harold1afbef42017-03-01 18:55:06 -080056import android.util.Log;
57import android.util.Slog;
Nathan Harold93962f32017-03-07 13:23:36 -080058import android.util.SparseArray;
Benedict Wong8149f6e2018-01-18 18:31:45 -080059import android.util.SparseBooleanArray;
Nathan Harolda10003d2017-08-23 13:46:33 -070060
Nathan Harold93962f32017-03-07 13:23:36 -080061import com.android.internal.annotations.GuardedBy;
ludi1a06aa72017-05-12 09:15:00 -070062import com.android.internal.annotations.VisibleForTesting;
Benedict Wong4f255702017-11-06 20:49:10 -080063import com.android.internal.util.Preconditions;
Nathan Harolda10003d2017-08-23 13:46:33 -070064
Benedict Wongab80e1f2018-07-25 18:46:19 -070065import libcore.io.IoUtils;
66
Nathan Harold1afbef42017-03-01 18:55:06 -080067import java.io.FileDescriptor;
Nathan Harold8dc1fd02017-04-04 19:37:48 -070068import java.io.IOException;
Nathan Harold1afbef42017-03-01 18:55:06 -080069import java.io.PrintWriter;
evitayane4259d32018-03-22 17:53:08 -070070import java.net.Inet4Address;
71import java.net.Inet6Address;
Nathan Harold8dc1fd02017-04-04 19:37:48 -070072import java.net.InetAddress;
73import java.net.InetSocketAddress;
74import java.net.UnknownHostException;
Benedict Wong409c8ca2017-10-26 19:41:43 -070075import java.util.ArrayList;
76import java.util.List;
Daulet Zhanguzinea1a7ca2020-01-03 09:46:50 +000077import java.util.Objects;
Nathan Harolda10003d2017-08-23 13:46:33 -070078
Benedict Wong409c8ca2017-10-26 19:41:43 -070079/**
80 * A service to manage multiple clients that want to access the IpSec API. The service is
81 * responsible for maintaining a list of clients and managing the resources (and related quotas)
82 * that each of them own.
83 *
84 * <p>Synchronization in IpSecService is done on all entrypoints due to potential race conditions at
85 * the kernel/xfrm level. Further, this allows the simplifying assumption to be made that only one
86 * thread is ever running at a time.
87 *
88 * @hide
89 */
Nathan Harold1afbef42017-03-01 18:55:06 -080090public class IpSecService extends IIpSecService.Stub {
91 private static final String TAG = "IpSecService";
92 private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Nathan Harold8dc1fd02017-04-04 19:37:48 -070093
Nathan Harold1afbef42017-03-01 18:55:06 -080094 private static final String NETD_SERVICE_NAME = "netd";
Benedict Wong564e2aa2018-05-07 20:06:44 -070095 private static final int[] ADDRESS_FAMILIES =
96 new int[] {OsConstants.AF_INET, OsConstants.AF_INET6};
Nathan Harold1afbef42017-03-01 18:55:06 -080097
ludi1a06aa72017-05-12 09:15:00 -070098 private static final int NETD_FETCH_TIMEOUT_MS = 5000; // ms
Nathan Harold8dc1fd02017-04-04 19:37:48 -070099 private static final InetAddress INADDR_ANY;
100
Benedict Wongabcc6c02019-03-20 09:44:09 -0700101 @VisibleForTesting static final int MAX_PORT_BIND_ATTEMPTS = 10;
102
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700103 static {
104 try {
105 INADDR_ANY = InetAddress.getByAddress(new byte[] {0, 0, 0, 0});
106 } catch (UnknownHostException e) {
107 throw new RuntimeException(e);
108 }
109 }
110
111 static final int FREE_PORT_MIN = 1024; // ports 1-1023 are reserved
112 static final int PORT_MAX = 0xFFFF; // ports are an unsigned 16-bit integer
113
114 /* Binder context for this service */
Nathan Harold1afbef42017-03-01 18:55:06 -0800115 private final Context mContext;
116
Nathan Haroldd8c74292017-12-13 19:16:33 -0800117 /**
Nathan Harolda2523312018-01-05 19:25:13 -0800118 * The next non-repeating global ID for tracking resources between users, this service, and
119 * kernel data structures. Accessing this variable is not thread safe, so it is only read or
120 * modified within blocks synchronized on IpSecService.this. We want to avoid -1
121 * (INVALID_RESOURCE_ID) and 0 (we probably forgot to initialize it).
Nathan Haroldd8c74292017-12-13 19:16:33 -0800122 */
123 @GuardedBy("IpSecService.this")
124 private int mNextResourceId = 1;
Nathan Harold1afbef42017-03-01 18:55:06 -0800125
ludi1a06aa72017-05-12 09:15:00 -0700126 interface IpSecServiceConfiguration {
127 INetd getNetdInstance() throws RemoteException;
128
129 static IpSecServiceConfiguration GETSRVINSTANCE =
130 new IpSecServiceConfiguration() {
131 @Override
132 public INetd getNetdInstance() throws RemoteException {
133 final INetd netd = NetdService.getInstance();
134 if (netd == null) {
135 throw new RemoteException("Failed to Get Netd Instance");
136 }
137 return netd;
138 }
139 };
140 }
141
142 private final IpSecServiceConfiguration mSrvConfig;
Benedict Wongbabe5d72017-12-03 19:42:36 -0800143 final UidFdTagger mUidFdTagger;
ludi1a06aa72017-05-12 09:15:00 -0700144
Benedict Wong409c8ca2017-10-26 19:41:43 -0700145 /**
146 * Interface for user-reference and kernel-resource cleanup.
147 *
148 * <p>This interface must be implemented for a resource to be reference counted.
149 */
150 @VisibleForTesting
151 public interface IResource {
152 /**
153 * Invalidates a IResource object, ensuring it is invalid for the purposes of allocating new
154 * objects dependent on it.
155 *
156 * <p>Implementations of this method are expected to remove references to the IResource
157 * object from the IpSecService's tracking arrays. The removal from the arrays ensures that
158 * the resource is considered invalid for user access or allocation or use in other
159 * resources.
160 *
161 * <p>References to the IResource object may be held by other RefcountedResource objects,
Benedict Wong4f9fb812017-12-13 17:16:53 -0800162 * and as such, the underlying resources and quota may not be cleaned up.
Benedict Wong409c8ca2017-10-26 19:41:43 -0700163 */
164 void invalidate() throws RemoteException;
165
166 /**
167 * Releases underlying resources and related quotas.
168 *
169 * <p>Implementations of this method are expected to remove all system resources that are
170 * tracked by the IResource object. Due to other RefcountedResource objects potentially
Benedict Wong344bd622017-11-16 15:27:22 -0800171 * having references to the IResource object, freeUnderlyingResources may not always be
Benedict Wong409c8ca2017-10-26 19:41:43 -0700172 * called from releaseIfUnreferencedRecursively().
173 */
174 void freeUnderlyingResources() throws RemoteException;
175 }
176
177 /**
178 * RefcountedResource manages references and dependencies in an exclusively acyclic graph.
179 *
180 * <p>RefcountedResource implements both explicit and implicit resource management. Creating a
181 * RefcountedResource object creates an explicit reference that must be freed by calling
182 * userRelease(). Additionally, adding this object as a child of another RefcountedResource
183 * object will add an implicit reference.
184 *
185 * <p>Resources are cleaned up when all references, both implicit and explicit, are released
186 * (ie, when userRelease() is called and when all parents have called releaseReference() on this
187 * object.)
188 */
189 @VisibleForTesting
190 public class RefcountedResource<T extends IResource> implements IBinder.DeathRecipient {
Junyu Lai4e645f32019-04-26 01:38:04 +0000191 private final T mResource;
192 private final List<RefcountedResource> mChildren;
Benedict Wong24452272019-02-25 12:33:22 -0800193 int mRefCount = 1; // starts at 1 for user's reference.
Junyu Lai4e645f32019-04-26 01:38:04 +0000194 IBinder mBinder;
Benedict Wong24452272019-02-25 12:33:22 -0800195
Junyu Lai4e645f32019-04-26 01:38:04 +0000196 RefcountedResource(T resource, IBinder binder, RefcountedResource... children) {
Benedict Wong409c8ca2017-10-26 19:41:43 -0700197 synchronized (IpSecService.this) {
198 this.mResource = resource;
Junyu Lai4e645f32019-04-26 01:38:04 +0000199 this.mChildren = new ArrayList<>(children.length);
Benedict Wong409c8ca2017-10-26 19:41:43 -0700200 this.mBinder = binder;
Junyu Lai4e645f32019-04-26 01:38:04 +0000201
Benedict Wong409c8ca2017-10-26 19:41:43 -0700202 for (RefcountedResource child : children) {
Junyu Lai4e645f32019-04-26 01:38:04 +0000203 mChildren.add(child);
Benedict Wong409c8ca2017-10-26 19:41:43 -0700204 child.mRefCount++;
205 }
206
207 try {
Junyu Lai4e645f32019-04-26 01:38:04 +0000208 mBinder.linkToDeath(this, 0);
Benedict Wong409c8ca2017-10-26 19:41:43 -0700209 } catch (RemoteException e) {
210 binderDied();
Benedict Wongccfaa3c2019-02-28 20:28:48 -0800211 e.rethrowFromSystemServer();
Benedict Wong409c8ca2017-10-26 19:41:43 -0700212 }
213 }
214 }
215
216 /**
217 * If the Binder object dies, this function is called to free the system resources that are
Benedict Wong344bd622017-11-16 15:27:22 -0800218 * being tracked by this record and to subsequently release this record for garbage
Benedict Wong409c8ca2017-10-26 19:41:43 -0700219 * collection
220 */
221 @Override
222 public void binderDied() {
223 synchronized (IpSecService.this) {
224 try {
225 userRelease();
226 } catch (Exception e) {
227 Log.e(TAG, "Failed to release resource: " + e);
228 }
229 }
230 }
231
232 public T getResource() {
233 return mResource;
234 }
235
236 /**
237 * Unlinks from binder and performs IpSecService resource cleanup (removes from resource
238 * arrays)
239 *
240 * <p>If this method has been previously called, the RefcountedResource's binder field will
241 * be null, and the method will return without performing the cleanup a second time.
242 *
243 * <p>Note that calling this function does not imply that kernel resources will be freed at
244 * this time, or that the related quota will be returned. Such actions will only be
245 * performed upon the reference count reaching zero.
246 */
247 @GuardedBy("IpSecService.this")
248 public void userRelease() throws RemoteException {
249 // Prevent users from putting reference counts into a bad state by calling
250 // userRelease() multiple times.
251 if (mBinder == null) {
252 return;
253 }
254
Junyu Lai4e645f32019-04-26 01:38:04 +0000255 mBinder.unlinkToDeath(this, 0);
Benedict Wong409c8ca2017-10-26 19:41:43 -0700256 mBinder = null;
257
258 mResource.invalidate();
Junyu Lai4e645f32019-04-26 01:38:04 +0000259
Benedict Wong409c8ca2017-10-26 19:41:43 -0700260 releaseReference();
261 }
262
263 /**
264 * Removes a reference to this resource. If the resultant reference count is zero, the
265 * underlying resources are freed, and references to all child resources are also dropped
266 * recursively (resulting in them freeing their resources and children, etcetera)
267 *
268 * <p>This method also sets the reference count to an invalid value (-1) to signify that it
269 * has been fully released. Any subsequent calls to this method will result in an
270 * IllegalStateException being thrown due to resource already having been previously
271 * released
272 */
273 @VisibleForTesting
274 @GuardedBy("IpSecService.this")
275 public void releaseReference() throws RemoteException {
276 mRefCount--;
277
278 if (mRefCount > 0) {
279 return;
280 } else if (mRefCount < 0) {
281 throw new IllegalStateException(
282 "Invalid operation - resource has already been released.");
283 }
284
285 // Cleanup own resources
286 mResource.freeUnderlyingResources();
287
288 // Cleanup child resources as needed
289 for (RefcountedResource<? extends IResource> child : mChildren) {
290 child.releaseReference();
291 }
292
293 // Enforce that resource cleanup can only be called once
294 // By decrementing the refcount (from 0 to -1), the next call will throw an
295 // IllegalStateException - it has already been released fully.
296 mRefCount--;
297 }
298
299 @Override
300 public String toString() {
301 return new StringBuilder()
302 .append("{mResource=")
303 .append(mResource)
304 .append(", mRefCount=")
305 .append(mRefCount)
306 .append(", mChildren=")
307 .append(mChildren)
308 .append("}")
309 .toString();
310 }
311 }
312
Benedict Wong4f9fb812017-12-13 17:16:53 -0800313 /**
314 * Very simple counting class that looks much like a counting semaphore
315 *
316 * <p>This class is not thread-safe, and expects that that users of this class will ensure
317 * synchronization and thread safety by holding the IpSecService.this instance lock.
318 */
Benedict Wong344bd622017-11-16 15:27:22 -0800319 @VisibleForTesting
320 static class ResourceTracker {
Nathan Harolda1afbd82017-04-24 16:16:34 -0700321 private final int mMax;
322 int mCurrent;
323
324 ResourceTracker(int max) {
325 mMax = max;
326 mCurrent = 0;
327 }
328
Benedict Wong344bd622017-11-16 15:27:22 -0800329 boolean isAvailable() {
Nathan Harolda1afbd82017-04-24 16:16:34 -0700330 return (mCurrent < mMax);
331 }
332
Benedict Wong344bd622017-11-16 15:27:22 -0800333 void take() {
Nathan Harolda1afbd82017-04-24 16:16:34 -0700334 if (!isAvailable()) {
335 Log.wtf(TAG, "Too many resources allocated!");
336 }
337 mCurrent++;
338 }
339
Benedict Wong344bd622017-11-16 15:27:22 -0800340 void give() {
Nathan Harolda1afbd82017-04-24 16:16:34 -0700341 if (mCurrent <= 0) {
342 Log.wtf(TAG, "We've released this resource too many times");
343 }
344 mCurrent--;
345 }
ludi3e5ea232017-08-10 15:44:40 -0700346
347 @Override
348 public String toString() {
349 return new StringBuilder()
350 .append("{mCurrent=")
351 .append(mCurrent)
352 .append(", mMax=")
353 .append(mMax)
354 .append("}")
355 .toString();
356 }
Nathan Harolda1afbd82017-04-24 16:16:34 -0700357 }
358
Benedict Wong344bd622017-11-16 15:27:22 -0800359 @VisibleForTesting
360 static final class UserRecord {
Benedict Wong344bd622017-11-16 15:27:22 -0800361 /* Maximum number of each type of resource that a single UID may possess */
Automerger Merge Workera3769202020-03-25 00:49:05 +0000362
363 // Up to 4 active VPNs/IWLAN with potential soft handover.
364 public static final int MAX_NUM_TUNNEL_INTERFACES = 8;
365 public static final int MAX_NUM_ENCAP_SOCKETS = 16;
366
367 // SPIs and Transforms are both cheap, and are 1:1 correlated.
368 public static final int MAX_NUM_TRANSFORMS = 64;
369 public static final int MAX_NUM_SPIS = 64;
Nathan Harolda1afbd82017-04-24 16:16:34 -0700370
Benedict Wong4f9fb812017-12-13 17:16:53 -0800371 /**
372 * Store each of the OwnedResource types in an (thinly wrapped) sparse array for indexing
373 * and explicit (user) reference management.
374 *
375 * <p>These are stored in separate arrays to improve debuggability and dump output clarity.
376 *
377 * <p>Resources are removed from this array when the user releases their explicit reference
378 * by calling one of the releaseResource() methods.
379 */
Benedict Wong344bd622017-11-16 15:27:22 -0800380 final RefcountedResourceArray<SpiRecord> mSpiRecords =
Benedict Wong4f9fb812017-12-13 17:16:53 -0800381 new RefcountedResourceArray<>(SpiRecord.class.getSimpleName());
Benedict Wong344bd622017-11-16 15:27:22 -0800382 final RefcountedResourceArray<TransformRecord> mTransformRecords =
Benedict Wong4f9fb812017-12-13 17:16:53 -0800383 new RefcountedResourceArray<>(TransformRecord.class.getSimpleName());
Benedict Wong344bd622017-11-16 15:27:22 -0800384 final RefcountedResourceArray<EncapSocketRecord> mEncapSocketRecords =
Benedict Wong4f9fb812017-12-13 17:16:53 -0800385 new RefcountedResourceArray<>(EncapSocketRecord.class.getSimpleName());
Benedict Wong8149f6e2018-01-18 18:31:45 -0800386 final RefcountedResourceArray<TunnelInterfaceRecord> mTunnelInterfaceRecords =
387 new RefcountedResourceArray<>(TunnelInterfaceRecord.class.getSimpleName());
Benedict Wong4f9fb812017-12-13 17:16:53 -0800388
389 /**
390 * Trackers for quotas for each of the OwnedResource types.
391 *
392 * <p>These trackers are separate from the resource arrays, since they are incremented and
393 * decremented at different points in time. Specifically, quota is only returned upon final
394 * resource deallocation (after all explicit and implicit references are released). Note
395 * that it is possible that calls to releaseResource() will not return the used quota if
396 * there are other resources that depend on (are parents of) the resource being released.
397 */
398 final ResourceTracker mSpiQuotaTracker = new ResourceTracker(MAX_NUM_SPIS);
399 final ResourceTracker mTransformQuotaTracker = new ResourceTracker(MAX_NUM_TRANSFORMS);
Benedict Wong344bd622017-11-16 15:27:22 -0800400 final ResourceTracker mSocketQuotaTracker = new ResourceTracker(MAX_NUM_ENCAP_SOCKETS);
Benedict Wong8149f6e2018-01-18 18:31:45 -0800401 final ResourceTracker mTunnelQuotaTracker = new ResourceTracker(MAX_NUM_TUNNEL_INTERFACES);
Benedict Wong344bd622017-11-16 15:27:22 -0800402
403 void removeSpiRecord(int resourceId) {
404 mSpiRecords.remove(resourceId);
Nathan Harolda1afbd82017-04-24 16:16:34 -0700405 }
406
Benedict Wong344bd622017-11-16 15:27:22 -0800407 void removeTransformRecord(int resourceId) {
408 mTransformRecords.remove(resourceId);
409 }
410
Benedict Wong8149f6e2018-01-18 18:31:45 -0800411 void removeTunnelInterfaceRecord(int resourceId) {
412 mTunnelInterfaceRecords.remove(resourceId);
413 }
414
Benedict Wong344bd622017-11-16 15:27:22 -0800415 void removeEncapSocketRecord(int resourceId) {
416 mEncapSocketRecords.remove(resourceId);
417 }
418
419 @Override
420 public String toString() {
421 return new StringBuilder()
422 .append("{mSpiQuotaTracker=")
423 .append(mSpiQuotaTracker)
424 .append(", mTransformQuotaTracker=")
425 .append(mTransformQuotaTracker)
426 .append(", mSocketQuotaTracker=")
427 .append(mSocketQuotaTracker)
Benedict Wongb8ef5412018-01-24 15:31:39 -0800428 .append(", mTunnelQuotaTracker=")
429 .append(mTunnelQuotaTracker)
Benedict Wong344bd622017-11-16 15:27:22 -0800430 .append(", mSpiRecords=")
431 .append(mSpiRecords)
432 .append(", mTransformRecords=")
433 .append(mTransformRecords)
434 .append(", mEncapSocketRecords=")
435 .append(mEncapSocketRecords)
Benedict Wongb8ef5412018-01-24 15:31:39 -0800436 .append(", mTunnelInterfaceRecords=")
437 .append(mTunnelInterfaceRecords)
Benedict Wong344bd622017-11-16 15:27:22 -0800438 .append("}")
439 .toString();
440 }
441 }
442
Benedict Wong4f9fb812017-12-13 17:16:53 -0800443 /**
444 * This class is not thread-safe, and expects that that users of this class will ensure
445 * synchronization and thread safety by holding the IpSecService.this instance lock.
446 */
Benedict Wong344bd622017-11-16 15:27:22 -0800447 @VisibleForTesting
448 static final class UserResourceTracker {
Nathan Harolda1afbd82017-04-24 16:16:34 -0700449 private final SparseArray<UserRecord> mUserRecords = new SparseArray<>();
450
Benedict Wong4f9fb812017-12-13 17:16:53 -0800451 /** Lazy-initialization/getter that populates or retrieves the UserRecord as needed */
Benedict Wong344bd622017-11-16 15:27:22 -0800452 public UserRecord getUserRecord(int uid) {
453 checkCallerUid(uid);
454
Nathan Harolda1afbd82017-04-24 16:16:34 -0700455 UserRecord r = mUserRecords.get(uid);
456 if (r == null) {
457 r = new UserRecord();
458 mUserRecords.put(uid, r);
459 }
460 return r;
461 }
ludi3e5ea232017-08-10 15:44:40 -0700462
Benedict Wong344bd622017-11-16 15:27:22 -0800463 /** Safety method; guards against access of other user's UserRecords */
464 private void checkCallerUid(int uid) {
465 if (uid != Binder.getCallingUid()
466 && android.os.Process.SYSTEM_UID != Binder.getCallingUid()) {
467 throw new SecurityException("Attempted access of unowned resources");
468 }
469 }
470
ludi3e5ea232017-08-10 15:44:40 -0700471 @Override
472 public String toString() {
473 return mUserRecords.toString();
474 }
Nathan Harolda1afbd82017-04-24 16:16:34 -0700475 }
476
Benedict Wong344bd622017-11-16 15:27:22 -0800477 @VisibleForTesting final UserResourceTracker mUserResourceTracker = new UserResourceTracker();
Nathan Harolda1afbd82017-04-24 16:16:34 -0700478
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700479 /**
Benedict Wong4f9fb812017-12-13 17:16:53 -0800480 * The OwnedResourceRecord class provides a facility to cleanly and reliably track system
Benedict Wong344bd622017-11-16 15:27:22 -0800481 * resources. It relies on a provided resourceId that should uniquely identify the kernel
482 * resource. To use this class, the user should implement the invalidate() and
483 * freeUnderlyingResources() methods that are responsible for cleaning up IpSecService resource
Benedict Wong4f9fb812017-12-13 17:16:53 -0800484 * tracking arrays and kernel resources, respectively.
485 *
486 * <p>This class associates kernel resources with the UID that owns and controls them.
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700487 */
Benedict Wong4f9fb812017-12-13 17:16:53 -0800488 private abstract class OwnedResourceRecord implements IResource {
Nathan Harold93962f32017-03-07 13:23:36 -0800489 final int pid;
490 final int uid;
Benedict Wong344bd622017-11-16 15:27:22 -0800491 protected final int mResourceId;
Nathan Harold93962f32017-03-07 13:23:36 -0800492
Benedict Wong4f9fb812017-12-13 17:16:53 -0800493 OwnedResourceRecord(int resourceId) {
Nathan Harold93962f32017-03-07 13:23:36 -0800494 super();
Nathan Harolda1afbd82017-04-24 16:16:34 -0700495 if (resourceId == INVALID_RESOURCE_ID) {
496 throw new IllegalArgumentException("Resource ID must not be INVALID_RESOURCE_ID");
497 }
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700498 mResourceId = resourceId;
Nathan Harold93962f32017-03-07 13:23:36 -0800499 pid = Binder.getCallingPid();
500 uid = Binder.getCallingUid();
501
Nathan Harolda1afbd82017-04-24 16:16:34 -0700502 getResourceTracker().take();
Nathan Harold93962f32017-03-07 13:23:36 -0800503 }
504
Benedict Wong344bd622017-11-16 15:27:22 -0800505 @Override
506 public abstract void invalidate() throws RemoteException;
507
508 /** Convenience method; retrieves the user resource record for the stored UID. */
509 protected UserRecord getUserRecord() {
510 return mUserResourceTracker.getUserRecord(uid);
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700511 }
512
Benedict Wong344bd622017-11-16 15:27:22 -0800513 @Override
514 public abstract void freeUnderlyingResources() throws RemoteException;
ludib0c95b12017-05-22 10:52:23 -0700515
Nathan Harolda1afbd82017-04-24 16:16:34 -0700516 /** Get the resource tracker for this resource */
517 protected abstract ResourceTracker getResourceTracker();
518
ludib0c95b12017-05-22 10:52:23 -0700519 @Override
520 public String toString() {
521 return new StringBuilder()
522 .append("{mResourceId=")
523 .append(mResourceId)
524 .append(", pid=")
525 .append(pid)
526 .append(", uid=")
527 .append(uid)
ludib0c95b12017-05-22 10:52:23 -0700528 .append("}")
529 .toString();
530 }
Nathan Harold93962f32017-03-07 13:23:36 -0800531 };
532
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700533 /**
Benedict Wong344bd622017-11-16 15:27:22 -0800534 * Thin wrapper over SparseArray to ensure resources exist, and simplify generic typing.
535 *
536 * <p>RefcountedResourceArray prevents null insertions, and throws an IllegalArgumentException
537 * if a key is not found during a retrieval process.
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700538 */
Benedict Wong344bd622017-11-16 15:27:22 -0800539 static class RefcountedResourceArray<T extends IResource> {
540 SparseArray<RefcountedResource<T>> mArray = new SparseArray<>();
541 private final String mTypeName;
Nathan Harold93962f32017-03-07 13:23:36 -0800542
Benedict Wong344bd622017-11-16 15:27:22 -0800543 public RefcountedResourceArray(String typeName) {
544 this.mTypeName = typeName;
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700545 }
546
Benedict Wong344bd622017-11-16 15:27:22 -0800547 /**
548 * Accessor method to get inner resource object.
549 *
550 * @throws IllegalArgumentException if no resource with provided key is found.
551 */
552 T getResourceOrThrow(int key) {
553 return getRefcountedResourceOrThrow(key).getResource();
554 }
555
556 /**
557 * Accessor method to get reference counting wrapper.
558 *
559 * @throws IllegalArgumentException if no resource with provided key is found.
560 */
561 RefcountedResource<T> getRefcountedResourceOrThrow(int key) {
562 RefcountedResource<T> resource = mArray.get(key);
563 if (resource == null) {
564 throw new IllegalArgumentException(
565 String.format("No such %s found for given id: %d", mTypeName, key));
566 }
567
568 return resource;
569 }
570
571 void put(int key, RefcountedResource<T> obj) {
Daulet Zhanguzinea1a7ca2020-01-03 09:46:50 +0000572 Objects.requireNonNull(obj, "Null resources cannot be added");
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700573 mArray.put(key, obj);
574 }
575
576 void remove(int key) {
577 mArray.remove(key);
578 }
ludib0c95b12017-05-22 10:52:23 -0700579
580 @Override
581 public String toString() {
582 return mArray.toString();
583 }
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700584 }
585
Benedict Wong4f9fb812017-12-13 17:16:53 -0800586 /**
587 * Tracks an SA in the kernel, and manages cleanup paths. Once a TransformRecord is
588 * created, the SpiRecord that originally tracked the SAs will reliquish the
589 * responsibility of freeing the underlying SA to this class via the mOwnedByTransform flag.
590 */
591 private final class TransformRecord extends OwnedResourceRecord {
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700592 private final IpSecConfig mConfig;
Nathan Harolda2523312018-01-05 19:25:13 -0800593 private final SpiRecord mSpi;
Benedict Wong344bd622017-11-16 15:27:22 -0800594 private final EncapSocketRecord mSocket;
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700595
596 TransformRecord(
Nathan Harolda2523312018-01-05 19:25:13 -0800597 int resourceId, IpSecConfig config, SpiRecord spi, EncapSocketRecord socket) {
Benedict Wong344bd622017-11-16 15:27:22 -0800598 super(resourceId);
Nathan Harold93962f32017-03-07 13:23:36 -0800599 mConfig = config;
Nathan Harolda2523312018-01-05 19:25:13 -0800600 mSpi = spi;
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700601 mSocket = socket;
Benedict Wonge6b42772017-12-13 18:26:40 -0800602
603 spi.setOwnedByTransform();
Nathan Harold93962f32017-03-07 13:23:36 -0800604 }
605
606 public IpSecConfig getConfig() {
607 return mConfig;
608 }
609
Nathan Harolda2523312018-01-05 19:25:13 -0800610 public SpiRecord getSpiRecord() {
611 return mSpi;
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700612 }
613
Benedict Wong0fe58a92018-01-19 17:36:02 -0800614 public EncapSocketRecord getSocketRecord() {
615 return mSocket;
616 }
617
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700618 /** always guarded by IpSecService#this */
Nathan Harold93962f32017-03-07 13:23:36 -0800619 @Override
Benedict Wong344bd622017-11-16 15:27:22 -0800620 public void freeUnderlyingResources() {
Nathan Harolda2523312018-01-05 19:25:13 -0800621 int spi = mSpi.getSpi();
622 try {
623 mSrvConfig
624 .getNetdInstance()
625 .ipSecDeleteSecurityAssociation(
Benedict Wonga0989622018-07-25 13:06:29 -0700626 uid,
Nathan Harolda2523312018-01-05 19:25:13 -0800627 mConfig.getSourceAddress(),
628 mConfig.getDestinationAddress(),
Di Lu0b611f42018-01-11 11:35:25 -0800629 spi,
630 mConfig.getMarkValue(),
Benedict Wong781dae62018-09-06 11:31:25 -0700631 mConfig.getMarkMask(),
632 mConfig.getXfrmInterfaceId());
Benedict Wongecc9f7c2018-03-01 18:53:07 -0800633 } catch (RemoteException | ServiceSpecificException e) {
634 Log.e(TAG, "Failed to delete SA with ID: " + mResourceId, e);
Nathan Harold93962f32017-03-07 13:23:36 -0800635 }
Nathan Harold93962f32017-03-07 13:23:36 -0800636
Benedict Wong344bd622017-11-16 15:27:22 -0800637 getResourceTracker().give();
Nathan Harold93962f32017-03-07 13:23:36 -0800638 }
ludib0c95b12017-05-22 10:52:23 -0700639
Benedict Wong344bd622017-11-16 15:27:22 -0800640 @Override
641 public void invalidate() throws RemoteException {
642 getUserRecord().removeTransformRecord(mResourceId);
643 }
644
645 @Override
Nathan Harolda1afbd82017-04-24 16:16:34 -0700646 protected ResourceTracker getResourceTracker() {
Benedict Wong344bd622017-11-16 15:27:22 -0800647 return getUserRecord().mTransformQuotaTracker;
Nathan Harolda1afbd82017-04-24 16:16:34 -0700648 }
649
ludib0c95b12017-05-22 10:52:23 -0700650 @Override
651 public String toString() {
652 StringBuilder strBuilder = new StringBuilder();
653 strBuilder
654 .append("{super=")
655 .append(super.toString())
656 .append(", mSocket=")
657 .append(mSocket)
Nathan Harolda2523312018-01-05 19:25:13 -0800658 .append(", mSpi.mResourceId=")
659 .append(mSpi.mResourceId)
ludib0c95b12017-05-22 10:52:23 -0700660 .append(", mConfig=")
661 .append(mConfig)
662 .append("}");
663 return strBuilder.toString();
664 }
Nathan Harold93962f32017-03-07 13:23:36 -0800665 }
666
Benedict Wong4f9fb812017-12-13 17:16:53 -0800667 /**
668 * Tracks a single SA in the kernel, and manages cleanup paths. Once used in a Transform, the
669 * responsibility for cleaning up underlying resources will be passed to the TransformRecord
670 * object
671 */
672 private final class SpiRecord extends OwnedResourceRecord {
Nathan Harolda2523312018-01-05 19:25:13 -0800673 private final String mSourceAddress;
674 private final String mDestinationAddress;
Nathan Harold93962f32017-03-07 13:23:36 -0800675 private int mSpi;
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700676
677 private boolean mOwnedByTransform = false;
Nathan Harold93962f32017-03-07 13:23:36 -0800678
Nathan Harolda2523312018-01-05 19:25:13 -0800679 SpiRecord(int resourceId, String sourceAddress, String destinationAddress, int spi) {
Benedict Wong344bd622017-11-16 15:27:22 -0800680 super(resourceId);
Nathan Harolda2523312018-01-05 19:25:13 -0800681 mSourceAddress = sourceAddress;
682 mDestinationAddress = destinationAddress;
Nathan Harold93962f32017-03-07 13:23:36 -0800683 mSpi = spi;
Nathan Harold93962f32017-03-07 13:23:36 -0800684 }
685
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700686 /** always guarded by IpSecService#this */
687 @Override
Benedict Wong344bd622017-11-16 15:27:22 -0800688 public void freeUnderlyingResources() {
Nathan Harold93962f32017-03-07 13:23:36 -0800689 try {
Nathan Harold22795302018-02-27 19:19:40 -0800690 if (!mOwnedByTransform) {
691 mSrvConfig
692 .getNetdInstance()
693 .ipSecDeleteSecurityAssociation(
Benedict Wong781dae62018-09-06 11:31:25 -0700694 uid, mSourceAddress, mDestinationAddress, mSpi, 0 /* mark */,
695 0 /* mask */, 0 /* if_id */);
Nathan Harold22795302018-02-27 19:19:40 -0800696 }
Benedict Wongecc9f7c2018-03-01 18:53:07 -0800697 } catch (ServiceSpecificException | RemoteException e) {
698 Log.e(TAG, "Failed to delete SPI reservation with ID: " + mResourceId, e);
Nathan Harold93962f32017-03-07 13:23:36 -0800699 }
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700700
701 mSpi = IpSecManager.INVALID_SECURITY_PARAMETER_INDEX;
Nathan Harold93962f32017-03-07 13:23:36 -0800702
Benedict Wong344bd622017-11-16 15:27:22 -0800703 getResourceTracker().give();
Nathan Harolda1afbd82017-04-24 16:16:34 -0700704 }
705
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700706 public int getSpi() {
707 return mSpi;
708 }
709
Nathan Harolda2523312018-01-05 19:25:13 -0800710 public String getDestinationAddress() {
711 return mDestinationAddress;
712 }
713
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700714 public void setOwnedByTransform() {
715 if (mOwnedByTransform) {
716 // Programming error
Andreas Gamped6d8e452017-07-11 10:25:09 -0700717 throw new IllegalStateException("Cannot own an SPI twice!");
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700718 }
719
720 mOwnedByTransform = true;
Nathan Harold93962f32017-03-07 13:23:36 -0800721 }
ludib0c95b12017-05-22 10:52:23 -0700722
Benedict Wonge6b42772017-12-13 18:26:40 -0800723 public boolean getOwnedByTransform() {
724 return mOwnedByTransform;
725 }
726
ludib0c95b12017-05-22 10:52:23 -0700727 @Override
Benedict Wong344bd622017-11-16 15:27:22 -0800728 public void invalidate() throws RemoteException {
729 getUserRecord().removeSpiRecord(mResourceId);
730 }
731
732 @Override
733 protected ResourceTracker getResourceTracker() {
734 return getUserRecord().mSpiQuotaTracker;
735 }
736
737 @Override
ludib0c95b12017-05-22 10:52:23 -0700738 public String toString() {
739 StringBuilder strBuilder = new StringBuilder();
740 strBuilder
741 .append("{super=")
742 .append(super.toString())
743 .append(", mSpi=")
744 .append(mSpi)
Nathan Harolda2523312018-01-05 19:25:13 -0800745 .append(", mSourceAddress=")
746 .append(mSourceAddress)
747 .append(", mDestinationAddress=")
748 .append(mDestinationAddress)
ludib0c95b12017-05-22 10:52:23 -0700749 .append(", mOwnedByTransform=")
750 .append(mOwnedByTransform)
751 .append("}");
752 return strBuilder.toString();
753 }
Nathan Harold93962f32017-03-07 13:23:36 -0800754 }
755
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +0900756 // These values have been reserved in NetIdManager
Benedict Wong8149f6e2018-01-18 18:31:45 -0800757 @VisibleForTesting static final int TUN_INTF_NETID_START = 0xFC00;
758
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +0900759 public static final int TUN_INTF_NETID_RANGE = 0x0400;
Benedict Wong8149f6e2018-01-18 18:31:45 -0800760
761 private final SparseBooleanArray mTunnelNetIds = new SparseBooleanArray();
762 private int mNextTunnelNetIdIndex = 0;
763
764 /**
765 * Reserves a netId within the range of netIds allocated for IPsec tunnel interfaces
766 *
767 * <p>This method should only be called from Binder threads. Do not call this from within the
768 * system server as it will crash the system on failure.
769 *
770 * @return an integer key within the netId range, if successful
771 * @throws IllegalStateException if unsuccessful (all netId are currently reserved)
772 */
773 @VisibleForTesting
774 int reserveNetId() {
775 synchronized (mTunnelNetIds) {
776 for (int i = 0; i < TUN_INTF_NETID_RANGE; i++) {
777 int index = mNextTunnelNetIdIndex;
778 int netId = index + TUN_INTF_NETID_START;
779 if (++mNextTunnelNetIdIndex >= TUN_INTF_NETID_RANGE) mNextTunnelNetIdIndex = 0;
780 if (!mTunnelNetIds.get(netId)) {
781 mTunnelNetIds.put(netId, true);
782 return netId;
783 }
784 }
785 }
786 throw new IllegalStateException("No free netIds to allocate");
787 }
788
789 @VisibleForTesting
790 void releaseNetId(int netId) {
791 synchronized (mTunnelNetIds) {
792 mTunnelNetIds.delete(netId);
793 }
794 }
795
796 private final class TunnelInterfaceRecord extends OwnedResourceRecord {
797 private final String mInterfaceName;
798 private final Network mUnderlyingNetwork;
799
800 // outer addresses
801 private final String mLocalAddress;
802 private final String mRemoteAddress;
803
804 private final int mIkey;
805 private final int mOkey;
806
Benedict Wong781dae62018-09-06 11:31:25 -0700807 private final int mIfId;
808
Benedict Wong8149f6e2018-01-18 18:31:45 -0800809 TunnelInterfaceRecord(
810 int resourceId,
811 String interfaceName,
812 Network underlyingNetwork,
813 String localAddr,
814 String remoteAddr,
815 int ikey,
Benedict Wong781dae62018-09-06 11:31:25 -0700816 int okey,
817 int intfId) {
Benedict Wong8149f6e2018-01-18 18:31:45 -0800818 super(resourceId);
819
820 mInterfaceName = interfaceName;
821 mUnderlyingNetwork = underlyingNetwork;
822 mLocalAddress = localAddr;
823 mRemoteAddress = remoteAddr;
824 mIkey = ikey;
825 mOkey = okey;
Benedict Wong781dae62018-09-06 11:31:25 -0700826 mIfId = intfId;
Benedict Wong8149f6e2018-01-18 18:31:45 -0800827 }
828
829 /** always guarded by IpSecService#this */
830 @Override
831 public void freeUnderlyingResources() {
Benedict Wong0fe58a92018-01-19 17:36:02 -0800832 // Calls to netd
Benedict Wong8149f6e2018-01-18 18:31:45 -0800833 // Teardown VTI
834 // Delete global policies
Benedict Wong0fe58a92018-01-19 17:36:02 -0800835 try {
Benedict Wong564e2aa2018-05-07 20:06:44 -0700836 final INetd netd = mSrvConfig.getNetdInstance();
Benedict Wong781dae62018-09-06 11:31:25 -0700837 netd.ipSecRemoveTunnelInterface(mInterfaceName);
Benedict Wong0fe58a92018-01-19 17:36:02 -0800838
Benedict Wong564e2aa2018-05-07 20:06:44 -0700839 for (int selAddrFamily : ADDRESS_FAMILIES) {
840 netd.ipSecDeleteSecurityPolicy(
Benedict Wonga0989622018-07-25 13:06:29 -0700841 uid,
Benedict Wong564e2aa2018-05-07 20:06:44 -0700842 selAddrFamily,
843 IpSecManager.DIRECTION_OUT,
844 mOkey,
Benedict Wong781dae62018-09-06 11:31:25 -0700845 0xffffffff,
846 mIfId);
Benedict Wong564e2aa2018-05-07 20:06:44 -0700847 netd.ipSecDeleteSecurityPolicy(
Benedict Wonga0989622018-07-25 13:06:29 -0700848 uid,
Benedict Wong564e2aa2018-05-07 20:06:44 -0700849 selAddrFamily,
850 IpSecManager.DIRECTION_IN,
851 mIkey,
Benedict Wong781dae62018-09-06 11:31:25 -0700852 0xffffffff,
853 mIfId);
Benedict Wong0fe58a92018-01-19 17:36:02 -0800854 }
Benedict Wongecc9f7c2018-03-01 18:53:07 -0800855 } catch (ServiceSpecificException | RemoteException e) {
Benedict Wong0fe58a92018-01-19 17:36:02 -0800856 Log.e(
857 TAG,
858 "Failed to delete VTI with interface name: "
859 + mInterfaceName
860 + " and id: "
Benedict Wongecc9f7c2018-03-01 18:53:07 -0800861 + mResourceId, e);
Benedict Wong0fe58a92018-01-19 17:36:02 -0800862 }
Benedict Wong8149f6e2018-01-18 18:31:45 -0800863
864 getResourceTracker().give();
865 releaseNetId(mIkey);
866 releaseNetId(mOkey);
867 }
868
869 public String getInterfaceName() {
870 return mInterfaceName;
871 }
872
873 public Network getUnderlyingNetwork() {
874 return mUnderlyingNetwork;
875 }
876
877 /** Returns the local, outer address for the tunnelInterface */
878 public String getLocalAddress() {
879 return mLocalAddress;
880 }
881
882 /** Returns the remote, outer address for the tunnelInterface */
883 public String getRemoteAddress() {
884 return mRemoteAddress;
885 }
886
887 public int getIkey() {
888 return mIkey;
889 }
890
891 public int getOkey() {
892 return mOkey;
893 }
894
Benedict Wong781dae62018-09-06 11:31:25 -0700895 public int getIfId() {
896 return mIfId;
897 }
898
Benedict Wong8149f6e2018-01-18 18:31:45 -0800899 @Override
900 protected ResourceTracker getResourceTracker() {
901 return getUserRecord().mTunnelQuotaTracker;
902 }
903
904 @Override
905 public void invalidate() {
906 getUserRecord().removeTunnelInterfaceRecord(mResourceId);
907 }
908
909 @Override
910 public String toString() {
911 return new StringBuilder()
912 .append("{super=")
913 .append(super.toString())
914 .append(", mInterfaceName=")
915 .append(mInterfaceName)
916 .append(", mUnderlyingNetwork=")
917 .append(mUnderlyingNetwork)
918 .append(", mLocalAddress=")
919 .append(mLocalAddress)
920 .append(", mRemoteAddress=")
921 .append(mRemoteAddress)
922 .append(", mIkey=")
923 .append(mIkey)
924 .append(", mOkey=")
925 .append(mOkey)
926 .append("}")
927 .toString();
928 }
929 }
930
Benedict Wong4f9fb812017-12-13 17:16:53 -0800931 /**
932 * Tracks a UDP encap socket, and manages cleanup paths
933 *
934 * <p>While this class does not manage non-kernel resources, race conditions around socket
935 * binding require that the service creates the encap socket, binds it and applies the socket
936 * policy before handing it to a user.
937 */
938 private final class EncapSocketRecord extends OwnedResourceRecord {
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700939 private FileDescriptor mSocket;
940 private final int mPort;
Nathan Harold93962f32017-03-07 13:23:36 -0800941
Benedict Wong344bd622017-11-16 15:27:22 -0800942 EncapSocketRecord(int resourceId, FileDescriptor socket, int port) {
943 super(resourceId);
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700944 mSocket = socket;
945 mPort = port;
946 }
947
948 /** always guarded by IpSecService#this */
949 @Override
Benedict Wong344bd622017-11-16 15:27:22 -0800950 public void freeUnderlyingResources() {
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700951 Log.d(TAG, "Closing port " + mPort);
952 IoUtils.closeQuietly(mSocket);
953 mSocket = null;
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700954
Benedict Wong344bd622017-11-16 15:27:22 -0800955 getResourceTracker().give();
Nathan Harolda1afbd82017-04-24 16:16:34 -0700956 }
957
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700958 public int getPort() {
959 return mPort;
960 }
961
Benedict Wong4c987eb2018-03-27 16:55:48 -0700962 public FileDescriptor getFileDescriptor() {
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700963 return mSocket;
964 }
ludib0c95b12017-05-22 10:52:23 -0700965
966 @Override
Benedict Wong344bd622017-11-16 15:27:22 -0800967 protected ResourceTracker getResourceTracker() {
968 return getUserRecord().mSocketQuotaTracker;
969 }
970
971 @Override
972 public void invalidate() {
973 getUserRecord().removeEncapSocketRecord(mResourceId);
974 }
975
976 @Override
ludib0c95b12017-05-22 10:52:23 -0700977 public String toString() {
978 return new StringBuilder()
979 .append("{super=")
980 .append(super.toString())
981 .append(", mSocket=")
982 .append(mSocket)
983 .append(", mPort=")
984 .append(mPort)
985 .append("}")
986 .toString();
987 }
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700988 }
Nathan Harold93962f32017-03-07 13:23:36 -0800989
Nathan Harold1afbef42017-03-01 18:55:06 -0800990 /**
991 * Constructs a new IpSecService instance
992 *
993 * @param context Binder context for this service
994 */
995 private IpSecService(Context context) {
ludi1a06aa72017-05-12 09:15:00 -0700996 this(context, IpSecServiceConfiguration.GETSRVINSTANCE);
Nathan Harold1afbef42017-03-01 18:55:06 -0800997 }
998
999 static IpSecService create(Context context) throws InterruptedException {
1000 final IpSecService service = new IpSecService(context);
1001 service.connectNativeNetdService();
1002 return service;
1003 }
1004
Nathan Harold21208ee2018-03-15 18:06:06 -07001005 @NonNull
1006 private AppOpsManager getAppOpsManager() {
1007 AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
1008 if(appOps == null) throw new RuntimeException("System Server couldn't get AppOps");
1009 return appOps;
1010 }
1011
ludi1a06aa72017-05-12 09:15:00 -07001012 /** @hide */
1013 @VisibleForTesting
1014 public IpSecService(Context context, IpSecServiceConfiguration config) {
Nathan Harolda2523312018-01-05 19:25:13 -08001015 this(
1016 context,
1017 config,
1018 (fd, uid) -> {
1019 try {
1020 TrafficStats.setThreadStatsUid(uid);
1021 TrafficStats.tagFileDescriptor(fd);
1022 } finally {
1023 TrafficStats.clearThreadStatsUid();
1024 }
1025 });
Benedict Wongbabe5d72017-12-03 19:42:36 -08001026 }
1027
1028 /** @hide */
1029 @VisibleForTesting
1030 public IpSecService(
1031 Context context, IpSecServiceConfiguration config, UidFdTagger uidFdTagger) {
ludi1a06aa72017-05-12 09:15:00 -07001032 mContext = context;
1033 mSrvConfig = config;
Benedict Wongbabe5d72017-12-03 19:42:36 -08001034 mUidFdTagger = uidFdTagger;
ludi1a06aa72017-05-12 09:15:00 -07001035 }
1036
Nathan Harold1afbef42017-03-01 18:55:06 -08001037 public void systemReady() {
1038 if (isNetdAlive()) {
1039 Slog.d(TAG, "IpSecService is ready");
1040 } else {
1041 Slog.wtf(TAG, "IpSecService not ready: failed to connect to NetD Native Service!");
1042 }
1043 }
1044
1045 private void connectNativeNetdService() {
1046 // Avoid blocking the system server to do this
Nathan Haroldb0e05082017-07-17 14:01:53 -07001047 new Thread() {
1048 @Override
1049 public void run() {
1050 synchronized (IpSecService.this) {
ludi1a06aa72017-05-12 09:15:00 -07001051 NetdService.get(NETD_FETCH_TIMEOUT_MS);
Nathan Haroldb0e05082017-07-17 14:01:53 -07001052 }
1053 }
1054 }.start();
Nathan Harold1afbef42017-03-01 18:55:06 -08001055 }
1056
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001057 synchronized boolean isNetdAlive() {
1058 try {
ludi1a06aa72017-05-12 09:15:00 -07001059 final INetd netd = mSrvConfig.getNetdInstance();
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001060 if (netd == null) {
Nathan Harold1afbef42017-03-01 18:55:06 -08001061 return false;
1062 }
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001063 return netd.isAlive();
1064 } catch (RemoteException re) {
1065 return false;
Nathan Harold1afbef42017-03-01 18:55:06 -08001066 }
1067 }
1068
Nathan Harolda10003d2017-08-23 13:46:33 -07001069 /**
1070 * Checks that the provided InetAddress is valid for use in an IPsec SA. The address must not be
1071 * a wildcard address and must be in a numeric form such as 1.2.3.4 or 2001::1.
1072 */
1073 private static void checkInetAddress(String inetAddress) {
1074 if (TextUtils.isEmpty(inetAddress)) {
1075 throw new IllegalArgumentException("Unspecified address");
1076 }
1077
1078 InetAddress checkAddr = NetworkUtils.numericToInetAddress(inetAddress);
1079
1080 if (checkAddr.isAnyLocalAddress()) {
1081 throw new IllegalArgumentException("Inappropriate wildcard address: " + inetAddress);
1082 }
1083 }
1084
1085 /**
1086 * Checks the user-provided direction field and throws an IllegalArgumentException if it is not
1087 * DIRECTION_IN or DIRECTION_OUT
1088 */
1089 private static void checkDirection(int direction) {
1090 switch (direction) {
Nathan Harolda2523312018-01-05 19:25:13 -08001091 case IpSecManager.DIRECTION_OUT:
1092 case IpSecManager.DIRECTION_IN:
Nathan Harolda10003d2017-08-23 13:46:33 -07001093 return;
1094 }
1095 throw new IllegalArgumentException("Invalid Direction: " + direction);
1096 }
1097
Nathan Harold93962f32017-03-07 13:23:36 -08001098 /** Get a new SPI and maintain the reservation in the system server */
Jonathan Basseri5fb92902017-11-16 10:58:01 -08001099 @Override
1100 public synchronized IpSecSpiResponse allocateSecurityParameterIndex(
Nathan Harolda2523312018-01-05 19:25:13 -08001101 String destinationAddress, int requestedSpi, IBinder binder) throws RemoteException {
1102 checkInetAddress(destinationAddress);
Nathan Harold7f606ee2018-03-28 08:52:51 -07001103 // RFC 4303 Section 2.1 - 0=local, 1-255=reserved.
1104 if (requestedSpi > 0 && requestedSpi < 256) {
1105 throw new IllegalArgumentException("ESP SPI must not be in the range of 0-255.");
1106 }
Daulet Zhanguzinea1a7ca2020-01-03 09:46:50 +00001107 Objects.requireNonNull(binder, "Null Binder passed to allocateSecurityParameterIndex");
Nathan Harolda10003d2017-08-23 13:46:33 -07001108
Benedict Wonga0989622018-07-25 13:06:29 -07001109 int callingUid = Binder.getCallingUid();
1110 UserRecord userRecord = mUserResourceTracker.getUserRecord(callingUid);
Nathan Haroldd8c74292017-12-13 19:16:33 -08001111 final int resourceId = mNextResourceId++;
Nathan Harold93962f32017-03-07 13:23:36 -08001112
1113 int spi = IpSecManager.INVALID_SECURITY_PARAMETER_INDEX;
Nathan Harold93962f32017-03-07 13:23:36 -08001114 try {
Benedict Wong344bd622017-11-16 15:27:22 -08001115 if (!userRecord.mSpiQuotaTracker.isAvailable()) {
Nathan Harolda1afbd82017-04-24 16:16:34 -07001116 return new IpSecSpiResponse(
Nathan Harolda10003d2017-08-23 13:46:33 -07001117 IpSecManager.Status.RESOURCE_UNAVAILABLE, INVALID_RESOURCE_ID, spi);
Nathan Harolda1afbd82017-04-24 16:16:34 -07001118 }
Nathan Harolda2523312018-01-05 19:25:13 -08001119
Nathan Harold93962f32017-03-07 13:23:36 -08001120 spi =
ludi1a06aa72017-05-12 09:15:00 -07001121 mSrvConfig
1122 .getNetdInstance()
Benedict Wonga0989622018-07-25 13:06:29 -07001123 .ipSecAllocateSpi(callingUid, "", destinationAddress, requestedSpi);
Nathan Harold93962f32017-03-07 13:23:36 -08001124 Log.d(TAG, "Allocated SPI " + spi);
Benedict Wong344bd622017-11-16 15:27:22 -08001125 userRecord.mSpiRecords.put(
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001126 resourceId,
Benedict Wong344bd622017-11-16 15:27:22 -08001127 new RefcountedResource<SpiRecord>(
Nathan Harolda2523312018-01-05 19:25:13 -08001128 new SpiRecord(resourceId, "", destinationAddress, spi), binder));
Nathan Harold93962f32017-03-07 13:23:36 -08001129 } catch (ServiceSpecificException e) {
Nathan Harold144ce0a2018-04-03 16:13:19 -07001130 if (e.errorCode == OsConstants.ENOENT) {
1131 return new IpSecSpiResponse(
1132 IpSecManager.Status.SPI_UNAVAILABLE, INVALID_RESOURCE_ID, spi);
1133 }
1134 throw e;
Nathan Harold93962f32017-03-07 13:23:36 -08001135 } catch (RemoteException e) {
1136 throw e.rethrowFromSystemServer();
1137 }
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001138 return new IpSecSpiResponse(IpSecManager.Status.OK, resourceId, spi);
1139 }
1140
1141 /* This method should only be called from Binder threads. Do not call this from
1142 * within the system server as it will crash the system on failure.
1143 */
Benedict Wong344bd622017-11-16 15:27:22 -08001144 private void releaseResource(RefcountedResourceArray resArray, int resourceId)
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001145 throws RemoteException {
Benedict Wong344bd622017-11-16 15:27:22 -08001146 resArray.getRefcountedResourceOrThrow(resourceId).userRelease();
Nathan Harold93962f32017-03-07 13:23:36 -08001147 }
1148
1149 /** Release a previously allocated SPI that has been registered with the system server */
1150 @Override
Benedict Wong344bd622017-11-16 15:27:22 -08001151 public synchronized void releaseSecurityParameterIndex(int resourceId) throws RemoteException {
1152 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
1153 releaseResource(userRecord.mSpiRecords, resourceId);
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001154 }
1155
1156 /**
1157 * This function finds and forcibly binds to a random system port, ensuring that the port cannot
1158 * be unbound.
1159 *
1160 * <p>A socket cannot be un-bound from a port if it was bound to that port by number. To select
1161 * a random open port and then bind by number, this function creates a temp socket, binds to a
1162 * random port (specifying 0), gets that port number, and then uses is to bind the user's UDP
1163 * Encapsulation Socket forcibly, so that it cannot be un-bound by the user with the returned
1164 * FileHandle.
1165 *
1166 * <p>The loop in this function handles the inherent race window between un-binding to a port
1167 * and re-binding, during which the system could *technically* hand that port out to someone
1168 * else.
1169 */
Benedict Wongf186d672017-10-10 20:44:28 -07001170 private int bindToRandomPort(FileDescriptor sockFd) throws IOException {
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001171 for (int i = MAX_PORT_BIND_ATTEMPTS; i > 0; i--) {
1172 try {
1173 FileDescriptor probeSocket = Os.socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1174 Os.bind(probeSocket, INADDR_ANY, 0);
1175 int port = ((InetSocketAddress) Os.getsockname(probeSocket)).getPort();
1176 Os.close(probeSocket);
1177 Log.v(TAG, "Binding to port " + port);
1178 Os.bind(sockFd, INADDR_ANY, port);
Benedict Wongf186d672017-10-10 20:44:28 -07001179 return port;
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001180 } catch (ErrnoException e) {
1181 // Someone miraculously claimed the port just after we closed probeSocket.
1182 if (e.errno == OsConstants.EADDRINUSE) {
1183 continue;
1184 }
1185 throw e.rethrowAsIOException();
1186 }
1187 }
1188 throw new IOException("Failed " + MAX_PORT_BIND_ATTEMPTS + " attempts to bind to a port");
1189 }
Nathan Harold93962f32017-03-07 13:23:36 -08001190
1191 /**
Benedict Wongbabe5d72017-12-03 19:42:36 -08001192 * Functional interface to do traffic tagging of given sockets to UIDs.
1193 *
1194 * <p>Specifically used by openUdpEncapsulationSocket to ensure data usage on the UDP encap
1195 * sockets are billed to the UID that the UDP encap socket was created on behalf of.
1196 *
1197 * <p>Separate class so that the socket tagging logic can be mocked; TrafficStats uses static
1198 * methods that cannot be easily mocked/tested.
1199 */
1200 @VisibleForTesting
1201 public interface UidFdTagger {
1202 /**
1203 * Sets socket tag to assign all traffic to the provided UID.
1204 *
1205 * <p>Since the socket is created on behalf of an unprivileged application, all traffic
1206 * should be accounted to the UID of the unprivileged application.
1207 */
1208 public void tag(FileDescriptor fd, int uid) throws IOException;
1209 }
1210
1211 /**
Nathan Harold93962f32017-03-07 13:23:36 -08001212 * Open a socket via the system server and bind it to the specified port (random if port=0).
1213 * This will return a PFD to the user that represent a bound UDP socket. The system server will
1214 * cache the socket and a record of its owner so that it can and must be freed when no longer
1215 * needed.
1216 */
1217 @Override
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001218 public synchronized IpSecUdpEncapResponse openUdpEncapsulationSocket(int port, IBinder binder)
1219 throws RemoteException {
1220 if (port != 0 && (port < FREE_PORT_MIN || port > PORT_MAX)) {
1221 throw new IllegalArgumentException(
1222 "Specified port number must be a valid non-reserved UDP port");
1223 }
Daulet Zhanguzinea1a7ca2020-01-03 09:46:50 +00001224 Objects.requireNonNull(binder, "Null Binder passed to openUdpEncapsulationSocket");
Nathan Harolda10003d2017-08-23 13:46:33 -07001225
Benedict Wongbabe5d72017-12-03 19:42:36 -08001226 int callingUid = Binder.getCallingUid();
1227 UserRecord userRecord = mUserResourceTracker.getUserRecord(callingUid);
Nathan Haroldd8c74292017-12-13 19:16:33 -08001228 final int resourceId = mNextResourceId++;
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001229 FileDescriptor sockFd = null;
1230 try {
Benedict Wong344bd622017-11-16 15:27:22 -08001231 if (!userRecord.mSocketQuotaTracker.isAvailable()) {
Nathan Harolda1afbd82017-04-24 16:16:34 -07001232 return new IpSecUdpEncapResponse(IpSecManager.Status.RESOURCE_UNAVAILABLE);
1233 }
1234
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001235 sockFd = Os.socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
Benedict Wongbabe5d72017-12-03 19:42:36 -08001236 mUidFdTagger.tag(sockFd, callingUid);
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001237
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001238 // This code is common to both the unspecified and specified port cases
1239 Os.setsockoptInt(
1240 sockFd,
1241 OsConstants.IPPROTO_UDP,
1242 OsConstants.UDP_ENCAP,
1243 OsConstants.UDP_ENCAP_ESPINUDP);
1244
Luke Huange8e522b2018-11-23 12:01:41 +08001245 mSrvConfig.getNetdInstance().ipSecSetEncapSocketOwner(
1246 new ParcelFileDescriptor(sockFd), callingUid);
Benedict Wongba8d3132017-12-06 21:56:35 -08001247 if (port != 0) {
1248 Log.v(TAG, "Binding to port " + port);
1249 Os.bind(sockFd, INADDR_ANY, port);
1250 } else {
1251 port = bindToRandomPort(sockFd);
1252 }
1253
Benedict Wong344bd622017-11-16 15:27:22 -08001254 userRecord.mEncapSocketRecords.put(
1255 resourceId,
1256 new RefcountedResource<EncapSocketRecord>(
1257 new EncapSocketRecord(resourceId, sockFd, port), binder));
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001258 return new IpSecUdpEncapResponse(IpSecManager.Status.OK, resourceId, port, sockFd);
1259 } catch (IOException | ErrnoException e) {
1260 IoUtils.closeQuietly(sockFd);
1261 }
1262 // If we make it to here, then something has gone wrong and we couldn't open a socket.
1263 // The only reasonable condition that would cause that is resource unavailable.
1264 return new IpSecUdpEncapResponse(IpSecManager.Status.RESOURCE_UNAVAILABLE);
Nathan Harold93962f32017-03-07 13:23:36 -08001265 }
1266
1267 /** close a socket that has been been allocated by and registered with the system server */
1268 @Override
Benedict Wong344bd622017-11-16 15:27:22 -08001269 public synchronized void closeUdpEncapsulationSocket(int resourceId) throws RemoteException {
1270 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
1271 releaseResource(userRecord.mEncapSocketRecords, resourceId);
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001272 }
Nathan Harold93962f32017-03-07 13:23:36 -08001273
Benedict Wong8149f6e2018-01-18 18:31:45 -08001274 /**
1275 * Create a tunnel interface for use in IPSec tunnel mode. The system server will cache the
1276 * tunnel interface and a record of its owner so that it can and must be freed when no longer
1277 * needed.
1278 */
1279 @Override
1280 public synchronized IpSecTunnelInterfaceResponse createTunnelInterface(
Nathan Harold21208ee2018-03-15 18:06:06 -07001281 String localAddr, String remoteAddr, Network underlyingNetwork, IBinder binder,
1282 String callingPackage) {
Benedict Wonge265d5f2018-11-08 19:45:34 -08001283 enforceTunnelFeatureAndPermissions(callingPackage);
Daulet Zhanguzinea1a7ca2020-01-03 09:46:50 +00001284 Objects.requireNonNull(binder, "Null Binder passed to createTunnelInterface");
1285 Objects.requireNonNull(underlyingNetwork, "No underlying network was specified");
Benedict Wong8149f6e2018-01-18 18:31:45 -08001286 checkInetAddress(localAddr);
1287 checkInetAddress(remoteAddr);
1288
1289 // TODO: Check that underlying network exists, and IP addresses not assigned to a different
1290 // network (b/72316676).
1291
Benedict Wonga0989622018-07-25 13:06:29 -07001292 int callerUid = Binder.getCallingUid();
1293 UserRecord userRecord = mUserResourceTracker.getUserRecord(callerUid);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001294 if (!userRecord.mTunnelQuotaTracker.isAvailable()) {
1295 return new IpSecTunnelInterfaceResponse(IpSecManager.Status.RESOURCE_UNAVAILABLE);
1296 }
1297
1298 final int resourceId = mNextResourceId++;
1299 final int ikey = reserveNetId();
1300 final int okey = reserveNetId();
Nathan Harold4fd7c322018-04-26 11:47:14 -07001301 String intfName = String.format("%s%d", INetd.IPSEC_INTERFACE_PREFIX, resourceId);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001302
Benedict Wong0fe58a92018-01-19 17:36:02 -08001303 try {
1304 // Calls to netd:
1305 // Create VTI
1306 // Add inbound/outbound global policies
1307 // (use reqid = 0)
Benedict Wong564e2aa2018-05-07 20:06:44 -07001308 final INetd netd = mSrvConfig.getNetdInstance();
Benedict Wong781dae62018-09-06 11:31:25 -07001309 netd.ipSecAddTunnelInterface(intfName, localAddr, remoteAddr, ikey, okey, resourceId);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001310
Benedict Wong564e2aa2018-05-07 20:06:44 -07001311 for (int selAddrFamily : ADDRESS_FAMILIES) {
1312 // Always send down correct local/remote addresses for template.
1313 netd.ipSecAddSecurityPolicy(
Benedict Wonga0989622018-07-25 13:06:29 -07001314 callerUid,
Benedict Wong564e2aa2018-05-07 20:06:44 -07001315 selAddrFamily,
1316 IpSecManager.DIRECTION_OUT,
1317 localAddr,
1318 remoteAddr,
1319 0,
1320 okey,
Benedict Wong781dae62018-09-06 11:31:25 -07001321 0xffffffff,
1322 resourceId);
Benedict Wong564e2aa2018-05-07 20:06:44 -07001323 netd.ipSecAddSecurityPolicy(
Benedict Wonga0989622018-07-25 13:06:29 -07001324 callerUid,
Benedict Wong564e2aa2018-05-07 20:06:44 -07001325 selAddrFamily,
1326 IpSecManager.DIRECTION_IN,
1327 remoteAddr,
1328 localAddr,
1329 0,
1330 ikey,
Benedict Wong781dae62018-09-06 11:31:25 -07001331 0xffffffff,
1332 resourceId);
Benedict Wong0fe58a92018-01-19 17:36:02 -08001333 }
1334
1335 userRecord.mTunnelInterfaceRecords.put(
1336 resourceId,
1337 new RefcountedResource<TunnelInterfaceRecord>(
1338 new TunnelInterfaceRecord(
1339 resourceId,
1340 intfName,
1341 underlyingNetwork,
1342 localAddr,
1343 remoteAddr,
1344 ikey,
Benedict Wong781dae62018-09-06 11:31:25 -07001345 okey,
1346 resourceId),
Benedict Wong0fe58a92018-01-19 17:36:02 -08001347 binder));
1348 return new IpSecTunnelInterfaceResponse(IpSecManager.Status.OK, resourceId, intfName);
1349 } catch (RemoteException e) {
1350 // Release keys if we got an error.
1351 releaseNetId(ikey);
1352 releaseNetId(okey);
1353 throw e.rethrowFromSystemServer();
Nathan Harold144ce0a2018-04-03 16:13:19 -07001354 } catch (Throwable t) {
1355 // Release keys if we got an error.
1356 releaseNetId(ikey);
1357 releaseNetId(okey);
1358 throw t;
Benedict Wong0fe58a92018-01-19 17:36:02 -08001359 }
Benedict Wong8149f6e2018-01-18 18:31:45 -08001360 }
1361
1362 /**
1363 * Adds a new local address to the tunnel interface. This allows packets to be sent and received
1364 * from multiple local IP addresses over the same tunnel.
1365 */
1366 @Override
Benedict Wongecc9f7c2018-03-01 18:53:07 -08001367 public synchronized void addAddressToTunnelInterface(
Nathan Harold21208ee2018-03-15 18:06:06 -07001368 int tunnelResourceId, LinkAddress localAddr, String callingPackage) {
Benedict Wonge265d5f2018-11-08 19:45:34 -08001369 enforceTunnelFeatureAndPermissions(callingPackage);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001370 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
1371
1372 // Get tunnelInterface record; if no such interface is found, will throw
1373 // IllegalArgumentException
1374 TunnelInterfaceRecord tunnelInterfaceInfo =
1375 userRecord.mTunnelInterfaceRecords.getResourceOrThrow(tunnelResourceId);
1376
Benedict Wongecc9f7c2018-03-01 18:53:07 -08001377 try {
1378 // We can assume general validity of the IP address, since we get them as a
1379 // LinkAddress, which does some validation.
1380 mSrvConfig
1381 .getNetdInstance()
1382 .interfaceAddAddress(
1383 tunnelInterfaceInfo.mInterfaceName,
1384 localAddr.getAddress().getHostAddress(),
1385 localAddr.getPrefixLength());
1386 } catch (RemoteException e) {
1387 throw e.rethrowFromSystemServer();
Benedict Wongecc9f7c2018-03-01 18:53:07 -08001388 }
Benedict Wong8149f6e2018-01-18 18:31:45 -08001389 }
1390
1391 /**
1392 * Remove a new local address from the tunnel interface. After removal, the address will no
1393 * longer be available to send from, or receive on.
1394 */
1395 @Override
1396 public synchronized void removeAddressFromTunnelInterface(
Nathan Harold21208ee2018-03-15 18:06:06 -07001397 int tunnelResourceId, LinkAddress localAddr, String callingPackage) {
Benedict Wonge265d5f2018-11-08 19:45:34 -08001398 enforceTunnelFeatureAndPermissions(callingPackage);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001399
Nathan Harold21208ee2018-03-15 18:06:06 -07001400 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
Benedict Wong8149f6e2018-01-18 18:31:45 -08001401 // Get tunnelInterface record; if no such interface is found, will throw
1402 // IllegalArgumentException
1403 TunnelInterfaceRecord tunnelInterfaceInfo =
1404 userRecord.mTunnelInterfaceRecords.getResourceOrThrow(tunnelResourceId);
1405
Benedict Wongecc9f7c2018-03-01 18:53:07 -08001406 try {
1407 // We can assume general validity of the IP address, since we get them as a
1408 // LinkAddress, which does some validation.
1409 mSrvConfig
1410 .getNetdInstance()
1411 .interfaceDelAddress(
1412 tunnelInterfaceInfo.mInterfaceName,
1413 localAddr.getAddress().getHostAddress(),
1414 localAddr.getPrefixLength());
1415 } catch (RemoteException e) {
1416 throw e.rethrowFromSystemServer();
Benedict Wongecc9f7c2018-03-01 18:53:07 -08001417 }
Benedict Wong8149f6e2018-01-18 18:31:45 -08001418 }
1419
1420 /**
1421 * Delete a TunnelInterface that has been been allocated by and registered with the system
1422 * server
1423 */
1424 @Override
Nathan Harold21208ee2018-03-15 18:06:06 -07001425 public synchronized void deleteTunnelInterface(
1426 int resourceId, String callingPackage) throws RemoteException {
Benedict Wonge265d5f2018-11-08 19:45:34 -08001427 enforceTunnelFeatureAndPermissions(callingPackage);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001428 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
1429 releaseResource(userRecord.mTunnelInterfaceRecords, resourceId);
1430 }
1431
Benedict Wong4f255702017-11-06 20:49:10 -08001432 @VisibleForTesting
Nathan Harolda2523312018-01-05 19:25:13 -08001433 void validateAlgorithms(IpSecConfig config) throws IllegalArgumentException {
1434 IpSecAlgorithm auth = config.getAuthentication();
1435 IpSecAlgorithm crypt = config.getEncryption();
1436 IpSecAlgorithm aead = config.getAuthenticatedEncryption();
Benedict Wong4f255702017-11-06 20:49:10 -08001437
Nathan Harolda2523312018-01-05 19:25:13 -08001438 // Validate the algorithm set
1439 Preconditions.checkArgument(
1440 aead != null || crypt != null || auth != null,
1441 "No Encryption or Authentication algorithms specified");
1442 Preconditions.checkArgument(
1443 auth == null || auth.isAuthentication(),
1444 "Unsupported algorithm for Authentication");
1445 Preconditions.checkArgument(
Benedict Wong4f255702017-11-06 20:49:10 -08001446 crypt == null || crypt.isEncryption(), "Unsupported algorithm for Encryption");
Nathan Harolda2523312018-01-05 19:25:13 -08001447 Preconditions.checkArgument(
1448 aead == null || aead.isAead(),
1449 "Unsupported algorithm for Authenticated Encryption");
1450 Preconditions.checkArgument(
1451 aead == null || (auth == null && crypt == null),
1452 "Authenticated Encryption is mutually exclusive with other Authentication "
1453 + "or Encryption algorithms");
Benedict Wong4f255702017-11-06 20:49:10 -08001454 }
1455
evitayane4259d32018-03-22 17:53:08 -07001456 private int getFamily(String inetAddress) {
1457 int family = AF_UNSPEC;
1458 InetAddress checkAddress = NetworkUtils.numericToInetAddress(inetAddress);
1459 if (checkAddress instanceof Inet4Address) {
1460 family = AF_INET;
1461 } else if (checkAddress instanceof Inet6Address) {
1462 family = AF_INET6;
1463 }
1464 return family;
1465 }
1466
Nathan Harold93962f32017-03-07 13:23:36 -08001467 /**
Nathan Harolda10003d2017-08-23 13:46:33 -07001468 * Checks an IpSecConfig parcel to ensure that the contents are sane and throws an
1469 * IllegalArgumentException if they are not.
1470 */
1471 private void checkIpSecConfig(IpSecConfig config) {
Benedict Wong344bd622017-11-16 15:27:22 -08001472 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
1473
Nathan Harolda10003d2017-08-23 13:46:33 -07001474 switch (config.getEncapType()) {
1475 case IpSecTransform.ENCAP_NONE:
1476 break;
1477 case IpSecTransform.ENCAP_ESPINUDP:
1478 case IpSecTransform.ENCAP_ESPINUDP_NON_IKE:
Benedict Wong344bd622017-11-16 15:27:22 -08001479 // Retrieve encap socket record; will throw IllegalArgumentException if not found
1480 userRecord.mEncapSocketRecords.getResourceOrThrow(
1481 config.getEncapSocketResourceId());
Nathan Harolda10003d2017-08-23 13:46:33 -07001482
1483 int port = config.getEncapRemotePort();
1484 if (port <= 0 || port > 0xFFFF) {
1485 throw new IllegalArgumentException("Invalid remote UDP port: " + port);
1486 }
1487 break;
1488 default:
1489 throw new IllegalArgumentException("Invalid Encap Type: " + config.getEncapType());
1490 }
1491
Nathan Harolda2523312018-01-05 19:25:13 -08001492 validateAlgorithms(config);
Nathan Harolda10003d2017-08-23 13:46:33 -07001493
Nathan Harolda2523312018-01-05 19:25:13 -08001494 // Retrieve SPI record; will throw IllegalArgumentException if not found
1495 SpiRecord s = userRecord.mSpiRecords.getResourceOrThrow(config.getSpiResourceId());
1496
Benedict Wonge6b42772017-12-13 18:26:40 -08001497 // Check to ensure that SPI has not already been used.
1498 if (s.getOwnedByTransform()) {
1499 throw new IllegalStateException("SPI already in use; cannot be used in new Transforms");
1500 }
1501
Nathan Harolda2523312018-01-05 19:25:13 -08001502 // If no remote address is supplied, then use one from the SPI.
1503 if (TextUtils.isEmpty(config.getDestinationAddress())) {
1504 config.setDestinationAddress(s.getDestinationAddress());
1505 }
1506
1507 // All remote addresses must match
1508 if (!config.getDestinationAddress().equals(s.getDestinationAddress())) {
1509 throw new IllegalArgumentException("Mismatched remote addresseses.");
1510 }
1511
1512 // This check is technically redundant due to the chain of custody between the SPI and
1513 // the IpSecConfig, but in the future if the dest is allowed to be set explicitly in
1514 // the transform, this will prevent us from messing up.
1515 checkInetAddress(config.getDestinationAddress());
1516
1517 // Require a valid source address for all transforms.
1518 checkInetAddress(config.getSourceAddress());
1519
evitayane4259d32018-03-22 17:53:08 -07001520 // Check to ensure source and destination have the same address family.
1521 String sourceAddress = config.getSourceAddress();
1522 String destinationAddress = config.getDestinationAddress();
1523 int sourceFamily = getFamily(sourceAddress);
1524 int destinationFamily = getFamily(destinationAddress);
1525 if (sourceFamily != destinationFamily) {
1526 throw new IllegalArgumentException(
1527 "Source address ("
1528 + sourceAddress
1529 + ") and destination address ("
1530 + destinationAddress
1531 + ") have different address families.");
1532 }
1533
1534 // Throw an error if UDP Encapsulation is not used in IPv4.
1535 if (config.getEncapType() != IpSecTransform.ENCAP_NONE && sourceFamily != AF_INET) {
1536 throw new IllegalArgumentException(
1537 "UDP Encapsulation is not supported for this address family");
1538 }
1539
Nathan Harolda2523312018-01-05 19:25:13 -08001540 switch (config.getMode()) {
1541 case IpSecTransform.MODE_TRANSPORT:
Nathan Harold5a920ca2018-02-02 18:34:25 -08001542 break;
Nathan Harolda2523312018-01-05 19:25:13 -08001543 case IpSecTransform.MODE_TUNNEL:
1544 break;
1545 default:
1546 throw new IllegalArgumentException(
1547 "Invalid IpSecTransform.mode: " + config.getMode());
Nathan Harolda10003d2017-08-23 13:46:33 -07001548 }
Benedict Wongab80e1f2018-07-25 18:46:19 -07001549
1550 config.setMarkValue(0);
1551 config.setMarkMask(0);
Nathan Harolda10003d2017-08-23 13:46:33 -07001552 }
1553
Benedict Wongd8db9182018-09-13 16:45:12 -07001554 private static final String TUNNEL_OP = AppOpsManager.OPSTR_MANAGE_IPSEC_TUNNELS;
Nathan Harold8c69bcb2018-05-15 19:18:38 -07001555
Benedict Wonge265d5f2018-11-08 19:45:34 -08001556 private void enforceTunnelFeatureAndPermissions(String callingPackage) {
1557 if (!mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_IPSEC_TUNNELS)) {
1558 throw new UnsupportedOperationException(
1559 "IPsec Tunnel Mode requires PackageManager.FEATURE_IPSEC_TUNNELS");
1560 }
1561
Daulet Zhanguzinea1a7ca2020-01-03 09:46:50 +00001562 Objects.requireNonNull(callingPackage, "Null calling package cannot create IpSec tunnels");
Benedict Wong64e8db82019-11-12 22:31:51 -08001563
1564 // OP_MANAGE_IPSEC_TUNNELS will return MODE_ERRORED by default, including for the system
1565 // server. If the appop is not granted, require that the caller has the MANAGE_IPSEC_TUNNELS
1566 // permission or is the System Server.
1567 if (AppOpsManager.MODE_ALLOWED == getAppOpsManager().noteOpNoThrow(
1568 TUNNEL_OP, Binder.getCallingUid(), callingPackage)) {
1569 return;
Nathan Harold21208ee2018-03-15 18:06:06 -07001570 }
Benedict Wong64e8db82019-11-12 22:31:51 -08001571 mContext.enforceCallingOrSelfPermission(
1572 android.Manifest.permission.MANAGE_IPSEC_TUNNELS, "IpSecService");
Nathan Harold5a920ca2018-02-02 18:34:25 -08001573 }
1574
Benedict Wong0fe58a92018-01-19 17:36:02 -08001575 private void createOrUpdateTransform(
1576 IpSecConfig c, int resourceId, SpiRecord spiRecord, EncapSocketRecord socketRecord)
1577 throws RemoteException {
1578
1579 int encapType = c.getEncapType(), encapLocalPort = 0, encapRemotePort = 0;
1580 if (encapType != IpSecTransform.ENCAP_NONE) {
1581 encapLocalPort = socketRecord.getPort();
1582 encapRemotePort = c.getEncapRemotePort();
1583 }
1584
1585 IpSecAlgorithm auth = c.getAuthentication();
1586 IpSecAlgorithm crypt = c.getEncryption();
1587 IpSecAlgorithm authCrypt = c.getAuthenticatedEncryption();
1588
Benedict Wongbf013a32018-03-15 19:41:41 -07001589 String cryptName;
1590 if (crypt == null) {
1591 cryptName = (authCrypt == null) ? IpSecAlgorithm.CRYPT_NULL : "";
1592 } else {
1593 cryptName = crypt.getName();
1594 }
1595
Benedict Wong0fe58a92018-01-19 17:36:02 -08001596 mSrvConfig
1597 .getNetdInstance()
1598 .ipSecAddSecurityAssociation(
Benedict Wonga0989622018-07-25 13:06:29 -07001599 Binder.getCallingUid(),
Benedict Wong0fe58a92018-01-19 17:36:02 -08001600 c.getMode(),
1601 c.getSourceAddress(),
1602 c.getDestinationAddress(),
1603 (c.getNetwork() != null) ? c.getNetwork().netId : 0,
1604 spiRecord.getSpi(),
1605 c.getMarkValue(),
1606 c.getMarkMask(),
1607 (auth != null) ? auth.getName() : "",
1608 (auth != null) ? auth.getKey() : new byte[] {},
1609 (auth != null) ? auth.getTruncationLengthBits() : 0,
Benedict Wongbf013a32018-03-15 19:41:41 -07001610 cryptName,
Benedict Wong0fe58a92018-01-19 17:36:02 -08001611 (crypt != null) ? crypt.getKey() : new byte[] {},
1612 (crypt != null) ? crypt.getTruncationLengthBits() : 0,
1613 (authCrypt != null) ? authCrypt.getName() : "",
1614 (authCrypt != null) ? authCrypt.getKey() : new byte[] {},
1615 (authCrypt != null) ? authCrypt.getTruncationLengthBits() : 0,
1616 encapType,
1617 encapLocalPort,
Benedict Wong781dae62018-09-06 11:31:25 -07001618 encapRemotePort,
1619 c.getXfrmInterfaceId());
Benedict Wong0fe58a92018-01-19 17:36:02 -08001620 }
1621
Nathan Harolda10003d2017-08-23 13:46:33 -07001622 /**
Benedict Wong0fe58a92018-01-19 17:36:02 -08001623 * Create a IPsec transform, which represents a single security association in the kernel. The
1624 * transform will be cached by the system server and must be freed when no longer needed. It is
1625 * possible to free one, deleting the SA from underneath sockets that are using it, which will
1626 * result in all of those sockets becoming unable to send or receive data.
Nathan Harold93962f32017-03-07 13:23:36 -08001627 */
1628 @Override
Nathan Harold21208ee2018-03-15 18:06:06 -07001629 public synchronized IpSecTransformResponse createTransform(
1630 IpSecConfig c, IBinder binder, String callingPackage) throws RemoteException {
Daulet Zhanguzinea1a7ca2020-01-03 09:46:50 +00001631 Objects.requireNonNull(c);
Nathan Harold21208ee2018-03-15 18:06:06 -07001632 if (c.getMode() == IpSecTransform.MODE_TUNNEL) {
Benedict Wonge265d5f2018-11-08 19:45:34 -08001633 enforceTunnelFeatureAndPermissions(callingPackage);
Nathan Harold21208ee2018-03-15 18:06:06 -07001634 }
Nathan Harolda10003d2017-08-23 13:46:33 -07001635 checkIpSecConfig(c);
Daulet Zhanguzinea1a7ca2020-01-03 09:46:50 +00001636 Objects.requireNonNull(binder, "Null Binder passed to createTransform");
Nathan Haroldd8c74292017-12-13 19:16:33 -08001637 final int resourceId = mNextResourceId++;
Benedict Wong344bd622017-11-16 15:27:22 -08001638
1639 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
Benedict Wong4f9fb812017-12-13 17:16:53 -08001640 List<RefcountedResource> dependencies = new ArrayList<>();
Benedict Wong344bd622017-11-16 15:27:22 -08001641
1642 if (!userRecord.mTransformQuotaTracker.isAvailable()) {
Nathan Harolda1afbd82017-04-24 16:16:34 -07001643 return new IpSecTransformResponse(IpSecManager.Status.RESOURCE_UNAVAILABLE);
1644 }
Nathan Harolda10003d2017-08-23 13:46:33 -07001645
Benedict Wong344bd622017-11-16 15:27:22 -08001646 EncapSocketRecord socketRecord = null;
Benedict Wong0fe58a92018-01-19 17:36:02 -08001647 if (c.getEncapType() != IpSecTransform.ENCAP_NONE) {
Benedict Wong344bd622017-11-16 15:27:22 -08001648 RefcountedResource<EncapSocketRecord> refcountedSocketRecord =
1649 userRecord.mEncapSocketRecords.getRefcountedResourceOrThrow(
1650 c.getEncapSocketResourceId());
1651 dependencies.add(refcountedSocketRecord);
Benedict Wong344bd622017-11-16 15:27:22 -08001652 socketRecord = refcountedSocketRecord.getResource();
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001653 }
1654
Nathan Harolda2523312018-01-05 19:25:13 -08001655 RefcountedResource<SpiRecord> refcountedSpiRecord =
1656 userRecord.mSpiRecords.getRefcountedResourceOrThrow(c.getSpiResourceId());
1657 dependencies.add(refcountedSpiRecord);
1658 SpiRecord spiRecord = refcountedSpiRecord.getResource();
Benedict Wong344bd622017-11-16 15:27:22 -08001659
Nathan Harold144ce0a2018-04-03 16:13:19 -07001660 createOrUpdateTransform(c, resourceId, spiRecord, socketRecord);
Benedict Wong0fe58a92018-01-19 17:36:02 -08001661
1662 // SA was created successfully, time to construct a record and lock it away
Benedict Wong344bd622017-11-16 15:27:22 -08001663 userRecord.mTransformRecords.put(
1664 resourceId,
1665 new RefcountedResource<TransformRecord>(
Nathan Harolda2523312018-01-05 19:25:13 -08001666 new TransformRecord(resourceId, c, spiRecord, socketRecord),
Benedict Wong344bd622017-11-16 15:27:22 -08001667 binder,
1668 dependencies.toArray(new RefcountedResource[dependencies.size()])));
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001669 return new IpSecTransformResponse(IpSecManager.Status.OK, resourceId);
Nathan Harold93962f32017-03-07 13:23:36 -08001670 }
1671
1672 /**
1673 * Delete a transport mode transform that was previously allocated by + registered with the
1674 * system server. If this is called on an inactive (or non-existent) transform, it will not
1675 * return an error. It's safe to de-allocate transforms that may have already been deleted for
1676 * other reasons.
1677 */
1678 @Override
Benedict Wongf33f03132018-01-18 14:38:16 -08001679 public synchronized void deleteTransform(int resourceId) throws RemoteException {
Benedict Wong344bd622017-11-16 15:27:22 -08001680 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
1681 releaseResource(userRecord.mTransformRecords, resourceId);
Nathan Harold93962f32017-03-07 13:23:36 -08001682 }
1683
1684 /**
1685 * Apply an active transport mode transform to a socket, which will apply the IPsec security
1686 * association as a correspondent policy to the provided socket
1687 */
1688 @Override
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001689 public synchronized void applyTransportModeTransform(
Nathan Harolda2523312018-01-05 19:25:13 -08001690 ParcelFileDescriptor socket, int direction, int resourceId) throws RemoteException {
Benedict Wonga0989622018-07-25 13:06:29 -07001691 int callingUid = Binder.getCallingUid();
1692 UserRecord userRecord = mUserResourceTracker.getUserRecord(callingUid);
Nathan Harolda2523312018-01-05 19:25:13 -08001693 checkDirection(direction);
Benedict Wong344bd622017-11-16 15:27:22 -08001694 // Get transform record; if no transform is found, will throw IllegalArgumentException
1695 TransformRecord info = userRecord.mTransformRecords.getResourceOrThrow(resourceId);
Nathan Harold93962f32017-03-07 13:23:36 -08001696
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001697 // TODO: make this a function.
Benedict Wonga0989622018-07-25 13:06:29 -07001698 if (info.pid != getCallingPid() || info.uid != callingUid) {
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001699 throw new SecurityException("Only the owner of an IpSec Transform may apply it!");
1700 }
1701
Benedict Wong8149f6e2018-01-18 18:31:45 -08001702 // Get config and check that to-be-applied transform has the correct mode
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001703 IpSecConfig c = info.getConfig();
Benedict Wong8149f6e2018-01-18 18:31:45 -08001704 Preconditions.checkArgument(
1705 c.getMode() == IpSecTransform.MODE_TRANSPORT,
1706 "Transform mode was not Transport mode; cannot be applied to a socket");
1707
Nathan Harold144ce0a2018-04-03 16:13:19 -07001708 mSrvConfig
1709 .getNetdInstance()
1710 .ipSecApplyTransportModeTransform(
Luke Huange8e522b2018-11-23 12:01:41 +08001711 socket,
Benedict Wonga0989622018-07-25 13:06:29 -07001712 callingUid,
Nathan Harold144ce0a2018-04-03 16:13:19 -07001713 direction,
1714 c.getSourceAddress(),
1715 c.getDestinationAddress(),
1716 info.getSpiRecord().getSpi());
Nathan Harold93962f32017-03-07 13:23:36 -08001717 }
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001718
Nathan Harold93962f32017-03-07 13:23:36 -08001719 /**
Nathan Harolda2523312018-01-05 19:25:13 -08001720 * Remove transport mode transforms from a socket, applying the default (empty) policy. This
1721 * ensures that NO IPsec policy is applied to the socket (would be the equivalent of applying a
1722 * policy that performs no IPsec). Today the resourceId parameter is passed but not used:
1723 * reserved for future improved input validation.
Nathan Harold93962f32017-03-07 13:23:36 -08001724 */
1725 @Override
Nathan Haroldf73d2522018-01-17 01:00:20 -08001726 public synchronized void removeTransportModeTransforms(ParcelFileDescriptor socket)
1727 throws RemoteException {
Nathan Harold144ce0a2018-04-03 16:13:19 -07001728 mSrvConfig
1729 .getNetdInstance()
Luke Huange8e522b2018-11-23 12:01:41 +08001730 .ipSecRemoveTransportModeTransform(socket);
Nathan Harold93962f32017-03-07 13:23:36 -08001731 }
1732
Benedict Wong8149f6e2018-01-18 18:31:45 -08001733 /**
1734 * Apply an active tunnel mode transform to a TunnelInterface, which will apply the IPsec
1735 * security association as a correspondent policy to the provided interface
1736 */
1737 @Override
1738 public synchronized void applyTunnelModeTransform(
Nathan Harold21208ee2018-03-15 18:06:06 -07001739 int tunnelResourceId, int direction,
1740 int transformResourceId, String callingPackage) throws RemoteException {
Benedict Wonge265d5f2018-11-08 19:45:34 -08001741 enforceTunnelFeatureAndPermissions(callingPackage);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001742 checkDirection(direction);
1743
Benedict Wonga0989622018-07-25 13:06:29 -07001744 int callingUid = Binder.getCallingUid();
1745 UserRecord userRecord = mUserResourceTracker.getUserRecord(callingUid);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001746
1747 // Get transform record; if no transform is found, will throw IllegalArgumentException
1748 TransformRecord transformInfo =
1749 userRecord.mTransformRecords.getResourceOrThrow(transformResourceId);
1750
1751 // Get tunnelInterface record; if no such interface is found, will throw
1752 // IllegalArgumentException
1753 TunnelInterfaceRecord tunnelInterfaceInfo =
1754 userRecord.mTunnelInterfaceRecords.getResourceOrThrow(tunnelResourceId);
1755
1756 // Get config and check that to-be-applied transform has the correct mode
1757 IpSecConfig c = transformInfo.getConfig();
1758 Preconditions.checkArgument(
1759 c.getMode() == IpSecTransform.MODE_TUNNEL,
1760 "Transform mode was not Tunnel mode; cannot be applied to a tunnel interface");
1761
Benedict Wong0fe58a92018-01-19 17:36:02 -08001762 EncapSocketRecord socketRecord = null;
1763 if (c.getEncapType() != IpSecTransform.ENCAP_NONE) {
1764 socketRecord =
1765 userRecord.mEncapSocketRecords.getResourceOrThrow(c.getEncapSocketResourceId());
1766 }
1767 SpiRecord spiRecord = userRecord.mSpiRecords.getResourceOrThrow(c.getSpiResourceId());
1768
Benedict Wong8149f6e2018-01-18 18:31:45 -08001769 int mark =
Benedict Wong564e2aa2018-05-07 20:06:44 -07001770 (direction == IpSecManager.DIRECTION_OUT)
1771 ? tunnelInterfaceInfo.getOkey()
1772 : tunnelInterfaceInfo.getIkey();
Benedict Wong8149f6e2018-01-18 18:31:45 -08001773
Benedict Wong0fe58a92018-01-19 17:36:02 -08001774 try {
Benedict Wong781dae62018-09-06 11:31:25 -07001775 // Default to using the invalid SPI of 0 for inbound SAs. This allows policies to skip
1776 // SPI matching as part of the template resolution.
1777 int spi = IpSecManager.INVALID_SECURITY_PARAMETER_INDEX;
1778 c.setXfrmInterfaceId(tunnelInterfaceInfo.getIfId());
1779
Benedict Wongab80e1f2018-07-25 18:46:19 -07001780 // TODO: enable this when UPDSA supports updating marks. Adding kernel support upstream
1781 // (and backporting) would allow us to narrow the mark space, and ensure that the SA
1782 // and SPs have matching marks (as VTI are meant to be built).
1783 // Currently update does nothing with marks. Leave empty (defaulting to 0) to ensure the
1784 // config matches the actual allocated resources in the kernel.
Benedict Wongb2920572018-11-21 21:24:55 -08001785 // All SAs will have zero marks (from creation time), and any policy that matches the
1786 // same src/dst could match these SAs. Non-IpSecService governed processes that
1787 // establish floating policies with the same src/dst may result in undefined
1788 // behavior. This is generally limited to vendor code due to the permissions
1789 // (CAP_NET_ADMIN) required.
Benedict Wongab80e1f2018-07-25 18:46:19 -07001790 //
1791 // c.setMarkValue(mark);
1792 // c.setMarkMask(0xffffffff);
Benedict Wong0fe58a92018-01-19 17:36:02 -08001793
1794 if (direction == IpSecManager.DIRECTION_OUT) {
1795 // Set output mark via underlying network (output only)
1796 c.setNetwork(tunnelInterfaceInfo.getUnderlyingNetwork());
1797
Benedict Wong781dae62018-09-06 11:31:25 -07001798 // Set outbound SPI only. We want inbound to use any valid SA (old, new) on rekeys,
1799 // but want to guarantee outbound packets are sent over the new SA.
1800 spi = transformInfo.getSpiRecord().getSpi();
1801 }
1802
1803 // Always update the policy with the relevant XFRM_IF_ID
1804 for (int selAddrFamily : ADDRESS_FAMILIES) {
1805 mSrvConfig
1806 .getNetdInstance()
1807 .ipSecUpdateSecurityPolicy(
1808 callingUid,
1809 selAddrFamily,
1810 direction,
1811 transformInfo.getConfig().getSourceAddress(),
1812 transformInfo.getConfig().getDestinationAddress(),
1813 spi, // If outbound, also add SPI to the policy.
1814 mark, // Must always set policy mark; ikey/okey for VTIs
1815 0xffffffff,
1816 c.getXfrmInterfaceId());
Benedict Wong0fe58a92018-01-19 17:36:02 -08001817 }
1818
1819 // Update SA with tunnel mark (ikey or okey based on direction)
1820 createOrUpdateTransform(c, transformResourceId, spiRecord, socketRecord);
1821 } catch (ServiceSpecificException e) {
1822 if (e.errorCode == EINVAL) {
1823 throw new IllegalArgumentException(e.toString());
1824 } else {
1825 throw e;
1826 }
1827 }
Benedict Wong8149f6e2018-01-18 18:31:45 -08001828 }
1829
Nathan Harold93962f32017-03-07 13:23:36 -08001830 @Override
ludib0c95b12017-05-22 10:52:23 -07001831 protected synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Nathan Harold1afbef42017-03-01 18:55:06 -08001832 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
ludib0c95b12017-05-22 10:52:23 -07001833
1834 pw.println("IpSecService dump:");
Nathan Harold1afbef42017-03-01 18:55:06 -08001835 pw.println("NetdNativeService Connection: " + (isNetdAlive() ? "alive" : "dead"));
1836 pw.println();
ludib0c95b12017-05-22 10:52:23 -07001837
Benedict Wong344bd622017-11-16 15:27:22 -08001838 pw.println("mUserResourceTracker:");
1839 pw.println(mUserResourceTracker);
Nathan Harold1afbef42017-03-01 18:55:06 -08001840 }
1841}