blob: 71a7a2b5abd36a14cca407cc8879fa4bf0f200aa [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 Harold8dc1fd02017-04-04 19:37:48 -070028import static com.android.internal.util.Preconditions.checkNotNull;
Nathan Harold1afbef42017-03-01 18:55:06 -080029
Nathan Harold21208ee2018-03-15 18:06:06 -070030import android.annotation.NonNull;
31import android.app.AppOpsManager;
Nathan Harold1afbef42017-03-01 18:55:06 -080032import android.content.Context;
33import android.net.IIpSecService;
34import android.net.INetd;
Nathan Harold93962f32017-03-07 13:23:36 -080035import android.net.IpSecAlgorithm;
36import android.net.IpSecConfig;
37import android.net.IpSecManager;
Nathan Harold8dc1fd02017-04-04 19:37:48 -070038import android.net.IpSecSpiResponse;
Nathan Harold93962f32017-03-07 13:23:36 -080039import android.net.IpSecTransform;
Nathan Harold8dc1fd02017-04-04 19:37:48 -070040import android.net.IpSecTransformResponse;
Benedict Wong8149f6e2018-01-18 18:31:45 -080041import android.net.IpSecTunnelInterfaceResponse;
Nathan Harold8dc1fd02017-04-04 19:37:48 -070042import android.net.IpSecUdpEncapResponse;
Benedict Wongecc9f7c2018-03-01 18:53:07 -080043import android.net.LinkAddress;
Benedict Wong8149f6e2018-01-18 18:31:45 -080044import android.net.Network;
Nathan Harolda10003d2017-08-23 13:46:33 -070045import android.net.NetworkUtils;
Benedict Wongbabe5d72017-12-03 19:42:36 -080046import android.net.TrafficStats;
Nathan Harold1afbef42017-03-01 18:55:06 -080047import android.net.util.NetdService;
Nathan Harold93962f32017-03-07 13:23:36 -080048import android.os.Binder;
Nathan Harold93962f32017-03-07 13:23:36 -080049import android.os.IBinder;
50import android.os.ParcelFileDescriptor;
Nathan Harold1afbef42017-03-01 18:55:06 -080051import android.os.RemoteException;
Nathan Harold93962f32017-03-07 13:23:36 -080052import android.os.ServiceSpecificException;
Nathan Harold8dc1fd02017-04-04 19:37:48 -070053import android.system.ErrnoException;
54import android.system.Os;
55import android.system.OsConstants;
Nathan Harolda10003d2017-08-23 13:46:33 -070056import android.text.TextUtils;
Nathan Harold1afbef42017-03-01 18:55:06 -080057import android.util.Log;
58import android.util.Slog;
Nathan Harold93962f32017-03-07 13:23:36 -080059import android.util.SparseArray;
Benedict Wong8149f6e2018-01-18 18:31:45 -080060import android.util.SparseBooleanArray;
Nathan Harolda10003d2017-08-23 13:46:33 -070061
Nathan Harold93962f32017-03-07 13:23:36 -080062import com.android.internal.annotations.GuardedBy;
ludi1a06aa72017-05-12 09:15:00 -070063import com.android.internal.annotations.VisibleForTesting;
Benedict Wong4f255702017-11-06 20:49:10 -080064import com.android.internal.util.Preconditions;
Nathan Harolda10003d2017-08-23 13:46:33 -070065
Benedict Wongab80e1f2018-07-25 18:46:19 -070066import libcore.io.IoUtils;
67
Nathan Harold1afbef42017-03-01 18:55:06 -080068import java.io.FileDescriptor;
Nathan Harold8dc1fd02017-04-04 19:37:48 -070069import java.io.IOException;
Nathan Harold1afbef42017-03-01 18:55:06 -080070import java.io.PrintWriter;
evitayane4259d32018-03-22 17:53:08 -070071import java.net.Inet4Address;
72import java.net.Inet6Address;
Nathan Harold8dc1fd02017-04-04 19:37:48 -070073import java.net.InetAddress;
74import java.net.InetSocketAddress;
75import java.net.UnknownHostException;
Benedict Wong409c8ca2017-10-26 19:41:43 -070076import java.util.ArrayList;
77import java.util.List;
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 int MAX_PORT_BIND_ATTEMPTS = 10;
100 private static final InetAddress INADDR_ANY;
101
102 static {
103 try {
104 INADDR_ANY = InetAddress.getByAddress(new byte[] {0, 0, 0, 0});
105 } catch (UnknownHostException e) {
106 throw new RuntimeException(e);
107 }
108 }
109
110 static final int FREE_PORT_MIN = 1024; // ports 1-1023 are reserved
111 static final int PORT_MAX = 0xFFFF; // ports are an unsigned 16-bit integer
112
113 /* Binder context for this service */
Nathan Harold1afbef42017-03-01 18:55:06 -0800114 private final Context mContext;
115
Nathan Haroldd8c74292017-12-13 19:16:33 -0800116 /**
Nathan Harolda2523312018-01-05 19:25:13 -0800117 * The next non-repeating global ID for tracking resources between users, this service, and
118 * kernel data structures. Accessing this variable is not thread safe, so it is only read or
119 * modified within blocks synchronized on IpSecService.this. We want to avoid -1
120 * (INVALID_RESOURCE_ID) and 0 (we probably forgot to initialize it).
Nathan Haroldd8c74292017-12-13 19:16:33 -0800121 */
122 @GuardedBy("IpSecService.this")
123 private int mNextResourceId = 1;
Nathan Harold1afbef42017-03-01 18:55:06 -0800124
ludi1a06aa72017-05-12 09:15:00 -0700125 interface IpSecServiceConfiguration {
126 INetd getNetdInstance() throws RemoteException;
127
128 static IpSecServiceConfiguration GETSRVINSTANCE =
129 new IpSecServiceConfiguration() {
130 @Override
131 public INetd getNetdInstance() throws RemoteException {
132 final INetd netd = NetdService.getInstance();
133 if (netd == null) {
134 throw new RemoteException("Failed to Get Netd Instance");
135 }
136 return netd;
137 }
138 };
139 }
140
141 private final IpSecServiceConfiguration mSrvConfig;
Benedict Wongbabe5d72017-12-03 19:42:36 -0800142 final UidFdTagger mUidFdTagger;
ludi1a06aa72017-05-12 09:15:00 -0700143
Benedict Wong409c8ca2017-10-26 19:41:43 -0700144 /**
145 * Interface for user-reference and kernel-resource cleanup.
146 *
147 * <p>This interface must be implemented for a resource to be reference counted.
148 */
149 @VisibleForTesting
150 public interface IResource {
151 /**
152 * Invalidates a IResource object, ensuring it is invalid for the purposes of allocating new
153 * objects dependent on it.
154 *
155 * <p>Implementations of this method are expected to remove references to the IResource
156 * object from the IpSecService's tracking arrays. The removal from the arrays ensures that
157 * the resource is considered invalid for user access or allocation or use in other
158 * resources.
159 *
160 * <p>References to the IResource object may be held by other RefcountedResource objects,
Benedict Wong4f9fb812017-12-13 17:16:53 -0800161 * and as such, the underlying resources and quota may not be cleaned up.
Benedict Wong409c8ca2017-10-26 19:41:43 -0700162 */
163 void invalidate() throws RemoteException;
164
165 /**
166 * Releases underlying resources and related quotas.
167 *
168 * <p>Implementations of this method are expected to remove all system resources that are
169 * tracked by the IResource object. Due to other RefcountedResource objects potentially
Benedict Wong344bd622017-11-16 15:27:22 -0800170 * having references to the IResource object, freeUnderlyingResources may not always be
Benedict Wong409c8ca2017-10-26 19:41:43 -0700171 * called from releaseIfUnreferencedRecursively().
172 */
173 void freeUnderlyingResources() throws RemoteException;
174 }
175
176 /**
177 * RefcountedResource manages references and dependencies in an exclusively acyclic graph.
178 *
179 * <p>RefcountedResource implements both explicit and implicit resource management. Creating a
180 * RefcountedResource object creates an explicit reference that must be freed by calling
181 * userRelease(). Additionally, adding this object as a child of another RefcountedResource
182 * object will add an implicit reference.
183 *
184 * <p>Resources are cleaned up when all references, both implicit and explicit, are released
185 * (ie, when userRelease() is called and when all parents have called releaseReference() on this
186 * object.)
187 */
188 @VisibleForTesting
189 public class RefcountedResource<T extends IResource> implements IBinder.DeathRecipient {
190 private final T mResource;
191 private final List<RefcountedResource> mChildren;
192 int mRefCount = 1; // starts at 1 for user's reference.
193 IBinder mBinder;
194
195 RefcountedResource(T resource, IBinder binder, RefcountedResource... children) {
196 synchronized (IpSecService.this) {
197 this.mResource = resource;
198 this.mChildren = new ArrayList<>(children.length);
199 this.mBinder = binder;
200
201 for (RefcountedResource child : children) {
202 mChildren.add(child);
203 child.mRefCount++;
204 }
205
206 try {
207 mBinder.linkToDeath(this, 0);
208 } catch (RemoteException e) {
209 binderDied();
210 }
211 }
212 }
213
214 /**
215 * If the Binder object dies, this function is called to free the system resources that are
Benedict Wong344bd622017-11-16 15:27:22 -0800216 * being tracked by this record and to subsequently release this record for garbage
Benedict Wong409c8ca2017-10-26 19:41:43 -0700217 * collection
218 */
219 @Override
220 public void binderDied() {
221 synchronized (IpSecService.this) {
222 try {
223 userRelease();
224 } catch (Exception e) {
225 Log.e(TAG, "Failed to release resource: " + e);
226 }
227 }
228 }
229
230 public T getResource() {
231 return mResource;
232 }
233
234 /**
235 * Unlinks from binder and performs IpSecService resource cleanup (removes from resource
236 * arrays)
237 *
238 * <p>If this method has been previously called, the RefcountedResource's binder field will
239 * be null, and the method will return without performing the cleanup a second time.
240 *
241 * <p>Note that calling this function does not imply that kernel resources will be freed at
242 * this time, or that the related quota will be returned. Such actions will only be
243 * performed upon the reference count reaching zero.
244 */
245 @GuardedBy("IpSecService.this")
246 public void userRelease() throws RemoteException {
247 // Prevent users from putting reference counts into a bad state by calling
248 // userRelease() multiple times.
249 if (mBinder == null) {
250 return;
251 }
252
253 mBinder.unlinkToDeath(this, 0);
254 mBinder = null;
255
256 mResource.invalidate();
257
258 releaseReference();
259 }
260
261 /**
262 * Removes a reference to this resource. If the resultant reference count is zero, the
263 * underlying resources are freed, and references to all child resources are also dropped
264 * recursively (resulting in them freeing their resources and children, etcetera)
265 *
266 * <p>This method also sets the reference count to an invalid value (-1) to signify that it
267 * has been fully released. Any subsequent calls to this method will result in an
268 * IllegalStateException being thrown due to resource already having been previously
269 * released
270 */
271 @VisibleForTesting
272 @GuardedBy("IpSecService.this")
273 public void releaseReference() throws RemoteException {
274 mRefCount--;
275
276 if (mRefCount > 0) {
277 return;
278 } else if (mRefCount < 0) {
279 throw new IllegalStateException(
280 "Invalid operation - resource has already been released.");
281 }
282
283 // Cleanup own resources
284 mResource.freeUnderlyingResources();
285
286 // Cleanup child resources as needed
287 for (RefcountedResource<? extends IResource> child : mChildren) {
288 child.releaseReference();
289 }
290
291 // Enforce that resource cleanup can only be called once
292 // By decrementing the refcount (from 0 to -1), the next call will throw an
293 // IllegalStateException - it has already been released fully.
294 mRefCount--;
295 }
296
297 @Override
298 public String toString() {
299 return new StringBuilder()
300 .append("{mResource=")
301 .append(mResource)
302 .append(", mRefCount=")
303 .append(mRefCount)
304 .append(", mChildren=")
305 .append(mChildren)
306 .append("}")
307 .toString();
308 }
309 }
310
Benedict Wong4f9fb812017-12-13 17:16:53 -0800311 /**
312 * Very simple counting class that looks much like a counting semaphore
313 *
314 * <p>This class is not thread-safe, and expects that that users of this class will ensure
315 * synchronization and thread safety by holding the IpSecService.this instance lock.
316 */
Benedict Wong344bd622017-11-16 15:27:22 -0800317 @VisibleForTesting
318 static class ResourceTracker {
Nathan Harolda1afbd82017-04-24 16:16:34 -0700319 private final int mMax;
320 int mCurrent;
321
322 ResourceTracker(int max) {
323 mMax = max;
324 mCurrent = 0;
325 }
326
Benedict Wong344bd622017-11-16 15:27:22 -0800327 boolean isAvailable() {
Nathan Harolda1afbd82017-04-24 16:16:34 -0700328 return (mCurrent < mMax);
329 }
330
Benedict Wong344bd622017-11-16 15:27:22 -0800331 void take() {
Nathan Harolda1afbd82017-04-24 16:16:34 -0700332 if (!isAvailable()) {
333 Log.wtf(TAG, "Too many resources allocated!");
334 }
335 mCurrent++;
336 }
337
Benedict Wong344bd622017-11-16 15:27:22 -0800338 void give() {
Nathan Harolda1afbd82017-04-24 16:16:34 -0700339 if (mCurrent <= 0) {
340 Log.wtf(TAG, "We've released this resource too many times");
341 }
342 mCurrent--;
343 }
ludi3e5ea232017-08-10 15:44:40 -0700344
345 @Override
346 public String toString() {
347 return new StringBuilder()
348 .append("{mCurrent=")
349 .append(mCurrent)
350 .append(", mMax=")
351 .append(mMax)
352 .append("}")
353 .toString();
354 }
Nathan Harolda1afbd82017-04-24 16:16:34 -0700355 }
356
Benedict Wong344bd622017-11-16 15:27:22 -0800357 @VisibleForTesting
358 static final class UserRecord {
Benedict Wong344bd622017-11-16 15:27:22 -0800359 /* Maximum number of each type of resource that a single UID may possess */
Benedict Wong8149f6e2018-01-18 18:31:45 -0800360 public static final int MAX_NUM_TUNNEL_INTERFACES = 2;
Nathan Harolda1afbd82017-04-24 16:16:34 -0700361 public static final int MAX_NUM_ENCAP_SOCKETS = 2;
Nathan Harolda1afbd82017-04-24 16:16:34 -0700362 public static final int MAX_NUM_TRANSFORMS = 4;
Nathan Harolda1afbd82017-04-24 16:16:34 -0700363 public static final int MAX_NUM_SPIS = 8;
364
Benedict Wong4f9fb812017-12-13 17:16:53 -0800365 /**
366 * Store each of the OwnedResource types in an (thinly wrapped) sparse array for indexing
367 * and explicit (user) reference management.
368 *
369 * <p>These are stored in separate arrays to improve debuggability and dump output clarity.
370 *
371 * <p>Resources are removed from this array when the user releases their explicit reference
372 * by calling one of the releaseResource() methods.
373 */
Benedict Wong344bd622017-11-16 15:27:22 -0800374 final RefcountedResourceArray<SpiRecord> mSpiRecords =
Benedict Wong4f9fb812017-12-13 17:16:53 -0800375 new RefcountedResourceArray<>(SpiRecord.class.getSimpleName());
Benedict Wong344bd622017-11-16 15:27:22 -0800376 final RefcountedResourceArray<TransformRecord> mTransformRecords =
Benedict Wong4f9fb812017-12-13 17:16:53 -0800377 new RefcountedResourceArray<>(TransformRecord.class.getSimpleName());
Benedict Wong344bd622017-11-16 15:27:22 -0800378 final RefcountedResourceArray<EncapSocketRecord> mEncapSocketRecords =
Benedict Wong4f9fb812017-12-13 17:16:53 -0800379 new RefcountedResourceArray<>(EncapSocketRecord.class.getSimpleName());
Benedict Wong8149f6e2018-01-18 18:31:45 -0800380 final RefcountedResourceArray<TunnelInterfaceRecord> mTunnelInterfaceRecords =
381 new RefcountedResourceArray<>(TunnelInterfaceRecord.class.getSimpleName());
Benedict Wong4f9fb812017-12-13 17:16:53 -0800382
383 /**
384 * Trackers for quotas for each of the OwnedResource types.
385 *
386 * <p>These trackers are separate from the resource arrays, since they are incremented and
387 * decremented at different points in time. Specifically, quota is only returned upon final
388 * resource deallocation (after all explicit and implicit references are released). Note
389 * that it is possible that calls to releaseResource() will not return the used quota if
390 * there are other resources that depend on (are parents of) the resource being released.
391 */
392 final ResourceTracker mSpiQuotaTracker = new ResourceTracker(MAX_NUM_SPIS);
393 final ResourceTracker mTransformQuotaTracker = new ResourceTracker(MAX_NUM_TRANSFORMS);
Benedict Wong344bd622017-11-16 15:27:22 -0800394 final ResourceTracker mSocketQuotaTracker = new ResourceTracker(MAX_NUM_ENCAP_SOCKETS);
Benedict Wong8149f6e2018-01-18 18:31:45 -0800395 final ResourceTracker mTunnelQuotaTracker = new ResourceTracker(MAX_NUM_TUNNEL_INTERFACES);
Benedict Wong344bd622017-11-16 15:27:22 -0800396
397 void removeSpiRecord(int resourceId) {
398 mSpiRecords.remove(resourceId);
Nathan Harolda1afbd82017-04-24 16:16:34 -0700399 }
400
Benedict Wong344bd622017-11-16 15:27:22 -0800401 void removeTransformRecord(int resourceId) {
402 mTransformRecords.remove(resourceId);
403 }
404
Benedict Wong8149f6e2018-01-18 18:31:45 -0800405 void removeTunnelInterfaceRecord(int resourceId) {
406 mTunnelInterfaceRecords.remove(resourceId);
407 }
408
Benedict Wong344bd622017-11-16 15:27:22 -0800409 void removeEncapSocketRecord(int resourceId) {
410 mEncapSocketRecords.remove(resourceId);
411 }
412
413 @Override
414 public String toString() {
415 return new StringBuilder()
416 .append("{mSpiQuotaTracker=")
417 .append(mSpiQuotaTracker)
418 .append(", mTransformQuotaTracker=")
419 .append(mTransformQuotaTracker)
420 .append(", mSocketQuotaTracker=")
421 .append(mSocketQuotaTracker)
Benedict Wongb8ef5412018-01-24 15:31:39 -0800422 .append(", mTunnelQuotaTracker=")
423 .append(mTunnelQuotaTracker)
Benedict Wong344bd622017-11-16 15:27:22 -0800424 .append(", mSpiRecords=")
425 .append(mSpiRecords)
426 .append(", mTransformRecords=")
427 .append(mTransformRecords)
428 .append(", mEncapSocketRecords=")
429 .append(mEncapSocketRecords)
Benedict Wongb8ef5412018-01-24 15:31:39 -0800430 .append(", mTunnelInterfaceRecords=")
431 .append(mTunnelInterfaceRecords)
Benedict Wong344bd622017-11-16 15:27:22 -0800432 .append("}")
433 .toString();
434 }
435 }
436
Benedict Wong4f9fb812017-12-13 17:16:53 -0800437 /**
438 * This class is not thread-safe, and expects that that users of this class will ensure
439 * synchronization and thread safety by holding the IpSecService.this instance lock.
440 */
Benedict Wong344bd622017-11-16 15:27:22 -0800441 @VisibleForTesting
442 static final class UserResourceTracker {
Nathan Harolda1afbd82017-04-24 16:16:34 -0700443 private final SparseArray<UserRecord> mUserRecords = new SparseArray<>();
444
Benedict Wong4f9fb812017-12-13 17:16:53 -0800445 /** Lazy-initialization/getter that populates or retrieves the UserRecord as needed */
Benedict Wong344bd622017-11-16 15:27:22 -0800446 public UserRecord getUserRecord(int uid) {
447 checkCallerUid(uid);
448
Nathan Harolda1afbd82017-04-24 16:16:34 -0700449 UserRecord r = mUserRecords.get(uid);
450 if (r == null) {
451 r = new UserRecord();
452 mUserRecords.put(uid, r);
453 }
454 return r;
455 }
ludi3e5ea232017-08-10 15:44:40 -0700456
Benedict Wong344bd622017-11-16 15:27:22 -0800457 /** Safety method; guards against access of other user's UserRecords */
458 private void checkCallerUid(int uid) {
459 if (uid != Binder.getCallingUid()
460 && android.os.Process.SYSTEM_UID != Binder.getCallingUid()) {
461 throw new SecurityException("Attempted access of unowned resources");
462 }
463 }
464
ludi3e5ea232017-08-10 15:44:40 -0700465 @Override
466 public String toString() {
467 return mUserRecords.toString();
468 }
Nathan Harolda1afbd82017-04-24 16:16:34 -0700469 }
470
Benedict Wong344bd622017-11-16 15:27:22 -0800471 @VisibleForTesting final UserResourceTracker mUserResourceTracker = new UserResourceTracker();
Nathan Harolda1afbd82017-04-24 16:16:34 -0700472
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700473 /**
Benedict Wong4f9fb812017-12-13 17:16:53 -0800474 * The OwnedResourceRecord class provides a facility to cleanly and reliably track system
Benedict Wong344bd622017-11-16 15:27:22 -0800475 * resources. It relies on a provided resourceId that should uniquely identify the kernel
476 * resource. To use this class, the user should implement the invalidate() and
477 * freeUnderlyingResources() methods that are responsible for cleaning up IpSecService resource
Benedict Wong4f9fb812017-12-13 17:16:53 -0800478 * tracking arrays and kernel resources, respectively.
479 *
480 * <p>This class associates kernel resources with the UID that owns and controls them.
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700481 */
Benedict Wong4f9fb812017-12-13 17:16:53 -0800482 private abstract class OwnedResourceRecord implements IResource {
Nathan Harold93962f32017-03-07 13:23:36 -0800483 final int pid;
484 final int uid;
Benedict Wong344bd622017-11-16 15:27:22 -0800485 protected final int mResourceId;
Nathan Harold93962f32017-03-07 13:23:36 -0800486
Benedict Wong4f9fb812017-12-13 17:16:53 -0800487 OwnedResourceRecord(int resourceId) {
Nathan Harold93962f32017-03-07 13:23:36 -0800488 super();
Nathan Harolda1afbd82017-04-24 16:16:34 -0700489 if (resourceId == INVALID_RESOURCE_ID) {
490 throw new IllegalArgumentException("Resource ID must not be INVALID_RESOURCE_ID");
491 }
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700492 mResourceId = resourceId;
Nathan Harold93962f32017-03-07 13:23:36 -0800493 pid = Binder.getCallingPid();
494 uid = Binder.getCallingUid();
495
Nathan Harolda1afbd82017-04-24 16:16:34 -0700496 getResourceTracker().take();
Nathan Harold93962f32017-03-07 13:23:36 -0800497 }
498
Benedict Wong344bd622017-11-16 15:27:22 -0800499 @Override
500 public abstract void invalidate() throws RemoteException;
501
502 /** Convenience method; retrieves the user resource record for the stored UID. */
503 protected UserRecord getUserRecord() {
504 return mUserResourceTracker.getUserRecord(uid);
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700505 }
506
Benedict Wong344bd622017-11-16 15:27:22 -0800507 @Override
508 public abstract void freeUnderlyingResources() throws RemoteException;
ludib0c95b12017-05-22 10:52:23 -0700509
Nathan Harolda1afbd82017-04-24 16:16:34 -0700510 /** Get the resource tracker for this resource */
511 protected abstract ResourceTracker getResourceTracker();
512
ludib0c95b12017-05-22 10:52:23 -0700513 @Override
514 public String toString() {
515 return new StringBuilder()
516 .append("{mResourceId=")
517 .append(mResourceId)
518 .append(", pid=")
519 .append(pid)
520 .append(", uid=")
521 .append(uid)
ludib0c95b12017-05-22 10:52:23 -0700522 .append("}")
523 .toString();
524 }
Nathan Harold93962f32017-03-07 13:23:36 -0800525 };
526
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700527 /**
Benedict Wong344bd622017-11-16 15:27:22 -0800528 * Thin wrapper over SparseArray to ensure resources exist, and simplify generic typing.
529 *
530 * <p>RefcountedResourceArray prevents null insertions, and throws an IllegalArgumentException
531 * if a key is not found during a retrieval process.
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700532 */
Benedict Wong344bd622017-11-16 15:27:22 -0800533 static class RefcountedResourceArray<T extends IResource> {
534 SparseArray<RefcountedResource<T>> mArray = new SparseArray<>();
535 private final String mTypeName;
Nathan Harold93962f32017-03-07 13:23:36 -0800536
Benedict Wong344bd622017-11-16 15:27:22 -0800537 public RefcountedResourceArray(String typeName) {
538 this.mTypeName = typeName;
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700539 }
540
Benedict Wong344bd622017-11-16 15:27:22 -0800541 /**
542 * Accessor method to get inner resource object.
543 *
544 * @throws IllegalArgumentException if no resource with provided key is found.
545 */
546 T getResourceOrThrow(int key) {
547 return getRefcountedResourceOrThrow(key).getResource();
548 }
549
550 /**
551 * Accessor method to get reference counting wrapper.
552 *
553 * @throws IllegalArgumentException if no resource with provided key is found.
554 */
555 RefcountedResource<T> getRefcountedResourceOrThrow(int key) {
556 RefcountedResource<T> resource = mArray.get(key);
557 if (resource == null) {
558 throw new IllegalArgumentException(
559 String.format("No such %s found for given id: %d", mTypeName, key));
560 }
561
562 return resource;
563 }
564
565 void put(int key, RefcountedResource<T> obj) {
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700566 checkNotNull(obj, "Null resources cannot be added");
567 mArray.put(key, obj);
568 }
569
570 void remove(int key) {
571 mArray.remove(key);
572 }
ludib0c95b12017-05-22 10:52:23 -0700573
574 @Override
575 public String toString() {
576 return mArray.toString();
577 }
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700578 }
579
Benedict Wong4f9fb812017-12-13 17:16:53 -0800580 /**
581 * Tracks an SA in the kernel, and manages cleanup paths. Once a TransformRecord is
582 * created, the SpiRecord that originally tracked the SAs will reliquish the
583 * responsibility of freeing the underlying SA to this class via the mOwnedByTransform flag.
584 */
585 private final class TransformRecord extends OwnedResourceRecord {
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700586 private final IpSecConfig mConfig;
Nathan Harolda2523312018-01-05 19:25:13 -0800587 private final SpiRecord mSpi;
Benedict Wong344bd622017-11-16 15:27:22 -0800588 private final EncapSocketRecord mSocket;
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700589
590 TransformRecord(
Nathan Harolda2523312018-01-05 19:25:13 -0800591 int resourceId, IpSecConfig config, SpiRecord spi, EncapSocketRecord socket) {
Benedict Wong344bd622017-11-16 15:27:22 -0800592 super(resourceId);
Nathan Harold93962f32017-03-07 13:23:36 -0800593 mConfig = config;
Nathan Harolda2523312018-01-05 19:25:13 -0800594 mSpi = spi;
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700595 mSocket = socket;
Benedict Wonge6b42772017-12-13 18:26:40 -0800596
597 spi.setOwnedByTransform();
Nathan Harold93962f32017-03-07 13:23:36 -0800598 }
599
600 public IpSecConfig getConfig() {
601 return mConfig;
602 }
603
Nathan Harolda2523312018-01-05 19:25:13 -0800604 public SpiRecord getSpiRecord() {
605 return mSpi;
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700606 }
607
Benedict Wong0fe58a92018-01-19 17:36:02 -0800608 public EncapSocketRecord getSocketRecord() {
609 return mSocket;
610 }
611
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700612 /** always guarded by IpSecService#this */
Nathan Harold93962f32017-03-07 13:23:36 -0800613 @Override
Benedict Wong344bd622017-11-16 15:27:22 -0800614 public void freeUnderlyingResources() {
Nathan Harolda2523312018-01-05 19:25:13 -0800615 int spi = mSpi.getSpi();
616 try {
617 mSrvConfig
618 .getNetdInstance()
619 .ipSecDeleteSecurityAssociation(
Benedict Wonga0989622018-07-25 13:06:29 -0700620 uid,
Nathan Harolda2523312018-01-05 19:25:13 -0800621 mConfig.getSourceAddress(),
622 mConfig.getDestinationAddress(),
Di Lu0b611f42018-01-11 11:35:25 -0800623 spi,
624 mConfig.getMarkValue(),
Benedict Wong781dae62018-09-06 11:31:25 -0700625 mConfig.getMarkMask(),
626 mConfig.getXfrmInterfaceId());
Benedict Wongecc9f7c2018-03-01 18:53:07 -0800627 } catch (RemoteException | ServiceSpecificException e) {
628 Log.e(TAG, "Failed to delete SA with ID: " + mResourceId, e);
Nathan Harold93962f32017-03-07 13:23:36 -0800629 }
Nathan Harold93962f32017-03-07 13:23:36 -0800630
Benedict Wong344bd622017-11-16 15:27:22 -0800631 getResourceTracker().give();
Nathan Harold93962f32017-03-07 13:23:36 -0800632 }
ludib0c95b12017-05-22 10:52:23 -0700633
Benedict Wong344bd622017-11-16 15:27:22 -0800634 @Override
635 public void invalidate() throws RemoteException {
636 getUserRecord().removeTransformRecord(mResourceId);
637 }
638
639 @Override
Nathan Harolda1afbd82017-04-24 16:16:34 -0700640 protected ResourceTracker getResourceTracker() {
Benedict Wong344bd622017-11-16 15:27:22 -0800641 return getUserRecord().mTransformQuotaTracker;
Nathan Harolda1afbd82017-04-24 16:16:34 -0700642 }
643
ludib0c95b12017-05-22 10:52:23 -0700644 @Override
645 public String toString() {
646 StringBuilder strBuilder = new StringBuilder();
647 strBuilder
648 .append("{super=")
649 .append(super.toString())
650 .append(", mSocket=")
651 .append(mSocket)
Nathan Harolda2523312018-01-05 19:25:13 -0800652 .append(", mSpi.mResourceId=")
653 .append(mSpi.mResourceId)
ludib0c95b12017-05-22 10:52:23 -0700654 .append(", mConfig=")
655 .append(mConfig)
656 .append("}");
657 return strBuilder.toString();
658 }
Nathan Harold93962f32017-03-07 13:23:36 -0800659 }
660
Benedict Wong4f9fb812017-12-13 17:16:53 -0800661 /**
662 * Tracks a single SA in the kernel, and manages cleanup paths. Once used in a Transform, the
663 * responsibility for cleaning up underlying resources will be passed to the TransformRecord
664 * object
665 */
666 private final class SpiRecord extends OwnedResourceRecord {
Nathan Harolda2523312018-01-05 19:25:13 -0800667 private final String mSourceAddress;
668 private final String mDestinationAddress;
Nathan Harold93962f32017-03-07 13:23:36 -0800669 private int mSpi;
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700670
671 private boolean mOwnedByTransform = false;
Nathan Harold93962f32017-03-07 13:23:36 -0800672
Nathan Harolda2523312018-01-05 19:25:13 -0800673 SpiRecord(int resourceId, String sourceAddress, String destinationAddress, int spi) {
Benedict Wong344bd622017-11-16 15:27:22 -0800674 super(resourceId);
Nathan Harolda2523312018-01-05 19:25:13 -0800675 mSourceAddress = sourceAddress;
676 mDestinationAddress = destinationAddress;
Nathan Harold93962f32017-03-07 13:23:36 -0800677 mSpi = spi;
Nathan Harold93962f32017-03-07 13:23:36 -0800678 }
679
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700680 /** always guarded by IpSecService#this */
681 @Override
Benedict Wong344bd622017-11-16 15:27:22 -0800682 public void freeUnderlyingResources() {
Nathan Harold93962f32017-03-07 13:23:36 -0800683 try {
Nathan Harold22795302018-02-27 19:19:40 -0800684 if (!mOwnedByTransform) {
685 mSrvConfig
686 .getNetdInstance()
687 .ipSecDeleteSecurityAssociation(
Benedict Wong781dae62018-09-06 11:31:25 -0700688 uid, mSourceAddress, mDestinationAddress, mSpi, 0 /* mark */,
689 0 /* mask */, 0 /* if_id */);
Nathan Harold22795302018-02-27 19:19:40 -0800690 }
Benedict Wongecc9f7c2018-03-01 18:53:07 -0800691 } catch (ServiceSpecificException | RemoteException e) {
692 Log.e(TAG, "Failed to delete SPI reservation with ID: " + mResourceId, e);
Nathan Harold93962f32017-03-07 13:23:36 -0800693 }
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700694
695 mSpi = IpSecManager.INVALID_SECURITY_PARAMETER_INDEX;
Nathan Harold93962f32017-03-07 13:23:36 -0800696
Benedict Wong344bd622017-11-16 15:27:22 -0800697 getResourceTracker().give();
Nathan Harolda1afbd82017-04-24 16:16:34 -0700698 }
699
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700700 public int getSpi() {
701 return mSpi;
702 }
703
Nathan Harolda2523312018-01-05 19:25:13 -0800704 public String getDestinationAddress() {
705 return mDestinationAddress;
706 }
707
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700708 public void setOwnedByTransform() {
709 if (mOwnedByTransform) {
710 // Programming error
Andreas Gamped6d8e452017-07-11 10:25:09 -0700711 throw new IllegalStateException("Cannot own an SPI twice!");
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700712 }
713
714 mOwnedByTransform = true;
Nathan Harold93962f32017-03-07 13:23:36 -0800715 }
ludib0c95b12017-05-22 10:52:23 -0700716
Benedict Wonge6b42772017-12-13 18:26:40 -0800717 public boolean getOwnedByTransform() {
718 return mOwnedByTransform;
719 }
720
ludib0c95b12017-05-22 10:52:23 -0700721 @Override
Benedict Wong344bd622017-11-16 15:27:22 -0800722 public void invalidate() throws RemoteException {
723 getUserRecord().removeSpiRecord(mResourceId);
724 }
725
726 @Override
727 protected ResourceTracker getResourceTracker() {
728 return getUserRecord().mSpiQuotaTracker;
729 }
730
731 @Override
ludib0c95b12017-05-22 10:52:23 -0700732 public String toString() {
733 StringBuilder strBuilder = new StringBuilder();
734 strBuilder
735 .append("{super=")
736 .append(super.toString())
737 .append(", mSpi=")
738 .append(mSpi)
Nathan Harolda2523312018-01-05 19:25:13 -0800739 .append(", mSourceAddress=")
740 .append(mSourceAddress)
741 .append(", mDestinationAddress=")
742 .append(mDestinationAddress)
ludib0c95b12017-05-22 10:52:23 -0700743 .append(", mOwnedByTransform=")
744 .append(mOwnedByTransform)
745 .append("}");
746 return strBuilder.toString();
747 }
Nathan Harold93962f32017-03-07 13:23:36 -0800748 }
749
Benedict Wong8149f6e2018-01-18 18:31:45 -0800750 // These values have been reserved in ConnectivityService
751 @VisibleForTesting static final int TUN_INTF_NETID_START = 0xFC00;
752
753 @VisibleForTesting static final int TUN_INTF_NETID_RANGE = 0x0400;
754
755 private final SparseBooleanArray mTunnelNetIds = new SparseBooleanArray();
756 private int mNextTunnelNetIdIndex = 0;
757
758 /**
759 * Reserves a netId within the range of netIds allocated for IPsec tunnel interfaces
760 *
761 * <p>This method should only be called from Binder threads. Do not call this from within the
762 * system server as it will crash the system on failure.
763 *
764 * @return an integer key within the netId range, if successful
765 * @throws IllegalStateException if unsuccessful (all netId are currently reserved)
766 */
767 @VisibleForTesting
768 int reserveNetId() {
769 synchronized (mTunnelNetIds) {
770 for (int i = 0; i < TUN_INTF_NETID_RANGE; i++) {
771 int index = mNextTunnelNetIdIndex;
772 int netId = index + TUN_INTF_NETID_START;
773 if (++mNextTunnelNetIdIndex >= TUN_INTF_NETID_RANGE) mNextTunnelNetIdIndex = 0;
774 if (!mTunnelNetIds.get(netId)) {
775 mTunnelNetIds.put(netId, true);
776 return netId;
777 }
778 }
779 }
780 throw new IllegalStateException("No free netIds to allocate");
781 }
782
783 @VisibleForTesting
784 void releaseNetId(int netId) {
785 synchronized (mTunnelNetIds) {
786 mTunnelNetIds.delete(netId);
787 }
788 }
789
790 private final class TunnelInterfaceRecord extends OwnedResourceRecord {
791 private final String mInterfaceName;
792 private final Network mUnderlyingNetwork;
793
794 // outer addresses
795 private final String mLocalAddress;
796 private final String mRemoteAddress;
797
798 private final int mIkey;
799 private final int mOkey;
800
Benedict Wong781dae62018-09-06 11:31:25 -0700801 private final int mIfId;
802
Benedict Wong8149f6e2018-01-18 18:31:45 -0800803 TunnelInterfaceRecord(
804 int resourceId,
805 String interfaceName,
806 Network underlyingNetwork,
807 String localAddr,
808 String remoteAddr,
809 int ikey,
Benedict Wong781dae62018-09-06 11:31:25 -0700810 int okey,
811 int intfId) {
Benedict Wong8149f6e2018-01-18 18:31:45 -0800812 super(resourceId);
813
814 mInterfaceName = interfaceName;
815 mUnderlyingNetwork = underlyingNetwork;
816 mLocalAddress = localAddr;
817 mRemoteAddress = remoteAddr;
818 mIkey = ikey;
819 mOkey = okey;
Benedict Wong781dae62018-09-06 11:31:25 -0700820 mIfId = intfId;
Benedict Wong8149f6e2018-01-18 18:31:45 -0800821 }
822
823 /** always guarded by IpSecService#this */
824 @Override
825 public void freeUnderlyingResources() {
Benedict Wong0fe58a92018-01-19 17:36:02 -0800826 // Calls to netd
Benedict Wong8149f6e2018-01-18 18:31:45 -0800827 // Teardown VTI
828 // Delete global policies
Benedict Wong0fe58a92018-01-19 17:36:02 -0800829 try {
Benedict Wong564e2aa2018-05-07 20:06:44 -0700830 final INetd netd = mSrvConfig.getNetdInstance();
Benedict Wong781dae62018-09-06 11:31:25 -0700831 netd.ipSecRemoveTunnelInterface(mInterfaceName);
Benedict Wong0fe58a92018-01-19 17:36:02 -0800832
Benedict Wong564e2aa2018-05-07 20:06:44 -0700833 for (int selAddrFamily : ADDRESS_FAMILIES) {
834 netd.ipSecDeleteSecurityPolicy(
Benedict Wonga0989622018-07-25 13:06:29 -0700835 uid,
Benedict Wong564e2aa2018-05-07 20:06:44 -0700836 selAddrFamily,
837 IpSecManager.DIRECTION_OUT,
838 mOkey,
Benedict Wong781dae62018-09-06 11:31:25 -0700839 0xffffffff,
840 mIfId);
Benedict Wong564e2aa2018-05-07 20:06:44 -0700841 netd.ipSecDeleteSecurityPolicy(
Benedict Wonga0989622018-07-25 13:06:29 -0700842 uid,
Benedict Wong564e2aa2018-05-07 20:06:44 -0700843 selAddrFamily,
844 IpSecManager.DIRECTION_IN,
845 mIkey,
Benedict Wong781dae62018-09-06 11:31:25 -0700846 0xffffffff,
847 mIfId);
Benedict Wong0fe58a92018-01-19 17:36:02 -0800848 }
Benedict Wongecc9f7c2018-03-01 18:53:07 -0800849 } catch (ServiceSpecificException | RemoteException e) {
Benedict Wong0fe58a92018-01-19 17:36:02 -0800850 Log.e(
851 TAG,
852 "Failed to delete VTI with interface name: "
853 + mInterfaceName
854 + " and id: "
Benedict Wongecc9f7c2018-03-01 18:53:07 -0800855 + mResourceId, e);
Benedict Wong0fe58a92018-01-19 17:36:02 -0800856 }
Benedict Wong8149f6e2018-01-18 18:31:45 -0800857
858 getResourceTracker().give();
859 releaseNetId(mIkey);
860 releaseNetId(mOkey);
861 }
862
863 public String getInterfaceName() {
864 return mInterfaceName;
865 }
866
867 public Network getUnderlyingNetwork() {
868 return mUnderlyingNetwork;
869 }
870
871 /** Returns the local, outer address for the tunnelInterface */
872 public String getLocalAddress() {
873 return mLocalAddress;
874 }
875
876 /** Returns the remote, outer address for the tunnelInterface */
877 public String getRemoteAddress() {
878 return mRemoteAddress;
879 }
880
881 public int getIkey() {
882 return mIkey;
883 }
884
885 public int getOkey() {
886 return mOkey;
887 }
888
Benedict Wong781dae62018-09-06 11:31:25 -0700889 public int getIfId() {
890 return mIfId;
891 }
892
Benedict Wong8149f6e2018-01-18 18:31:45 -0800893 @Override
894 protected ResourceTracker getResourceTracker() {
895 return getUserRecord().mTunnelQuotaTracker;
896 }
897
898 @Override
899 public void invalidate() {
900 getUserRecord().removeTunnelInterfaceRecord(mResourceId);
901 }
902
903 @Override
904 public String toString() {
905 return new StringBuilder()
906 .append("{super=")
907 .append(super.toString())
908 .append(", mInterfaceName=")
909 .append(mInterfaceName)
910 .append(", mUnderlyingNetwork=")
911 .append(mUnderlyingNetwork)
912 .append(", mLocalAddress=")
913 .append(mLocalAddress)
914 .append(", mRemoteAddress=")
915 .append(mRemoteAddress)
916 .append(", mIkey=")
917 .append(mIkey)
918 .append(", mOkey=")
919 .append(mOkey)
920 .append("}")
921 .toString();
922 }
923 }
924
Benedict Wong4f9fb812017-12-13 17:16:53 -0800925 /**
926 * Tracks a UDP encap socket, and manages cleanup paths
927 *
928 * <p>While this class does not manage non-kernel resources, race conditions around socket
929 * binding require that the service creates the encap socket, binds it and applies the socket
930 * policy before handing it to a user.
931 */
932 private final class EncapSocketRecord extends OwnedResourceRecord {
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700933 private FileDescriptor mSocket;
934 private final int mPort;
Nathan Harold93962f32017-03-07 13:23:36 -0800935
Benedict Wong344bd622017-11-16 15:27:22 -0800936 EncapSocketRecord(int resourceId, FileDescriptor socket, int port) {
937 super(resourceId);
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700938 mSocket = socket;
939 mPort = port;
940 }
941
942 /** always guarded by IpSecService#this */
943 @Override
Benedict Wong344bd622017-11-16 15:27:22 -0800944 public void freeUnderlyingResources() {
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700945 Log.d(TAG, "Closing port " + mPort);
946 IoUtils.closeQuietly(mSocket);
947 mSocket = null;
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700948
Benedict Wong344bd622017-11-16 15:27:22 -0800949 getResourceTracker().give();
Nathan Harolda1afbd82017-04-24 16:16:34 -0700950 }
951
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700952 public int getPort() {
953 return mPort;
954 }
955
Benedict Wong4c987eb2018-03-27 16:55:48 -0700956 public FileDescriptor getFileDescriptor() {
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700957 return mSocket;
958 }
ludib0c95b12017-05-22 10:52:23 -0700959
960 @Override
Benedict Wong344bd622017-11-16 15:27:22 -0800961 protected ResourceTracker getResourceTracker() {
962 return getUserRecord().mSocketQuotaTracker;
963 }
964
965 @Override
966 public void invalidate() {
967 getUserRecord().removeEncapSocketRecord(mResourceId);
968 }
969
970 @Override
ludib0c95b12017-05-22 10:52:23 -0700971 public String toString() {
972 return new StringBuilder()
973 .append("{super=")
974 .append(super.toString())
975 .append(", mSocket=")
976 .append(mSocket)
977 .append(", mPort=")
978 .append(mPort)
979 .append("}")
980 .toString();
981 }
Nathan Harold8dc1fd02017-04-04 19:37:48 -0700982 }
Nathan Harold93962f32017-03-07 13:23:36 -0800983
Nathan Harold1afbef42017-03-01 18:55:06 -0800984 /**
985 * Constructs a new IpSecService instance
986 *
987 * @param context Binder context for this service
988 */
989 private IpSecService(Context context) {
ludi1a06aa72017-05-12 09:15:00 -0700990 this(context, IpSecServiceConfiguration.GETSRVINSTANCE);
Nathan Harold1afbef42017-03-01 18:55:06 -0800991 }
992
993 static IpSecService create(Context context) throws InterruptedException {
994 final IpSecService service = new IpSecService(context);
995 service.connectNativeNetdService();
996 return service;
997 }
998
Nathan Harold21208ee2018-03-15 18:06:06 -0700999 @NonNull
1000 private AppOpsManager getAppOpsManager() {
1001 AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
1002 if(appOps == null) throw new RuntimeException("System Server couldn't get AppOps");
1003 return appOps;
1004 }
1005
ludi1a06aa72017-05-12 09:15:00 -07001006 /** @hide */
1007 @VisibleForTesting
1008 public IpSecService(Context context, IpSecServiceConfiguration config) {
Nathan Harolda2523312018-01-05 19:25:13 -08001009 this(
1010 context,
1011 config,
1012 (fd, uid) -> {
1013 try {
1014 TrafficStats.setThreadStatsUid(uid);
1015 TrafficStats.tagFileDescriptor(fd);
1016 } finally {
1017 TrafficStats.clearThreadStatsUid();
1018 }
1019 });
Benedict Wongbabe5d72017-12-03 19:42:36 -08001020 }
1021
1022 /** @hide */
1023 @VisibleForTesting
1024 public IpSecService(
1025 Context context, IpSecServiceConfiguration config, UidFdTagger uidFdTagger) {
ludi1a06aa72017-05-12 09:15:00 -07001026 mContext = context;
1027 mSrvConfig = config;
Benedict Wongbabe5d72017-12-03 19:42:36 -08001028 mUidFdTagger = uidFdTagger;
ludi1a06aa72017-05-12 09:15:00 -07001029 }
1030
Nathan Harold1afbef42017-03-01 18:55:06 -08001031 public void systemReady() {
1032 if (isNetdAlive()) {
1033 Slog.d(TAG, "IpSecService is ready");
1034 } else {
1035 Slog.wtf(TAG, "IpSecService not ready: failed to connect to NetD Native Service!");
1036 }
1037 }
1038
1039 private void connectNativeNetdService() {
1040 // Avoid blocking the system server to do this
Nathan Haroldb0e05082017-07-17 14:01:53 -07001041 new Thread() {
1042 @Override
1043 public void run() {
1044 synchronized (IpSecService.this) {
ludi1a06aa72017-05-12 09:15:00 -07001045 NetdService.get(NETD_FETCH_TIMEOUT_MS);
Nathan Haroldb0e05082017-07-17 14:01:53 -07001046 }
1047 }
1048 }.start();
Nathan Harold1afbef42017-03-01 18:55:06 -08001049 }
1050
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001051 synchronized boolean isNetdAlive() {
1052 try {
ludi1a06aa72017-05-12 09:15:00 -07001053 final INetd netd = mSrvConfig.getNetdInstance();
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001054 if (netd == null) {
Nathan Harold1afbef42017-03-01 18:55:06 -08001055 return false;
1056 }
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001057 return netd.isAlive();
1058 } catch (RemoteException re) {
1059 return false;
Nathan Harold1afbef42017-03-01 18:55:06 -08001060 }
1061 }
1062
Nathan Harolda10003d2017-08-23 13:46:33 -07001063 /**
1064 * Checks that the provided InetAddress is valid for use in an IPsec SA. The address must not be
1065 * a wildcard address and must be in a numeric form such as 1.2.3.4 or 2001::1.
1066 */
1067 private static void checkInetAddress(String inetAddress) {
1068 if (TextUtils.isEmpty(inetAddress)) {
1069 throw new IllegalArgumentException("Unspecified address");
1070 }
1071
1072 InetAddress checkAddr = NetworkUtils.numericToInetAddress(inetAddress);
1073
1074 if (checkAddr.isAnyLocalAddress()) {
1075 throw new IllegalArgumentException("Inappropriate wildcard address: " + inetAddress);
1076 }
1077 }
1078
1079 /**
1080 * Checks the user-provided direction field and throws an IllegalArgumentException if it is not
1081 * DIRECTION_IN or DIRECTION_OUT
1082 */
1083 private static void checkDirection(int direction) {
1084 switch (direction) {
Nathan Harolda2523312018-01-05 19:25:13 -08001085 case IpSecManager.DIRECTION_OUT:
1086 case IpSecManager.DIRECTION_IN:
Nathan Harolda10003d2017-08-23 13:46:33 -07001087 return;
1088 }
1089 throw new IllegalArgumentException("Invalid Direction: " + direction);
1090 }
1091
Nathan Harold93962f32017-03-07 13:23:36 -08001092 /** Get a new SPI and maintain the reservation in the system server */
Jonathan Basseri5fb92902017-11-16 10:58:01 -08001093 @Override
1094 public synchronized IpSecSpiResponse allocateSecurityParameterIndex(
Nathan Harolda2523312018-01-05 19:25:13 -08001095 String destinationAddress, int requestedSpi, IBinder binder) throws RemoteException {
1096 checkInetAddress(destinationAddress);
Nathan Harold7f606ee2018-03-28 08:52:51 -07001097 // RFC 4303 Section 2.1 - 0=local, 1-255=reserved.
1098 if (requestedSpi > 0 && requestedSpi < 256) {
1099 throw new IllegalArgumentException("ESP SPI must not be in the range of 0-255.");
1100 }
Jonathan Basseri5fb92902017-11-16 10:58:01 -08001101 checkNotNull(binder, "Null Binder passed to allocateSecurityParameterIndex");
Nathan Harolda10003d2017-08-23 13:46:33 -07001102
Benedict Wonga0989622018-07-25 13:06:29 -07001103 int callingUid = Binder.getCallingUid();
1104 UserRecord userRecord = mUserResourceTracker.getUserRecord(callingUid);
Nathan Haroldd8c74292017-12-13 19:16:33 -08001105 final int resourceId = mNextResourceId++;
Nathan Harold93962f32017-03-07 13:23:36 -08001106
1107 int spi = IpSecManager.INVALID_SECURITY_PARAMETER_INDEX;
Nathan Harold93962f32017-03-07 13:23:36 -08001108 try {
Benedict Wong344bd622017-11-16 15:27:22 -08001109 if (!userRecord.mSpiQuotaTracker.isAvailable()) {
Nathan Harolda1afbd82017-04-24 16:16:34 -07001110 return new IpSecSpiResponse(
Nathan Harolda10003d2017-08-23 13:46:33 -07001111 IpSecManager.Status.RESOURCE_UNAVAILABLE, INVALID_RESOURCE_ID, spi);
Nathan Harolda1afbd82017-04-24 16:16:34 -07001112 }
Nathan Harolda2523312018-01-05 19:25:13 -08001113
Nathan Harold93962f32017-03-07 13:23:36 -08001114 spi =
ludi1a06aa72017-05-12 09:15:00 -07001115 mSrvConfig
1116 .getNetdInstance()
Benedict Wonga0989622018-07-25 13:06:29 -07001117 .ipSecAllocateSpi(callingUid, "", destinationAddress, requestedSpi);
Nathan Harold93962f32017-03-07 13:23:36 -08001118 Log.d(TAG, "Allocated SPI " + spi);
Benedict Wong344bd622017-11-16 15:27:22 -08001119 userRecord.mSpiRecords.put(
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001120 resourceId,
Benedict Wong344bd622017-11-16 15:27:22 -08001121 new RefcountedResource<SpiRecord>(
Nathan Harolda2523312018-01-05 19:25:13 -08001122 new SpiRecord(resourceId, "", destinationAddress, spi), binder));
Nathan Harold93962f32017-03-07 13:23:36 -08001123 } catch (ServiceSpecificException e) {
Nathan Harold144ce0a2018-04-03 16:13:19 -07001124 if (e.errorCode == OsConstants.ENOENT) {
1125 return new IpSecSpiResponse(
1126 IpSecManager.Status.SPI_UNAVAILABLE, INVALID_RESOURCE_ID, spi);
1127 }
1128 throw e;
Nathan Harold93962f32017-03-07 13:23:36 -08001129 } catch (RemoteException e) {
1130 throw e.rethrowFromSystemServer();
1131 }
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001132 return new IpSecSpiResponse(IpSecManager.Status.OK, resourceId, spi);
1133 }
1134
1135 /* This method should only be called from Binder threads. Do not call this from
1136 * within the system server as it will crash the system on failure.
1137 */
Benedict Wong344bd622017-11-16 15:27:22 -08001138 private void releaseResource(RefcountedResourceArray resArray, int resourceId)
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001139 throws RemoteException {
Benedict Wong344bd622017-11-16 15:27:22 -08001140 resArray.getRefcountedResourceOrThrow(resourceId).userRelease();
Nathan Harold93962f32017-03-07 13:23:36 -08001141 }
1142
1143 /** Release a previously allocated SPI that has been registered with the system server */
1144 @Override
Benedict Wong344bd622017-11-16 15:27:22 -08001145 public synchronized void releaseSecurityParameterIndex(int resourceId) throws RemoteException {
1146 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
1147 releaseResource(userRecord.mSpiRecords, resourceId);
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001148 }
1149
1150 /**
1151 * This function finds and forcibly binds to a random system port, ensuring that the port cannot
1152 * be unbound.
1153 *
1154 * <p>A socket cannot be un-bound from a port if it was bound to that port by number. To select
1155 * a random open port and then bind by number, this function creates a temp socket, binds to a
1156 * random port (specifying 0), gets that port number, and then uses is to bind the user's UDP
1157 * Encapsulation Socket forcibly, so that it cannot be un-bound by the user with the returned
1158 * FileHandle.
1159 *
1160 * <p>The loop in this function handles the inherent race window between un-binding to a port
1161 * and re-binding, during which the system could *technically* hand that port out to someone
1162 * else.
1163 */
Benedict Wongf186d672017-10-10 20:44:28 -07001164 private int bindToRandomPort(FileDescriptor sockFd) throws IOException {
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001165 for (int i = MAX_PORT_BIND_ATTEMPTS; i > 0; i--) {
1166 try {
1167 FileDescriptor probeSocket = Os.socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1168 Os.bind(probeSocket, INADDR_ANY, 0);
1169 int port = ((InetSocketAddress) Os.getsockname(probeSocket)).getPort();
1170 Os.close(probeSocket);
1171 Log.v(TAG, "Binding to port " + port);
1172 Os.bind(sockFd, INADDR_ANY, port);
Benedict Wongf186d672017-10-10 20:44:28 -07001173 return port;
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001174 } catch (ErrnoException e) {
1175 // Someone miraculously claimed the port just after we closed probeSocket.
1176 if (e.errno == OsConstants.EADDRINUSE) {
1177 continue;
1178 }
1179 throw e.rethrowAsIOException();
1180 }
1181 }
1182 throw new IOException("Failed " + MAX_PORT_BIND_ATTEMPTS + " attempts to bind to a port");
1183 }
Nathan Harold93962f32017-03-07 13:23:36 -08001184
1185 /**
Benedict Wongbabe5d72017-12-03 19:42:36 -08001186 * Functional interface to do traffic tagging of given sockets to UIDs.
1187 *
1188 * <p>Specifically used by openUdpEncapsulationSocket to ensure data usage on the UDP encap
1189 * sockets are billed to the UID that the UDP encap socket was created on behalf of.
1190 *
1191 * <p>Separate class so that the socket tagging logic can be mocked; TrafficStats uses static
1192 * methods that cannot be easily mocked/tested.
1193 */
1194 @VisibleForTesting
1195 public interface UidFdTagger {
1196 /**
1197 * Sets socket tag to assign all traffic to the provided UID.
1198 *
1199 * <p>Since the socket is created on behalf of an unprivileged application, all traffic
1200 * should be accounted to the UID of the unprivileged application.
1201 */
1202 public void tag(FileDescriptor fd, int uid) throws IOException;
1203 }
1204
1205 /**
Nathan Harold93962f32017-03-07 13:23:36 -08001206 * Open a socket via the system server and bind it to the specified port (random if port=0).
1207 * This will return a PFD to the user that represent a bound UDP socket. The system server will
1208 * cache the socket and a record of its owner so that it can and must be freed when no longer
1209 * needed.
1210 */
1211 @Override
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001212 public synchronized IpSecUdpEncapResponse openUdpEncapsulationSocket(int port, IBinder binder)
1213 throws RemoteException {
1214 if (port != 0 && (port < FREE_PORT_MIN || port > PORT_MAX)) {
1215 throw new IllegalArgumentException(
1216 "Specified port number must be a valid non-reserved UDP port");
1217 }
Nathan Harolda10003d2017-08-23 13:46:33 -07001218 checkNotNull(binder, "Null Binder passed to openUdpEncapsulationSocket");
1219
Benedict Wongbabe5d72017-12-03 19:42:36 -08001220 int callingUid = Binder.getCallingUid();
1221 UserRecord userRecord = mUserResourceTracker.getUserRecord(callingUid);
Nathan Haroldd8c74292017-12-13 19:16:33 -08001222 final int resourceId = mNextResourceId++;
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001223 FileDescriptor sockFd = null;
1224 try {
Benedict Wong344bd622017-11-16 15:27:22 -08001225 if (!userRecord.mSocketQuotaTracker.isAvailable()) {
Nathan Harolda1afbd82017-04-24 16:16:34 -07001226 return new IpSecUdpEncapResponse(IpSecManager.Status.RESOURCE_UNAVAILABLE);
1227 }
1228
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001229 sockFd = Os.socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
Benedict Wongbabe5d72017-12-03 19:42:36 -08001230 mUidFdTagger.tag(sockFd, callingUid);
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001231
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001232 // This code is common to both the unspecified and specified port cases
1233 Os.setsockoptInt(
1234 sockFd,
1235 OsConstants.IPPROTO_UDP,
1236 OsConstants.UDP_ENCAP,
1237 OsConstants.UDP_ENCAP_ESPINUDP);
1238
Benedict Wongba8d3132017-12-06 21:56:35 -08001239 mSrvConfig.getNetdInstance().ipSecSetEncapSocketOwner(sockFd, callingUid);
1240 if (port != 0) {
1241 Log.v(TAG, "Binding to port " + port);
1242 Os.bind(sockFd, INADDR_ANY, port);
1243 } else {
1244 port = bindToRandomPort(sockFd);
1245 }
1246
Benedict Wong344bd622017-11-16 15:27:22 -08001247 userRecord.mEncapSocketRecords.put(
1248 resourceId,
1249 new RefcountedResource<EncapSocketRecord>(
1250 new EncapSocketRecord(resourceId, sockFd, port), binder));
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001251 return new IpSecUdpEncapResponse(IpSecManager.Status.OK, resourceId, port, sockFd);
1252 } catch (IOException | ErrnoException e) {
1253 IoUtils.closeQuietly(sockFd);
1254 }
1255 // If we make it to here, then something has gone wrong and we couldn't open a socket.
1256 // The only reasonable condition that would cause that is resource unavailable.
1257 return new IpSecUdpEncapResponse(IpSecManager.Status.RESOURCE_UNAVAILABLE);
Nathan Harold93962f32017-03-07 13:23:36 -08001258 }
1259
1260 /** close a socket that has been been allocated by and registered with the system server */
1261 @Override
Benedict Wong344bd622017-11-16 15:27:22 -08001262 public synchronized void closeUdpEncapsulationSocket(int resourceId) throws RemoteException {
1263 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
1264 releaseResource(userRecord.mEncapSocketRecords, resourceId);
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001265 }
Nathan Harold93962f32017-03-07 13:23:36 -08001266
Benedict Wong8149f6e2018-01-18 18:31:45 -08001267 /**
1268 * Create a tunnel interface for use in IPSec tunnel mode. The system server will cache the
1269 * tunnel interface and a record of its owner so that it can and must be freed when no longer
1270 * needed.
1271 */
1272 @Override
1273 public synchronized IpSecTunnelInterfaceResponse createTunnelInterface(
Nathan Harold21208ee2018-03-15 18:06:06 -07001274 String localAddr, String remoteAddr, Network underlyingNetwork, IBinder binder,
1275 String callingPackage) {
1276 enforceTunnelPermissions(callingPackage);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001277 checkNotNull(binder, "Null Binder passed to createTunnelInterface");
1278 checkNotNull(underlyingNetwork, "No underlying network was specified");
1279 checkInetAddress(localAddr);
1280 checkInetAddress(remoteAddr);
1281
1282 // TODO: Check that underlying network exists, and IP addresses not assigned to a different
1283 // network (b/72316676).
1284
Benedict Wonga0989622018-07-25 13:06:29 -07001285 int callerUid = Binder.getCallingUid();
1286 UserRecord userRecord = mUserResourceTracker.getUserRecord(callerUid);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001287 if (!userRecord.mTunnelQuotaTracker.isAvailable()) {
1288 return new IpSecTunnelInterfaceResponse(IpSecManager.Status.RESOURCE_UNAVAILABLE);
1289 }
1290
1291 final int resourceId = mNextResourceId++;
1292 final int ikey = reserveNetId();
1293 final int okey = reserveNetId();
Nathan Harold4fd7c322018-04-26 11:47:14 -07001294 String intfName = String.format("%s%d", INetd.IPSEC_INTERFACE_PREFIX, resourceId);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001295
Benedict Wong0fe58a92018-01-19 17:36:02 -08001296 try {
1297 // Calls to netd:
1298 // Create VTI
1299 // Add inbound/outbound global policies
1300 // (use reqid = 0)
Benedict Wong564e2aa2018-05-07 20:06:44 -07001301 final INetd netd = mSrvConfig.getNetdInstance();
Benedict Wong781dae62018-09-06 11:31:25 -07001302 netd.ipSecAddTunnelInterface(intfName, localAddr, remoteAddr, ikey, okey, resourceId);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001303
Benedict Wong564e2aa2018-05-07 20:06:44 -07001304 for (int selAddrFamily : ADDRESS_FAMILIES) {
1305 // Always send down correct local/remote addresses for template.
1306 netd.ipSecAddSecurityPolicy(
Benedict Wonga0989622018-07-25 13:06:29 -07001307 callerUid,
Benedict Wong564e2aa2018-05-07 20:06:44 -07001308 selAddrFamily,
1309 IpSecManager.DIRECTION_OUT,
1310 localAddr,
1311 remoteAddr,
1312 0,
1313 okey,
Benedict Wong781dae62018-09-06 11:31:25 -07001314 0xffffffff,
1315 resourceId);
Benedict Wong564e2aa2018-05-07 20:06:44 -07001316 netd.ipSecAddSecurityPolicy(
Benedict Wonga0989622018-07-25 13:06:29 -07001317 callerUid,
Benedict Wong564e2aa2018-05-07 20:06:44 -07001318 selAddrFamily,
1319 IpSecManager.DIRECTION_IN,
1320 remoteAddr,
1321 localAddr,
1322 0,
1323 ikey,
Benedict Wong781dae62018-09-06 11:31:25 -07001324 0xffffffff,
1325 resourceId);
Benedict Wong0fe58a92018-01-19 17:36:02 -08001326 }
1327
1328 userRecord.mTunnelInterfaceRecords.put(
1329 resourceId,
1330 new RefcountedResource<TunnelInterfaceRecord>(
1331 new TunnelInterfaceRecord(
1332 resourceId,
1333 intfName,
1334 underlyingNetwork,
1335 localAddr,
1336 remoteAddr,
1337 ikey,
Benedict Wong781dae62018-09-06 11:31:25 -07001338 okey,
1339 resourceId),
Benedict Wong0fe58a92018-01-19 17:36:02 -08001340 binder));
1341 return new IpSecTunnelInterfaceResponse(IpSecManager.Status.OK, resourceId, intfName);
1342 } catch (RemoteException e) {
1343 // Release keys if we got an error.
1344 releaseNetId(ikey);
1345 releaseNetId(okey);
1346 throw e.rethrowFromSystemServer();
Nathan Harold144ce0a2018-04-03 16:13:19 -07001347 } catch (Throwable t) {
1348 // Release keys if we got an error.
1349 releaseNetId(ikey);
1350 releaseNetId(okey);
1351 throw t;
Benedict Wong0fe58a92018-01-19 17:36:02 -08001352 }
Benedict Wong8149f6e2018-01-18 18:31:45 -08001353 }
1354
1355 /**
1356 * Adds a new local address to the tunnel interface. This allows packets to be sent and received
1357 * from multiple local IP addresses over the same tunnel.
1358 */
1359 @Override
Benedict Wongecc9f7c2018-03-01 18:53:07 -08001360 public synchronized void addAddressToTunnelInterface(
Nathan Harold21208ee2018-03-15 18:06:06 -07001361 int tunnelResourceId, LinkAddress localAddr, String callingPackage) {
1362 enforceTunnelPermissions(callingPackage);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001363 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
1364
1365 // Get tunnelInterface record; if no such interface is found, will throw
1366 // IllegalArgumentException
1367 TunnelInterfaceRecord tunnelInterfaceInfo =
1368 userRecord.mTunnelInterfaceRecords.getResourceOrThrow(tunnelResourceId);
1369
Benedict Wongecc9f7c2018-03-01 18:53:07 -08001370 try {
1371 // We can assume general validity of the IP address, since we get them as a
1372 // LinkAddress, which does some validation.
1373 mSrvConfig
1374 .getNetdInstance()
1375 .interfaceAddAddress(
1376 tunnelInterfaceInfo.mInterfaceName,
1377 localAddr.getAddress().getHostAddress(),
1378 localAddr.getPrefixLength());
1379 } catch (RemoteException e) {
1380 throw e.rethrowFromSystemServer();
Benedict Wongecc9f7c2018-03-01 18:53:07 -08001381 }
Benedict Wong8149f6e2018-01-18 18:31:45 -08001382 }
1383
1384 /**
1385 * Remove a new local address from the tunnel interface. After removal, the address will no
1386 * longer be available to send from, or receive on.
1387 */
1388 @Override
1389 public synchronized void removeAddressFromTunnelInterface(
Nathan Harold21208ee2018-03-15 18:06:06 -07001390 int tunnelResourceId, LinkAddress localAddr, String callingPackage) {
1391 enforceTunnelPermissions(callingPackage);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001392
Nathan Harold21208ee2018-03-15 18:06:06 -07001393 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
Benedict Wong8149f6e2018-01-18 18:31:45 -08001394 // Get tunnelInterface record; if no such interface is found, will throw
1395 // IllegalArgumentException
1396 TunnelInterfaceRecord tunnelInterfaceInfo =
1397 userRecord.mTunnelInterfaceRecords.getResourceOrThrow(tunnelResourceId);
1398
Benedict Wongecc9f7c2018-03-01 18:53:07 -08001399 try {
1400 // We can assume general validity of the IP address, since we get them as a
1401 // LinkAddress, which does some validation.
1402 mSrvConfig
1403 .getNetdInstance()
1404 .interfaceDelAddress(
1405 tunnelInterfaceInfo.mInterfaceName,
1406 localAddr.getAddress().getHostAddress(),
1407 localAddr.getPrefixLength());
1408 } catch (RemoteException e) {
1409 throw e.rethrowFromSystemServer();
Benedict Wongecc9f7c2018-03-01 18:53:07 -08001410 }
Benedict Wong8149f6e2018-01-18 18:31:45 -08001411 }
1412
1413 /**
1414 * Delete a TunnelInterface that has been been allocated by and registered with the system
1415 * server
1416 */
1417 @Override
Nathan Harold21208ee2018-03-15 18:06:06 -07001418 public synchronized void deleteTunnelInterface(
1419 int resourceId, String callingPackage) throws RemoteException {
1420 enforceTunnelPermissions(callingPackage);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001421 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
1422 releaseResource(userRecord.mTunnelInterfaceRecords, resourceId);
1423 }
1424
Benedict Wong4f255702017-11-06 20:49:10 -08001425 @VisibleForTesting
Nathan Harolda2523312018-01-05 19:25:13 -08001426 void validateAlgorithms(IpSecConfig config) throws IllegalArgumentException {
1427 IpSecAlgorithm auth = config.getAuthentication();
1428 IpSecAlgorithm crypt = config.getEncryption();
1429 IpSecAlgorithm aead = config.getAuthenticatedEncryption();
Benedict Wong4f255702017-11-06 20:49:10 -08001430
Nathan Harolda2523312018-01-05 19:25:13 -08001431 // Validate the algorithm set
1432 Preconditions.checkArgument(
1433 aead != null || crypt != null || auth != null,
1434 "No Encryption or Authentication algorithms specified");
1435 Preconditions.checkArgument(
1436 auth == null || auth.isAuthentication(),
1437 "Unsupported algorithm for Authentication");
1438 Preconditions.checkArgument(
Benedict Wong4f255702017-11-06 20:49:10 -08001439 crypt == null || crypt.isEncryption(), "Unsupported algorithm for Encryption");
Nathan Harolda2523312018-01-05 19:25:13 -08001440 Preconditions.checkArgument(
1441 aead == null || aead.isAead(),
1442 "Unsupported algorithm for Authenticated Encryption");
1443 Preconditions.checkArgument(
1444 aead == null || (auth == null && crypt == null),
1445 "Authenticated Encryption is mutually exclusive with other Authentication "
1446 + "or Encryption algorithms");
Benedict Wong4f255702017-11-06 20:49:10 -08001447 }
1448
evitayane4259d32018-03-22 17:53:08 -07001449 private int getFamily(String inetAddress) {
1450 int family = AF_UNSPEC;
1451 InetAddress checkAddress = NetworkUtils.numericToInetAddress(inetAddress);
1452 if (checkAddress instanceof Inet4Address) {
1453 family = AF_INET;
1454 } else if (checkAddress instanceof Inet6Address) {
1455 family = AF_INET6;
1456 }
1457 return family;
1458 }
1459
Nathan Harold93962f32017-03-07 13:23:36 -08001460 /**
Nathan Harolda10003d2017-08-23 13:46:33 -07001461 * Checks an IpSecConfig parcel to ensure that the contents are sane and throws an
1462 * IllegalArgumentException if they are not.
1463 */
1464 private void checkIpSecConfig(IpSecConfig config) {
Benedict Wong344bd622017-11-16 15:27:22 -08001465 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
1466
Nathan Harolda10003d2017-08-23 13:46:33 -07001467 switch (config.getEncapType()) {
1468 case IpSecTransform.ENCAP_NONE:
1469 break;
1470 case IpSecTransform.ENCAP_ESPINUDP:
1471 case IpSecTransform.ENCAP_ESPINUDP_NON_IKE:
Benedict Wong344bd622017-11-16 15:27:22 -08001472 // Retrieve encap socket record; will throw IllegalArgumentException if not found
1473 userRecord.mEncapSocketRecords.getResourceOrThrow(
1474 config.getEncapSocketResourceId());
Nathan Harolda10003d2017-08-23 13:46:33 -07001475
1476 int port = config.getEncapRemotePort();
1477 if (port <= 0 || port > 0xFFFF) {
1478 throw new IllegalArgumentException("Invalid remote UDP port: " + port);
1479 }
1480 break;
1481 default:
1482 throw new IllegalArgumentException("Invalid Encap Type: " + config.getEncapType());
1483 }
1484
Nathan Harolda2523312018-01-05 19:25:13 -08001485 validateAlgorithms(config);
Nathan Harolda10003d2017-08-23 13:46:33 -07001486
Nathan Harolda2523312018-01-05 19:25:13 -08001487 // Retrieve SPI record; will throw IllegalArgumentException if not found
1488 SpiRecord s = userRecord.mSpiRecords.getResourceOrThrow(config.getSpiResourceId());
1489
Benedict Wonge6b42772017-12-13 18:26:40 -08001490 // Check to ensure that SPI has not already been used.
1491 if (s.getOwnedByTransform()) {
1492 throw new IllegalStateException("SPI already in use; cannot be used in new Transforms");
1493 }
1494
Nathan Harolda2523312018-01-05 19:25:13 -08001495 // If no remote address is supplied, then use one from the SPI.
1496 if (TextUtils.isEmpty(config.getDestinationAddress())) {
1497 config.setDestinationAddress(s.getDestinationAddress());
1498 }
1499
1500 // All remote addresses must match
1501 if (!config.getDestinationAddress().equals(s.getDestinationAddress())) {
1502 throw new IllegalArgumentException("Mismatched remote addresseses.");
1503 }
1504
1505 // This check is technically redundant due to the chain of custody between the SPI and
1506 // the IpSecConfig, but in the future if the dest is allowed to be set explicitly in
1507 // the transform, this will prevent us from messing up.
1508 checkInetAddress(config.getDestinationAddress());
1509
1510 // Require a valid source address for all transforms.
1511 checkInetAddress(config.getSourceAddress());
1512
evitayane4259d32018-03-22 17:53:08 -07001513 // Check to ensure source and destination have the same address family.
1514 String sourceAddress = config.getSourceAddress();
1515 String destinationAddress = config.getDestinationAddress();
1516 int sourceFamily = getFamily(sourceAddress);
1517 int destinationFamily = getFamily(destinationAddress);
1518 if (sourceFamily != destinationFamily) {
1519 throw new IllegalArgumentException(
1520 "Source address ("
1521 + sourceAddress
1522 + ") and destination address ("
1523 + destinationAddress
1524 + ") have different address families.");
1525 }
1526
1527 // Throw an error if UDP Encapsulation is not used in IPv4.
1528 if (config.getEncapType() != IpSecTransform.ENCAP_NONE && sourceFamily != AF_INET) {
1529 throw new IllegalArgumentException(
1530 "UDP Encapsulation is not supported for this address family");
1531 }
1532
Nathan Harolda2523312018-01-05 19:25:13 -08001533 switch (config.getMode()) {
1534 case IpSecTransform.MODE_TRANSPORT:
Nathan Harold5a920ca2018-02-02 18:34:25 -08001535 break;
Nathan Harolda2523312018-01-05 19:25:13 -08001536 case IpSecTransform.MODE_TUNNEL:
1537 break;
1538 default:
1539 throw new IllegalArgumentException(
1540 "Invalid IpSecTransform.mode: " + config.getMode());
Nathan Harolda10003d2017-08-23 13:46:33 -07001541 }
Benedict Wongab80e1f2018-07-25 18:46:19 -07001542
1543 config.setMarkValue(0);
1544 config.setMarkMask(0);
Nathan Harolda10003d2017-08-23 13:46:33 -07001545 }
1546
Benedict Wongd8db9182018-09-13 16:45:12 -07001547 private static final String TUNNEL_OP = AppOpsManager.OPSTR_MANAGE_IPSEC_TUNNELS;
Nathan Harold8c69bcb2018-05-15 19:18:38 -07001548
Nathan Harold21208ee2018-03-15 18:06:06 -07001549 private void enforceTunnelPermissions(String callingPackage) {
1550 checkNotNull(callingPackage, "Null calling package cannot create IpSec tunnels");
Benedict Wongd8db9182018-09-13 16:45:12 -07001551 switch (getAppOpsManager().noteOp(TUNNEL_OP, Binder.getCallingUid(), callingPackage)) {
1552 case AppOpsManager.MODE_DEFAULT:
1553 mContext.enforceCallingOrSelfPermission(
1554 android.Manifest.permission.MANAGE_IPSEC_TUNNELS, "IpSecService");
1555 break;
1556 case AppOpsManager.MODE_ALLOWED:
1557 return;
1558 default:
1559 throw new SecurityException("Request to ignore AppOps for non-legacy API");
Nathan Harold21208ee2018-03-15 18:06:06 -07001560 }
Nathan Harold5a920ca2018-02-02 18:34:25 -08001561 }
1562
Benedict Wong0fe58a92018-01-19 17:36:02 -08001563 private void createOrUpdateTransform(
1564 IpSecConfig c, int resourceId, SpiRecord spiRecord, EncapSocketRecord socketRecord)
1565 throws RemoteException {
1566
1567 int encapType = c.getEncapType(), encapLocalPort = 0, encapRemotePort = 0;
1568 if (encapType != IpSecTransform.ENCAP_NONE) {
1569 encapLocalPort = socketRecord.getPort();
1570 encapRemotePort = c.getEncapRemotePort();
1571 }
1572
1573 IpSecAlgorithm auth = c.getAuthentication();
1574 IpSecAlgorithm crypt = c.getEncryption();
1575 IpSecAlgorithm authCrypt = c.getAuthenticatedEncryption();
1576
Benedict Wongbf013a32018-03-15 19:41:41 -07001577 String cryptName;
1578 if (crypt == null) {
1579 cryptName = (authCrypt == null) ? IpSecAlgorithm.CRYPT_NULL : "";
1580 } else {
1581 cryptName = crypt.getName();
1582 }
1583
Benedict Wong0fe58a92018-01-19 17:36:02 -08001584 mSrvConfig
1585 .getNetdInstance()
1586 .ipSecAddSecurityAssociation(
Benedict Wonga0989622018-07-25 13:06:29 -07001587 Binder.getCallingUid(),
Benedict Wong0fe58a92018-01-19 17:36:02 -08001588 c.getMode(),
1589 c.getSourceAddress(),
1590 c.getDestinationAddress(),
1591 (c.getNetwork() != null) ? c.getNetwork().netId : 0,
1592 spiRecord.getSpi(),
1593 c.getMarkValue(),
1594 c.getMarkMask(),
1595 (auth != null) ? auth.getName() : "",
1596 (auth != null) ? auth.getKey() : new byte[] {},
1597 (auth != null) ? auth.getTruncationLengthBits() : 0,
Benedict Wongbf013a32018-03-15 19:41:41 -07001598 cryptName,
Benedict Wong0fe58a92018-01-19 17:36:02 -08001599 (crypt != null) ? crypt.getKey() : new byte[] {},
1600 (crypt != null) ? crypt.getTruncationLengthBits() : 0,
1601 (authCrypt != null) ? authCrypt.getName() : "",
1602 (authCrypt != null) ? authCrypt.getKey() : new byte[] {},
1603 (authCrypt != null) ? authCrypt.getTruncationLengthBits() : 0,
1604 encapType,
1605 encapLocalPort,
Benedict Wong781dae62018-09-06 11:31:25 -07001606 encapRemotePort,
1607 c.getXfrmInterfaceId());
Benedict Wong0fe58a92018-01-19 17:36:02 -08001608 }
1609
Nathan Harolda10003d2017-08-23 13:46:33 -07001610 /**
Benedict Wong0fe58a92018-01-19 17:36:02 -08001611 * Create a IPsec transform, which represents a single security association in the kernel. The
1612 * transform will be cached by the system server and must be freed when no longer needed. It is
1613 * possible to free one, deleting the SA from underneath sockets that are using it, which will
1614 * result in all of those sockets becoming unable to send or receive data.
Nathan Harold93962f32017-03-07 13:23:36 -08001615 */
1616 @Override
Nathan Harold21208ee2018-03-15 18:06:06 -07001617 public synchronized IpSecTransformResponse createTransform(
1618 IpSecConfig c, IBinder binder, String callingPackage) throws RemoteException {
1619 checkNotNull(c);
1620 if (c.getMode() == IpSecTransform.MODE_TUNNEL) {
1621 enforceTunnelPermissions(callingPackage);
1622 }
Nathan Harolda10003d2017-08-23 13:46:33 -07001623 checkIpSecConfig(c);
Benedict Wongf33f03132018-01-18 14:38:16 -08001624 checkNotNull(binder, "Null Binder passed to createTransform");
Nathan Haroldd8c74292017-12-13 19:16:33 -08001625 final int resourceId = mNextResourceId++;
Benedict Wong344bd622017-11-16 15:27:22 -08001626
1627 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
Benedict Wong4f9fb812017-12-13 17:16:53 -08001628 List<RefcountedResource> dependencies = new ArrayList<>();
Benedict Wong344bd622017-11-16 15:27:22 -08001629
1630 if (!userRecord.mTransformQuotaTracker.isAvailable()) {
Nathan Harolda1afbd82017-04-24 16:16:34 -07001631 return new IpSecTransformResponse(IpSecManager.Status.RESOURCE_UNAVAILABLE);
1632 }
Nathan Harolda10003d2017-08-23 13:46:33 -07001633
Benedict Wong344bd622017-11-16 15:27:22 -08001634 EncapSocketRecord socketRecord = null;
Benedict Wong0fe58a92018-01-19 17:36:02 -08001635 if (c.getEncapType() != IpSecTransform.ENCAP_NONE) {
Benedict Wong344bd622017-11-16 15:27:22 -08001636 RefcountedResource<EncapSocketRecord> refcountedSocketRecord =
1637 userRecord.mEncapSocketRecords.getRefcountedResourceOrThrow(
1638 c.getEncapSocketResourceId());
1639 dependencies.add(refcountedSocketRecord);
Benedict Wong344bd622017-11-16 15:27:22 -08001640 socketRecord = refcountedSocketRecord.getResource();
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001641 }
1642
Nathan Harolda2523312018-01-05 19:25:13 -08001643 RefcountedResource<SpiRecord> refcountedSpiRecord =
1644 userRecord.mSpiRecords.getRefcountedResourceOrThrow(c.getSpiResourceId());
1645 dependencies.add(refcountedSpiRecord);
1646 SpiRecord spiRecord = refcountedSpiRecord.getResource();
Benedict Wong344bd622017-11-16 15:27:22 -08001647
Nathan Harold144ce0a2018-04-03 16:13:19 -07001648 createOrUpdateTransform(c, resourceId, spiRecord, socketRecord);
Benedict Wong0fe58a92018-01-19 17:36:02 -08001649
1650 // SA was created successfully, time to construct a record and lock it away
Benedict Wong344bd622017-11-16 15:27:22 -08001651 userRecord.mTransformRecords.put(
1652 resourceId,
1653 new RefcountedResource<TransformRecord>(
Nathan Harolda2523312018-01-05 19:25:13 -08001654 new TransformRecord(resourceId, c, spiRecord, socketRecord),
Benedict Wong344bd622017-11-16 15:27:22 -08001655 binder,
1656 dependencies.toArray(new RefcountedResource[dependencies.size()])));
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001657 return new IpSecTransformResponse(IpSecManager.Status.OK, resourceId);
Nathan Harold93962f32017-03-07 13:23:36 -08001658 }
1659
1660 /**
1661 * Delete a transport mode transform that was previously allocated by + registered with the
1662 * system server. If this is called on an inactive (or non-existent) transform, it will not
1663 * return an error. It's safe to de-allocate transforms that may have already been deleted for
1664 * other reasons.
1665 */
1666 @Override
Benedict Wongf33f03132018-01-18 14:38:16 -08001667 public synchronized void deleteTransform(int resourceId) throws RemoteException {
Benedict Wong344bd622017-11-16 15:27:22 -08001668 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
1669 releaseResource(userRecord.mTransformRecords, resourceId);
Nathan Harold93962f32017-03-07 13:23:36 -08001670 }
1671
1672 /**
1673 * Apply an active transport mode transform to a socket, which will apply the IPsec security
1674 * association as a correspondent policy to the provided socket
1675 */
1676 @Override
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001677 public synchronized void applyTransportModeTransform(
Nathan Harolda2523312018-01-05 19:25:13 -08001678 ParcelFileDescriptor socket, int direction, int resourceId) throws RemoteException {
Benedict Wonga0989622018-07-25 13:06:29 -07001679 int callingUid = Binder.getCallingUid();
1680 UserRecord userRecord = mUserResourceTracker.getUserRecord(callingUid);
Nathan Harolda2523312018-01-05 19:25:13 -08001681 checkDirection(direction);
Benedict Wong344bd622017-11-16 15:27:22 -08001682 // Get transform record; if no transform is found, will throw IllegalArgumentException
1683 TransformRecord info = userRecord.mTransformRecords.getResourceOrThrow(resourceId);
Nathan Harold93962f32017-03-07 13:23:36 -08001684
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001685 // TODO: make this a function.
Benedict Wonga0989622018-07-25 13:06:29 -07001686 if (info.pid != getCallingPid() || info.uid != callingUid) {
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001687 throw new SecurityException("Only the owner of an IpSec Transform may apply it!");
1688 }
1689
Benedict Wong8149f6e2018-01-18 18:31:45 -08001690 // Get config and check that to-be-applied transform has the correct mode
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001691 IpSecConfig c = info.getConfig();
Benedict Wong8149f6e2018-01-18 18:31:45 -08001692 Preconditions.checkArgument(
1693 c.getMode() == IpSecTransform.MODE_TRANSPORT,
1694 "Transform mode was not Transport mode; cannot be applied to a socket");
1695
Nathan Harold144ce0a2018-04-03 16:13:19 -07001696 mSrvConfig
1697 .getNetdInstance()
1698 .ipSecApplyTransportModeTransform(
1699 socket.getFileDescriptor(),
Benedict Wonga0989622018-07-25 13:06:29 -07001700 callingUid,
Nathan Harold144ce0a2018-04-03 16:13:19 -07001701 direction,
1702 c.getSourceAddress(),
1703 c.getDestinationAddress(),
1704 info.getSpiRecord().getSpi());
Nathan Harold93962f32017-03-07 13:23:36 -08001705 }
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001706
Nathan Harold93962f32017-03-07 13:23:36 -08001707 /**
Nathan Harolda2523312018-01-05 19:25:13 -08001708 * Remove transport mode transforms from a socket, applying the default (empty) policy. This
1709 * ensures that NO IPsec policy is applied to the socket (would be the equivalent of applying a
1710 * policy that performs no IPsec). Today the resourceId parameter is passed but not used:
1711 * reserved for future improved input validation.
Nathan Harold93962f32017-03-07 13:23:36 -08001712 */
1713 @Override
Nathan Haroldf73d2522018-01-17 01:00:20 -08001714 public synchronized void removeTransportModeTransforms(ParcelFileDescriptor socket)
1715 throws RemoteException {
Nathan Harold144ce0a2018-04-03 16:13:19 -07001716 mSrvConfig
1717 .getNetdInstance()
1718 .ipSecRemoveTransportModeTransform(socket.getFileDescriptor());
Nathan Harold93962f32017-03-07 13:23:36 -08001719 }
1720
Benedict Wong8149f6e2018-01-18 18:31:45 -08001721 /**
1722 * Apply an active tunnel mode transform to a TunnelInterface, which will apply the IPsec
1723 * security association as a correspondent policy to the provided interface
1724 */
1725 @Override
1726 public synchronized void applyTunnelModeTransform(
Nathan Harold21208ee2018-03-15 18:06:06 -07001727 int tunnelResourceId, int direction,
1728 int transformResourceId, String callingPackage) throws RemoteException {
1729 enforceTunnelPermissions(callingPackage);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001730 checkDirection(direction);
1731
Benedict Wonga0989622018-07-25 13:06:29 -07001732 int callingUid = Binder.getCallingUid();
1733 UserRecord userRecord = mUserResourceTracker.getUserRecord(callingUid);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001734
1735 // Get transform record; if no transform is found, will throw IllegalArgumentException
1736 TransformRecord transformInfo =
1737 userRecord.mTransformRecords.getResourceOrThrow(transformResourceId);
1738
1739 // Get tunnelInterface record; if no such interface is found, will throw
1740 // IllegalArgumentException
1741 TunnelInterfaceRecord tunnelInterfaceInfo =
1742 userRecord.mTunnelInterfaceRecords.getResourceOrThrow(tunnelResourceId);
1743
1744 // Get config and check that to-be-applied transform has the correct mode
1745 IpSecConfig c = transformInfo.getConfig();
1746 Preconditions.checkArgument(
1747 c.getMode() == IpSecTransform.MODE_TUNNEL,
1748 "Transform mode was not Tunnel mode; cannot be applied to a tunnel interface");
1749
Benedict Wong0fe58a92018-01-19 17:36:02 -08001750 EncapSocketRecord socketRecord = null;
1751 if (c.getEncapType() != IpSecTransform.ENCAP_NONE) {
1752 socketRecord =
1753 userRecord.mEncapSocketRecords.getResourceOrThrow(c.getEncapSocketResourceId());
1754 }
1755 SpiRecord spiRecord = userRecord.mSpiRecords.getResourceOrThrow(c.getSpiResourceId());
1756
Benedict Wong8149f6e2018-01-18 18:31:45 -08001757 int mark =
Benedict Wong564e2aa2018-05-07 20:06:44 -07001758 (direction == IpSecManager.DIRECTION_OUT)
1759 ? tunnelInterfaceInfo.getOkey()
1760 : tunnelInterfaceInfo.getIkey();
Benedict Wong8149f6e2018-01-18 18:31:45 -08001761
Benedict Wong0fe58a92018-01-19 17:36:02 -08001762 try {
Benedict Wong781dae62018-09-06 11:31:25 -07001763 // Default to using the invalid SPI of 0 for inbound SAs. This allows policies to skip
1764 // SPI matching as part of the template resolution.
1765 int spi = IpSecManager.INVALID_SECURITY_PARAMETER_INDEX;
1766 c.setXfrmInterfaceId(tunnelInterfaceInfo.getIfId());
1767
Benedict Wongab80e1f2018-07-25 18:46:19 -07001768 // TODO: enable this when UPDSA supports updating marks. Adding kernel support upstream
1769 // (and backporting) would allow us to narrow the mark space, and ensure that the SA
1770 // and SPs have matching marks (as VTI are meant to be built).
1771 // Currently update does nothing with marks. Leave empty (defaulting to 0) to ensure the
1772 // config matches the actual allocated resources in the kernel.
1773 //
1774 // c.setMarkValue(mark);
1775 // c.setMarkMask(0xffffffff);
Benedict Wong0fe58a92018-01-19 17:36:02 -08001776
1777 if (direction == IpSecManager.DIRECTION_OUT) {
1778 // Set output mark via underlying network (output only)
1779 c.setNetwork(tunnelInterfaceInfo.getUnderlyingNetwork());
1780
Benedict Wong781dae62018-09-06 11:31:25 -07001781 // Set outbound SPI only. We want inbound to use any valid SA (old, new) on rekeys,
1782 // but want to guarantee outbound packets are sent over the new SA.
1783 spi = transformInfo.getSpiRecord().getSpi();
1784 }
1785
1786 // Always update the policy with the relevant XFRM_IF_ID
1787 for (int selAddrFamily : ADDRESS_FAMILIES) {
1788 mSrvConfig
1789 .getNetdInstance()
1790 .ipSecUpdateSecurityPolicy(
1791 callingUid,
1792 selAddrFamily,
1793 direction,
1794 transformInfo.getConfig().getSourceAddress(),
1795 transformInfo.getConfig().getDestinationAddress(),
1796 spi, // If outbound, also add SPI to the policy.
1797 mark, // Must always set policy mark; ikey/okey for VTIs
1798 0xffffffff,
1799 c.getXfrmInterfaceId());
Benedict Wong0fe58a92018-01-19 17:36:02 -08001800 }
1801
1802 // Update SA with tunnel mark (ikey or okey based on direction)
1803 createOrUpdateTransform(c, transformResourceId, spiRecord, socketRecord);
1804 } catch (ServiceSpecificException e) {
1805 if (e.errorCode == EINVAL) {
1806 throw new IllegalArgumentException(e.toString());
1807 } else {
1808 throw e;
1809 }
1810 }
Benedict Wong8149f6e2018-01-18 18:31:45 -08001811 }
1812
Nathan Harold93962f32017-03-07 13:23:36 -08001813 @Override
ludib0c95b12017-05-22 10:52:23 -07001814 protected synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Nathan Harold1afbef42017-03-01 18:55:06 -08001815 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
ludib0c95b12017-05-22 10:52:23 -07001816
1817 pw.println("IpSecService dump:");
Nathan Harold1afbef42017-03-01 18:55:06 -08001818 pw.println("NetdNativeService Connection: " + (isNetdAlive() ? "alive" : "dead"));
1819 pw.println();
ludib0c95b12017-05-22 10:52:23 -07001820
Benedict Wong344bd622017-11-16 15:27:22 -08001821 pw.println("mUserResourceTracker:");
1822 pw.println(mUserResourceTracker);
Nathan Harold1afbef42017-03-01 18:55:06 -08001823 }
1824}