blob: 126bf6556538edf75ff857add96da69cc1893499 [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;
Remi NGUYEN VAN231b52b2019-01-29 15:38:52 +090047import 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
Luke Huange8e522b2018-11-23 12:01:41 +08001239 mSrvConfig.getNetdInstance().ipSecSetEncapSocketOwner(
1240 new ParcelFileDescriptor(sockFd), callingUid);
Benedict Wongba8d3132017-12-06 21:56:35 -08001241 if (port != 0) {
1242 Log.v(TAG, "Binding to port " + port);
1243 Os.bind(sockFd, INADDR_ANY, port);
1244 } else {
1245 port = bindToRandomPort(sockFd);
1246 }
1247
Benedict Wong344bd622017-11-16 15:27:22 -08001248 userRecord.mEncapSocketRecords.put(
1249 resourceId,
1250 new RefcountedResource<EncapSocketRecord>(
1251 new EncapSocketRecord(resourceId, sockFd, port), binder));
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001252 return new IpSecUdpEncapResponse(IpSecManager.Status.OK, resourceId, port, sockFd);
1253 } catch (IOException | ErrnoException e) {
1254 IoUtils.closeQuietly(sockFd);
1255 }
1256 // If we make it to here, then something has gone wrong and we couldn't open a socket.
1257 // The only reasonable condition that would cause that is resource unavailable.
1258 return new IpSecUdpEncapResponse(IpSecManager.Status.RESOURCE_UNAVAILABLE);
Nathan Harold93962f32017-03-07 13:23:36 -08001259 }
1260
1261 /** close a socket that has been been allocated by and registered with the system server */
1262 @Override
Benedict Wong344bd622017-11-16 15:27:22 -08001263 public synchronized void closeUdpEncapsulationSocket(int resourceId) throws RemoteException {
1264 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
1265 releaseResource(userRecord.mEncapSocketRecords, resourceId);
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001266 }
Nathan Harold93962f32017-03-07 13:23:36 -08001267
Benedict Wong8149f6e2018-01-18 18:31:45 -08001268 /**
1269 * Create a tunnel interface for use in IPSec tunnel mode. The system server will cache the
1270 * tunnel interface and a record of its owner so that it can and must be freed when no longer
1271 * needed.
1272 */
1273 @Override
1274 public synchronized IpSecTunnelInterfaceResponse createTunnelInterface(
Nathan Harold21208ee2018-03-15 18:06:06 -07001275 String localAddr, String remoteAddr, Network underlyingNetwork, IBinder binder,
1276 String callingPackage) {
1277 enforceTunnelPermissions(callingPackage);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001278 checkNotNull(binder, "Null Binder passed to createTunnelInterface");
1279 checkNotNull(underlyingNetwork, "No underlying network was specified");
1280 checkInetAddress(localAddr);
1281 checkInetAddress(remoteAddr);
1282
1283 // TODO: Check that underlying network exists, and IP addresses not assigned to a different
1284 // network (b/72316676).
1285
Benedict Wonga0989622018-07-25 13:06:29 -07001286 int callerUid = Binder.getCallingUid();
1287 UserRecord userRecord = mUserResourceTracker.getUserRecord(callerUid);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001288 if (!userRecord.mTunnelQuotaTracker.isAvailable()) {
1289 return new IpSecTunnelInterfaceResponse(IpSecManager.Status.RESOURCE_UNAVAILABLE);
1290 }
1291
1292 final int resourceId = mNextResourceId++;
1293 final int ikey = reserveNetId();
1294 final int okey = reserveNetId();
Nathan Harold4fd7c322018-04-26 11:47:14 -07001295 String intfName = String.format("%s%d", INetd.IPSEC_INTERFACE_PREFIX, resourceId);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001296
Benedict Wong0fe58a92018-01-19 17:36:02 -08001297 try {
1298 // Calls to netd:
1299 // Create VTI
1300 // Add inbound/outbound global policies
1301 // (use reqid = 0)
Benedict Wong564e2aa2018-05-07 20:06:44 -07001302 final INetd netd = mSrvConfig.getNetdInstance();
Benedict Wong781dae62018-09-06 11:31:25 -07001303 netd.ipSecAddTunnelInterface(intfName, localAddr, remoteAddr, ikey, okey, resourceId);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001304
Benedict Wong564e2aa2018-05-07 20:06:44 -07001305 for (int selAddrFamily : ADDRESS_FAMILIES) {
1306 // Always send down correct local/remote addresses for template.
1307 netd.ipSecAddSecurityPolicy(
Benedict Wonga0989622018-07-25 13:06:29 -07001308 callerUid,
Benedict Wong564e2aa2018-05-07 20:06:44 -07001309 selAddrFamily,
1310 IpSecManager.DIRECTION_OUT,
1311 localAddr,
1312 remoteAddr,
1313 0,
1314 okey,
Benedict Wong781dae62018-09-06 11:31:25 -07001315 0xffffffff,
1316 resourceId);
Benedict Wong564e2aa2018-05-07 20:06:44 -07001317 netd.ipSecAddSecurityPolicy(
Benedict Wonga0989622018-07-25 13:06:29 -07001318 callerUid,
Benedict Wong564e2aa2018-05-07 20:06:44 -07001319 selAddrFamily,
1320 IpSecManager.DIRECTION_IN,
1321 remoteAddr,
1322 localAddr,
1323 0,
1324 ikey,
Benedict Wong781dae62018-09-06 11:31:25 -07001325 0xffffffff,
1326 resourceId);
Benedict Wong0fe58a92018-01-19 17:36:02 -08001327 }
1328
1329 userRecord.mTunnelInterfaceRecords.put(
1330 resourceId,
1331 new RefcountedResource<TunnelInterfaceRecord>(
1332 new TunnelInterfaceRecord(
1333 resourceId,
1334 intfName,
1335 underlyingNetwork,
1336 localAddr,
1337 remoteAddr,
1338 ikey,
Benedict Wong781dae62018-09-06 11:31:25 -07001339 okey,
1340 resourceId),
Benedict Wong0fe58a92018-01-19 17:36:02 -08001341 binder));
1342 return new IpSecTunnelInterfaceResponse(IpSecManager.Status.OK, resourceId, intfName);
1343 } catch (RemoteException e) {
1344 // Release keys if we got an error.
1345 releaseNetId(ikey);
1346 releaseNetId(okey);
1347 throw e.rethrowFromSystemServer();
Nathan Harold144ce0a2018-04-03 16:13:19 -07001348 } catch (Throwable t) {
1349 // Release keys if we got an error.
1350 releaseNetId(ikey);
1351 releaseNetId(okey);
1352 throw t;
Benedict Wong0fe58a92018-01-19 17:36:02 -08001353 }
Benedict Wong8149f6e2018-01-18 18:31:45 -08001354 }
1355
1356 /**
1357 * Adds a new local address to the tunnel interface. This allows packets to be sent and received
1358 * from multiple local IP addresses over the same tunnel.
1359 */
1360 @Override
Benedict Wongecc9f7c2018-03-01 18:53:07 -08001361 public synchronized void addAddressToTunnelInterface(
Nathan Harold21208ee2018-03-15 18:06:06 -07001362 int tunnelResourceId, LinkAddress localAddr, String callingPackage) {
1363 enforceTunnelPermissions(callingPackage);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001364 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
1365
1366 // Get tunnelInterface record; if no such interface is found, will throw
1367 // IllegalArgumentException
1368 TunnelInterfaceRecord tunnelInterfaceInfo =
1369 userRecord.mTunnelInterfaceRecords.getResourceOrThrow(tunnelResourceId);
1370
Benedict Wongecc9f7c2018-03-01 18:53:07 -08001371 try {
1372 // We can assume general validity of the IP address, since we get them as a
1373 // LinkAddress, which does some validation.
1374 mSrvConfig
1375 .getNetdInstance()
1376 .interfaceAddAddress(
1377 tunnelInterfaceInfo.mInterfaceName,
1378 localAddr.getAddress().getHostAddress(),
1379 localAddr.getPrefixLength());
1380 } catch (RemoteException e) {
1381 throw e.rethrowFromSystemServer();
Benedict Wongecc9f7c2018-03-01 18:53:07 -08001382 }
Benedict Wong8149f6e2018-01-18 18:31:45 -08001383 }
1384
1385 /**
1386 * Remove a new local address from the tunnel interface. After removal, the address will no
1387 * longer be available to send from, or receive on.
1388 */
1389 @Override
1390 public synchronized void removeAddressFromTunnelInterface(
Nathan Harold21208ee2018-03-15 18:06:06 -07001391 int tunnelResourceId, LinkAddress localAddr, String callingPackage) {
1392 enforceTunnelPermissions(callingPackage);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001393
Nathan Harold21208ee2018-03-15 18:06:06 -07001394 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
Benedict Wong8149f6e2018-01-18 18:31:45 -08001395 // Get tunnelInterface record; if no such interface is found, will throw
1396 // IllegalArgumentException
1397 TunnelInterfaceRecord tunnelInterfaceInfo =
1398 userRecord.mTunnelInterfaceRecords.getResourceOrThrow(tunnelResourceId);
1399
Benedict Wongecc9f7c2018-03-01 18:53:07 -08001400 try {
1401 // We can assume general validity of the IP address, since we get them as a
1402 // LinkAddress, which does some validation.
1403 mSrvConfig
1404 .getNetdInstance()
1405 .interfaceDelAddress(
1406 tunnelInterfaceInfo.mInterfaceName,
1407 localAddr.getAddress().getHostAddress(),
1408 localAddr.getPrefixLength());
1409 } catch (RemoteException e) {
1410 throw e.rethrowFromSystemServer();
Benedict Wongecc9f7c2018-03-01 18:53:07 -08001411 }
Benedict Wong8149f6e2018-01-18 18:31:45 -08001412 }
1413
1414 /**
1415 * Delete a TunnelInterface that has been been allocated by and registered with the system
1416 * server
1417 */
1418 @Override
Nathan Harold21208ee2018-03-15 18:06:06 -07001419 public synchronized void deleteTunnelInterface(
1420 int resourceId, String callingPackage) throws RemoteException {
1421 enforceTunnelPermissions(callingPackage);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001422 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
1423 releaseResource(userRecord.mTunnelInterfaceRecords, resourceId);
1424 }
1425
Benedict Wong4f255702017-11-06 20:49:10 -08001426 @VisibleForTesting
Nathan Harolda2523312018-01-05 19:25:13 -08001427 void validateAlgorithms(IpSecConfig config) throws IllegalArgumentException {
1428 IpSecAlgorithm auth = config.getAuthentication();
1429 IpSecAlgorithm crypt = config.getEncryption();
1430 IpSecAlgorithm aead = config.getAuthenticatedEncryption();
Benedict Wong4f255702017-11-06 20:49:10 -08001431
Nathan Harolda2523312018-01-05 19:25:13 -08001432 // Validate the algorithm set
1433 Preconditions.checkArgument(
1434 aead != null || crypt != null || auth != null,
1435 "No Encryption or Authentication algorithms specified");
1436 Preconditions.checkArgument(
1437 auth == null || auth.isAuthentication(),
1438 "Unsupported algorithm for Authentication");
1439 Preconditions.checkArgument(
Benedict Wong4f255702017-11-06 20:49:10 -08001440 crypt == null || crypt.isEncryption(), "Unsupported algorithm for Encryption");
Nathan Harolda2523312018-01-05 19:25:13 -08001441 Preconditions.checkArgument(
1442 aead == null || aead.isAead(),
1443 "Unsupported algorithm for Authenticated Encryption");
1444 Preconditions.checkArgument(
1445 aead == null || (auth == null && crypt == null),
1446 "Authenticated Encryption is mutually exclusive with other Authentication "
1447 + "or Encryption algorithms");
Benedict Wong4f255702017-11-06 20:49:10 -08001448 }
1449
evitayane4259d32018-03-22 17:53:08 -07001450 private int getFamily(String inetAddress) {
1451 int family = AF_UNSPEC;
1452 InetAddress checkAddress = NetworkUtils.numericToInetAddress(inetAddress);
1453 if (checkAddress instanceof Inet4Address) {
1454 family = AF_INET;
1455 } else if (checkAddress instanceof Inet6Address) {
1456 family = AF_INET6;
1457 }
1458 return family;
1459 }
1460
Nathan Harold93962f32017-03-07 13:23:36 -08001461 /**
Nathan Harolda10003d2017-08-23 13:46:33 -07001462 * Checks an IpSecConfig parcel to ensure that the contents are sane and throws an
1463 * IllegalArgumentException if they are not.
1464 */
1465 private void checkIpSecConfig(IpSecConfig config) {
Benedict Wong344bd622017-11-16 15:27:22 -08001466 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
1467
Nathan Harolda10003d2017-08-23 13:46:33 -07001468 switch (config.getEncapType()) {
1469 case IpSecTransform.ENCAP_NONE:
1470 break;
1471 case IpSecTransform.ENCAP_ESPINUDP:
1472 case IpSecTransform.ENCAP_ESPINUDP_NON_IKE:
Benedict Wong344bd622017-11-16 15:27:22 -08001473 // Retrieve encap socket record; will throw IllegalArgumentException if not found
1474 userRecord.mEncapSocketRecords.getResourceOrThrow(
1475 config.getEncapSocketResourceId());
Nathan Harolda10003d2017-08-23 13:46:33 -07001476
1477 int port = config.getEncapRemotePort();
1478 if (port <= 0 || port > 0xFFFF) {
1479 throw new IllegalArgumentException("Invalid remote UDP port: " + port);
1480 }
1481 break;
1482 default:
1483 throw new IllegalArgumentException("Invalid Encap Type: " + config.getEncapType());
1484 }
1485
Nathan Harolda2523312018-01-05 19:25:13 -08001486 validateAlgorithms(config);
Nathan Harolda10003d2017-08-23 13:46:33 -07001487
Nathan Harolda2523312018-01-05 19:25:13 -08001488 // Retrieve SPI record; will throw IllegalArgumentException if not found
1489 SpiRecord s = userRecord.mSpiRecords.getResourceOrThrow(config.getSpiResourceId());
1490
Benedict Wonge6b42772017-12-13 18:26:40 -08001491 // Check to ensure that SPI has not already been used.
1492 if (s.getOwnedByTransform()) {
1493 throw new IllegalStateException("SPI already in use; cannot be used in new Transforms");
1494 }
1495
Nathan Harolda2523312018-01-05 19:25:13 -08001496 // If no remote address is supplied, then use one from the SPI.
1497 if (TextUtils.isEmpty(config.getDestinationAddress())) {
1498 config.setDestinationAddress(s.getDestinationAddress());
1499 }
1500
1501 // All remote addresses must match
1502 if (!config.getDestinationAddress().equals(s.getDestinationAddress())) {
1503 throw new IllegalArgumentException("Mismatched remote addresseses.");
1504 }
1505
1506 // This check is technically redundant due to the chain of custody between the SPI and
1507 // the IpSecConfig, but in the future if the dest is allowed to be set explicitly in
1508 // the transform, this will prevent us from messing up.
1509 checkInetAddress(config.getDestinationAddress());
1510
1511 // Require a valid source address for all transforms.
1512 checkInetAddress(config.getSourceAddress());
1513
evitayane4259d32018-03-22 17:53:08 -07001514 // Check to ensure source and destination have the same address family.
1515 String sourceAddress = config.getSourceAddress();
1516 String destinationAddress = config.getDestinationAddress();
1517 int sourceFamily = getFamily(sourceAddress);
1518 int destinationFamily = getFamily(destinationAddress);
1519 if (sourceFamily != destinationFamily) {
1520 throw new IllegalArgumentException(
1521 "Source address ("
1522 + sourceAddress
1523 + ") and destination address ("
1524 + destinationAddress
1525 + ") have different address families.");
1526 }
1527
1528 // Throw an error if UDP Encapsulation is not used in IPv4.
1529 if (config.getEncapType() != IpSecTransform.ENCAP_NONE && sourceFamily != AF_INET) {
1530 throw new IllegalArgumentException(
1531 "UDP Encapsulation is not supported for this address family");
1532 }
1533
Nathan Harolda2523312018-01-05 19:25:13 -08001534 switch (config.getMode()) {
1535 case IpSecTransform.MODE_TRANSPORT:
Nathan Harold5a920ca2018-02-02 18:34:25 -08001536 break;
Nathan Harolda2523312018-01-05 19:25:13 -08001537 case IpSecTransform.MODE_TUNNEL:
1538 break;
1539 default:
1540 throw new IllegalArgumentException(
1541 "Invalid IpSecTransform.mode: " + config.getMode());
Nathan Harolda10003d2017-08-23 13:46:33 -07001542 }
Benedict Wongab80e1f2018-07-25 18:46:19 -07001543
1544 config.setMarkValue(0);
1545 config.setMarkMask(0);
Nathan Harolda10003d2017-08-23 13:46:33 -07001546 }
1547
Benedict Wongd8db9182018-09-13 16:45:12 -07001548 private static final String TUNNEL_OP = AppOpsManager.OPSTR_MANAGE_IPSEC_TUNNELS;
Nathan Harold8c69bcb2018-05-15 19:18:38 -07001549
Nathan Harold21208ee2018-03-15 18:06:06 -07001550 private void enforceTunnelPermissions(String callingPackage) {
1551 checkNotNull(callingPackage, "Null calling package cannot create IpSec tunnels");
Benedict Wongd8db9182018-09-13 16:45:12 -07001552 switch (getAppOpsManager().noteOp(TUNNEL_OP, Binder.getCallingUid(), callingPackage)) {
1553 case AppOpsManager.MODE_DEFAULT:
1554 mContext.enforceCallingOrSelfPermission(
1555 android.Manifest.permission.MANAGE_IPSEC_TUNNELS, "IpSecService");
1556 break;
1557 case AppOpsManager.MODE_ALLOWED:
1558 return;
1559 default:
1560 throw new SecurityException("Request to ignore AppOps for non-legacy API");
Nathan Harold21208ee2018-03-15 18:06:06 -07001561 }
Nathan Harold5a920ca2018-02-02 18:34:25 -08001562 }
1563
Benedict Wong0fe58a92018-01-19 17:36:02 -08001564 private void createOrUpdateTransform(
1565 IpSecConfig c, int resourceId, SpiRecord spiRecord, EncapSocketRecord socketRecord)
1566 throws RemoteException {
1567
1568 int encapType = c.getEncapType(), encapLocalPort = 0, encapRemotePort = 0;
1569 if (encapType != IpSecTransform.ENCAP_NONE) {
1570 encapLocalPort = socketRecord.getPort();
1571 encapRemotePort = c.getEncapRemotePort();
1572 }
1573
1574 IpSecAlgorithm auth = c.getAuthentication();
1575 IpSecAlgorithm crypt = c.getEncryption();
1576 IpSecAlgorithm authCrypt = c.getAuthenticatedEncryption();
1577
Benedict Wongbf013a32018-03-15 19:41:41 -07001578 String cryptName;
1579 if (crypt == null) {
1580 cryptName = (authCrypt == null) ? IpSecAlgorithm.CRYPT_NULL : "";
1581 } else {
1582 cryptName = crypt.getName();
1583 }
1584
Benedict Wong0fe58a92018-01-19 17:36:02 -08001585 mSrvConfig
1586 .getNetdInstance()
1587 .ipSecAddSecurityAssociation(
Benedict Wonga0989622018-07-25 13:06:29 -07001588 Binder.getCallingUid(),
Benedict Wong0fe58a92018-01-19 17:36:02 -08001589 c.getMode(),
1590 c.getSourceAddress(),
1591 c.getDestinationAddress(),
1592 (c.getNetwork() != null) ? c.getNetwork().netId : 0,
1593 spiRecord.getSpi(),
1594 c.getMarkValue(),
1595 c.getMarkMask(),
1596 (auth != null) ? auth.getName() : "",
1597 (auth != null) ? auth.getKey() : new byte[] {},
1598 (auth != null) ? auth.getTruncationLengthBits() : 0,
Benedict Wongbf013a32018-03-15 19:41:41 -07001599 cryptName,
Benedict Wong0fe58a92018-01-19 17:36:02 -08001600 (crypt != null) ? crypt.getKey() : new byte[] {},
1601 (crypt != null) ? crypt.getTruncationLengthBits() : 0,
1602 (authCrypt != null) ? authCrypt.getName() : "",
1603 (authCrypt != null) ? authCrypt.getKey() : new byte[] {},
1604 (authCrypt != null) ? authCrypt.getTruncationLengthBits() : 0,
1605 encapType,
1606 encapLocalPort,
Benedict Wong781dae62018-09-06 11:31:25 -07001607 encapRemotePort,
1608 c.getXfrmInterfaceId());
Benedict Wong0fe58a92018-01-19 17:36:02 -08001609 }
1610
Nathan Harolda10003d2017-08-23 13:46:33 -07001611 /**
Benedict Wong0fe58a92018-01-19 17:36:02 -08001612 * Create a IPsec transform, which represents a single security association in the kernel. The
1613 * transform will be cached by the system server and must be freed when no longer needed. It is
1614 * possible to free one, deleting the SA from underneath sockets that are using it, which will
1615 * result in all of those sockets becoming unable to send or receive data.
Nathan Harold93962f32017-03-07 13:23:36 -08001616 */
1617 @Override
Nathan Harold21208ee2018-03-15 18:06:06 -07001618 public synchronized IpSecTransformResponse createTransform(
1619 IpSecConfig c, IBinder binder, String callingPackage) throws RemoteException {
1620 checkNotNull(c);
1621 if (c.getMode() == IpSecTransform.MODE_TUNNEL) {
1622 enforceTunnelPermissions(callingPackage);
1623 }
Nathan Harolda10003d2017-08-23 13:46:33 -07001624 checkIpSecConfig(c);
Benedict Wongf33f03132018-01-18 14:38:16 -08001625 checkNotNull(binder, "Null Binder passed to createTransform");
Nathan Haroldd8c74292017-12-13 19:16:33 -08001626 final int resourceId = mNextResourceId++;
Benedict Wong344bd622017-11-16 15:27:22 -08001627
1628 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
Benedict Wong4f9fb812017-12-13 17:16:53 -08001629 List<RefcountedResource> dependencies = new ArrayList<>();
Benedict Wong344bd622017-11-16 15:27:22 -08001630
1631 if (!userRecord.mTransformQuotaTracker.isAvailable()) {
Nathan Harolda1afbd82017-04-24 16:16:34 -07001632 return new IpSecTransformResponse(IpSecManager.Status.RESOURCE_UNAVAILABLE);
1633 }
Nathan Harolda10003d2017-08-23 13:46:33 -07001634
Benedict Wong344bd622017-11-16 15:27:22 -08001635 EncapSocketRecord socketRecord = null;
Benedict Wong0fe58a92018-01-19 17:36:02 -08001636 if (c.getEncapType() != IpSecTransform.ENCAP_NONE) {
Benedict Wong344bd622017-11-16 15:27:22 -08001637 RefcountedResource<EncapSocketRecord> refcountedSocketRecord =
1638 userRecord.mEncapSocketRecords.getRefcountedResourceOrThrow(
1639 c.getEncapSocketResourceId());
1640 dependencies.add(refcountedSocketRecord);
Benedict Wong344bd622017-11-16 15:27:22 -08001641 socketRecord = refcountedSocketRecord.getResource();
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001642 }
1643
Nathan Harolda2523312018-01-05 19:25:13 -08001644 RefcountedResource<SpiRecord> refcountedSpiRecord =
1645 userRecord.mSpiRecords.getRefcountedResourceOrThrow(c.getSpiResourceId());
1646 dependencies.add(refcountedSpiRecord);
1647 SpiRecord spiRecord = refcountedSpiRecord.getResource();
Benedict Wong344bd622017-11-16 15:27:22 -08001648
Nathan Harold144ce0a2018-04-03 16:13:19 -07001649 createOrUpdateTransform(c, resourceId, spiRecord, socketRecord);
Benedict Wong0fe58a92018-01-19 17:36:02 -08001650
1651 // SA was created successfully, time to construct a record and lock it away
Benedict Wong344bd622017-11-16 15:27:22 -08001652 userRecord.mTransformRecords.put(
1653 resourceId,
1654 new RefcountedResource<TransformRecord>(
Nathan Harolda2523312018-01-05 19:25:13 -08001655 new TransformRecord(resourceId, c, spiRecord, socketRecord),
Benedict Wong344bd622017-11-16 15:27:22 -08001656 binder,
1657 dependencies.toArray(new RefcountedResource[dependencies.size()])));
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001658 return new IpSecTransformResponse(IpSecManager.Status.OK, resourceId);
Nathan Harold93962f32017-03-07 13:23:36 -08001659 }
1660
1661 /**
1662 * Delete a transport mode transform that was previously allocated by + registered with the
1663 * system server. If this is called on an inactive (or non-existent) transform, it will not
1664 * return an error. It's safe to de-allocate transforms that may have already been deleted for
1665 * other reasons.
1666 */
1667 @Override
Benedict Wongf33f03132018-01-18 14:38:16 -08001668 public synchronized void deleteTransform(int resourceId) throws RemoteException {
Benedict Wong344bd622017-11-16 15:27:22 -08001669 UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
1670 releaseResource(userRecord.mTransformRecords, resourceId);
Nathan Harold93962f32017-03-07 13:23:36 -08001671 }
1672
1673 /**
1674 * Apply an active transport mode transform to a socket, which will apply the IPsec security
1675 * association as a correspondent policy to the provided socket
1676 */
1677 @Override
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001678 public synchronized void applyTransportModeTransform(
Nathan Harolda2523312018-01-05 19:25:13 -08001679 ParcelFileDescriptor socket, int direction, int resourceId) throws RemoteException {
Benedict Wonga0989622018-07-25 13:06:29 -07001680 int callingUid = Binder.getCallingUid();
1681 UserRecord userRecord = mUserResourceTracker.getUserRecord(callingUid);
Nathan Harolda2523312018-01-05 19:25:13 -08001682 checkDirection(direction);
Benedict Wong344bd622017-11-16 15:27:22 -08001683 // Get transform record; if no transform is found, will throw IllegalArgumentException
1684 TransformRecord info = userRecord.mTransformRecords.getResourceOrThrow(resourceId);
Nathan Harold93962f32017-03-07 13:23:36 -08001685
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001686 // TODO: make this a function.
Benedict Wonga0989622018-07-25 13:06:29 -07001687 if (info.pid != getCallingPid() || info.uid != callingUid) {
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001688 throw new SecurityException("Only the owner of an IpSec Transform may apply it!");
1689 }
1690
Benedict Wong8149f6e2018-01-18 18:31:45 -08001691 // Get config and check that to-be-applied transform has the correct mode
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001692 IpSecConfig c = info.getConfig();
Benedict Wong8149f6e2018-01-18 18:31:45 -08001693 Preconditions.checkArgument(
1694 c.getMode() == IpSecTransform.MODE_TRANSPORT,
1695 "Transform mode was not Transport mode; cannot be applied to a socket");
1696
Nathan Harold144ce0a2018-04-03 16:13:19 -07001697 mSrvConfig
1698 .getNetdInstance()
1699 .ipSecApplyTransportModeTransform(
Luke Huange8e522b2018-11-23 12:01:41 +08001700 socket,
Benedict Wonga0989622018-07-25 13:06:29 -07001701 callingUid,
Nathan Harold144ce0a2018-04-03 16:13:19 -07001702 direction,
1703 c.getSourceAddress(),
1704 c.getDestinationAddress(),
1705 info.getSpiRecord().getSpi());
Nathan Harold93962f32017-03-07 13:23:36 -08001706 }
Nathan Harold8dc1fd02017-04-04 19:37:48 -07001707
Nathan Harold93962f32017-03-07 13:23:36 -08001708 /**
Nathan Harolda2523312018-01-05 19:25:13 -08001709 * Remove transport mode transforms from a socket, applying the default (empty) policy. This
1710 * ensures that NO IPsec policy is applied to the socket (would be the equivalent of applying a
1711 * policy that performs no IPsec). Today the resourceId parameter is passed but not used:
1712 * reserved for future improved input validation.
Nathan Harold93962f32017-03-07 13:23:36 -08001713 */
1714 @Override
Nathan Haroldf73d2522018-01-17 01:00:20 -08001715 public synchronized void removeTransportModeTransforms(ParcelFileDescriptor socket)
1716 throws RemoteException {
Nathan Harold144ce0a2018-04-03 16:13:19 -07001717 mSrvConfig
1718 .getNetdInstance()
Luke Huange8e522b2018-11-23 12:01:41 +08001719 .ipSecRemoveTransportModeTransform(socket);
Nathan Harold93962f32017-03-07 13:23:36 -08001720 }
1721
Benedict Wong8149f6e2018-01-18 18:31:45 -08001722 /**
1723 * Apply an active tunnel mode transform to a TunnelInterface, which will apply the IPsec
1724 * security association as a correspondent policy to the provided interface
1725 */
1726 @Override
1727 public synchronized void applyTunnelModeTransform(
Nathan Harold21208ee2018-03-15 18:06:06 -07001728 int tunnelResourceId, int direction,
1729 int transformResourceId, String callingPackage) throws RemoteException {
1730 enforceTunnelPermissions(callingPackage);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001731 checkDirection(direction);
1732
Benedict Wonga0989622018-07-25 13:06:29 -07001733 int callingUid = Binder.getCallingUid();
1734 UserRecord userRecord = mUserResourceTracker.getUserRecord(callingUid);
Benedict Wong8149f6e2018-01-18 18:31:45 -08001735
1736 // Get transform record; if no transform is found, will throw IllegalArgumentException
1737 TransformRecord transformInfo =
1738 userRecord.mTransformRecords.getResourceOrThrow(transformResourceId);
1739
1740 // Get tunnelInterface record; if no such interface is found, will throw
1741 // IllegalArgumentException
1742 TunnelInterfaceRecord tunnelInterfaceInfo =
1743 userRecord.mTunnelInterfaceRecords.getResourceOrThrow(tunnelResourceId);
1744
1745 // Get config and check that to-be-applied transform has the correct mode
1746 IpSecConfig c = transformInfo.getConfig();
1747 Preconditions.checkArgument(
1748 c.getMode() == IpSecTransform.MODE_TUNNEL,
1749 "Transform mode was not Tunnel mode; cannot be applied to a tunnel interface");
1750
Benedict Wong0fe58a92018-01-19 17:36:02 -08001751 EncapSocketRecord socketRecord = null;
1752 if (c.getEncapType() != IpSecTransform.ENCAP_NONE) {
1753 socketRecord =
1754 userRecord.mEncapSocketRecords.getResourceOrThrow(c.getEncapSocketResourceId());
1755 }
1756 SpiRecord spiRecord = userRecord.mSpiRecords.getResourceOrThrow(c.getSpiResourceId());
1757
Benedict Wong8149f6e2018-01-18 18:31:45 -08001758 int mark =
Benedict Wong564e2aa2018-05-07 20:06:44 -07001759 (direction == IpSecManager.DIRECTION_OUT)
1760 ? tunnelInterfaceInfo.getOkey()
1761 : tunnelInterfaceInfo.getIkey();
Benedict Wong8149f6e2018-01-18 18:31:45 -08001762
Benedict Wong0fe58a92018-01-19 17:36:02 -08001763 try {
Benedict Wong781dae62018-09-06 11:31:25 -07001764 // Default to using the invalid SPI of 0 for inbound SAs. This allows policies to skip
1765 // SPI matching as part of the template resolution.
1766 int spi = IpSecManager.INVALID_SECURITY_PARAMETER_INDEX;
1767 c.setXfrmInterfaceId(tunnelInterfaceInfo.getIfId());
1768
Benedict Wongab80e1f2018-07-25 18:46:19 -07001769 // TODO: enable this when UPDSA supports updating marks. Adding kernel support upstream
1770 // (and backporting) would allow us to narrow the mark space, and ensure that the SA
1771 // and SPs have matching marks (as VTI are meant to be built).
1772 // Currently update does nothing with marks. Leave empty (defaulting to 0) to ensure the
1773 // config matches the actual allocated resources in the kernel.
Benedict Wongb2920572018-11-21 21:24:55 -08001774 // All SAs will have zero marks (from creation time), and any policy that matches the
1775 // same src/dst could match these SAs. Non-IpSecService governed processes that
1776 // establish floating policies with the same src/dst may result in undefined
1777 // behavior. This is generally limited to vendor code due to the permissions
1778 // (CAP_NET_ADMIN) required.
Benedict Wongab80e1f2018-07-25 18:46:19 -07001779 //
1780 // c.setMarkValue(mark);
1781 // c.setMarkMask(0xffffffff);
Benedict Wong0fe58a92018-01-19 17:36:02 -08001782
1783 if (direction == IpSecManager.DIRECTION_OUT) {
1784 // Set output mark via underlying network (output only)
1785 c.setNetwork(tunnelInterfaceInfo.getUnderlyingNetwork());
1786
Benedict Wong781dae62018-09-06 11:31:25 -07001787 // Set outbound SPI only. We want inbound to use any valid SA (old, new) on rekeys,
1788 // but want to guarantee outbound packets are sent over the new SA.
1789 spi = transformInfo.getSpiRecord().getSpi();
1790 }
1791
1792 // Always update the policy with the relevant XFRM_IF_ID
1793 for (int selAddrFamily : ADDRESS_FAMILIES) {
1794 mSrvConfig
1795 .getNetdInstance()
1796 .ipSecUpdateSecurityPolicy(
1797 callingUid,
1798 selAddrFamily,
1799 direction,
1800 transformInfo.getConfig().getSourceAddress(),
1801 transformInfo.getConfig().getDestinationAddress(),
1802 spi, // If outbound, also add SPI to the policy.
1803 mark, // Must always set policy mark; ikey/okey for VTIs
1804 0xffffffff,
1805 c.getXfrmInterfaceId());
Benedict Wong0fe58a92018-01-19 17:36:02 -08001806 }
1807
1808 // Update SA with tunnel mark (ikey or okey based on direction)
1809 createOrUpdateTransform(c, transformResourceId, spiRecord, socketRecord);
1810 } catch (ServiceSpecificException e) {
1811 if (e.errorCode == EINVAL) {
1812 throw new IllegalArgumentException(e.toString());
1813 } else {
1814 throw e;
1815 }
1816 }
Benedict Wong8149f6e2018-01-18 18:31:45 -08001817 }
1818
Nathan Harold93962f32017-03-07 13:23:36 -08001819 @Override
ludib0c95b12017-05-22 10:52:23 -07001820 protected synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Nathan Harold1afbef42017-03-01 18:55:06 -08001821 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
ludib0c95b12017-05-22 10:52:23 -07001822
1823 pw.println("IpSecService dump:");
Nathan Harold1afbef42017-03-01 18:55:06 -08001824 pw.println("NetdNativeService Connection: " + (isNetdAlive() ? "alive" : "dead"));
1825 pw.println();
ludib0c95b12017-05-22 10:52:23 -07001826
Benedict Wong344bd622017-11-16 15:27:22 -08001827 pw.println("mUserResourceTracker:");
1828 pw.println(mUserResourceTracker);
Nathan Harold1afbef42017-03-01 18:55:06 -08001829 }
1830}