├── .gitignore ├── Tests ├── Info.plist └── MOLXPCConnectionTests.m ├── BUILD ├── non_module_deps.bzl ├── MODULE.bazel ├── CONTRIBUTING.md ├── README.md ├── Source └── MOLXPCConnection │ ├── MOLXPCConnection.h │ └── MOLXPCConnection.m └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | bazel-* 3 | MODULE.bazel.lock 4 | -------------------------------------------------------------------------------- /Tests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleVersion 20 | 1 21 | 22 | 23 | -------------------------------------------------------------------------------- /BUILD: -------------------------------------------------------------------------------- 1 | load("@build_bazel_rules_apple//apple:macos.bzl", "macos_unit_test") 2 | 3 | objc_library( 4 | name = "MOLXPCConnection", 5 | srcs = ["Source/MOLXPCConnection/MOLXPCConnection.m"], 6 | hdrs = ["Source/MOLXPCConnection/MOLXPCConnection.h"], 7 | copts = ["-Wunguarded-availability"], 8 | includes = ["Source"], 9 | sdk_frameworks = ["Security"], 10 | visibility = ["//visibility:public"], 11 | deps = ["@MOLCodesignChecker"], 12 | ) 13 | 14 | objc_library( 15 | name = "MOLXPCConnectionTestsLib", 16 | testonly = 1, 17 | srcs = ["Tests/MOLXPCConnectionTests.m"], 18 | copts = ["-Wunguarded-availability"], 19 | deps = [ 20 | ":MOLXPCConnection", 21 | "@OCMock", 22 | ], 23 | ) 24 | 25 | macos_unit_test( 26 | name = "MOLXPCConnectionTests", 27 | minimum_os_version = "10.11", 28 | deps = [":MOLXPCConnectionTestsLib"], 29 | ) 30 | -------------------------------------------------------------------------------- /non_module_deps.bzl: -------------------------------------------------------------------------------- 1 | load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository") 2 | 3 | def _non_module_deps_impl(ctx): 4 | # OCMock is used in several tests. 5 | git_repository( 6 | name = "OCMock", 7 | build_file_content = """ 8 | objc_library( 9 | name = "OCMock", 10 | testonly = 1, 11 | hdrs = glob(["Source/OCMock/*.h"]), 12 | copts = [ 13 | "-Wno-vla", 14 | ], 15 | includes = [ 16 | "Source", 17 | "Source/OCMock", 18 | ], 19 | non_arc_srcs = glob(["Source/OCMock/*.m"]), 20 | pch = "Source/OCMock/OCMock-Prefix.pch", 21 | visibility = ["//visibility:public"], 22 | ) 23 | """, 24 | commit = "afd2c6924e8a36cb872bc475248b978f743c6050", # tag = v3.9.1 25 | remote = "https://github.com/erikdoe/ocmock", 26 | shallow_since = "1635703064 +0100", 27 | ) 28 | 29 | non_module_deps = module_extension(implementation = _non_module_deps_impl) 30 | -------------------------------------------------------------------------------- /MODULE.bazel: -------------------------------------------------------------------------------- 1 | module(name = "molxpcconnection", version = "2.1") 2 | 3 | bazel_dep(name = "apple_support", version = "1.15.1", repo_name = "build_bazel_apple_support") 4 | bazel_dep(name = "rules_apple", version = "3.5.0", repo_name = "build_bazel_rules_apple") 5 | 6 | bazel_dep(name = "molcertificate", version = "2.1", repo_name = "MOLCertificate") 7 | git_override( 8 | module_name = "molcertificate", 9 | remote = "https://github.com/google/macops-molcertificate.git", 10 | commit = "34f0ccf68a34a07cc636ada89057c529f90bec3a", 11 | ) 12 | 13 | bazel_dep(name = "molcodesignchecker", version = "3.0", repo_name = "MOLCodesignChecker") 14 | git_override( 15 | module_name = "molcodesignchecker", 16 | remote = "https://github.com/google/macops-molcodesignchecker.git", 17 | commit = "5060bcc8baa90bae3b0ca705d14850328bbbec53", 18 | ) 19 | 20 | non_module_deps = use_extension("//:non_module_deps.bzl", "non_module_deps") 21 | use_repo(non_module_deps, "OCMock") 22 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Want to contribute? Great! First, read this page (including the small print at the end). 2 | 3 | ### Before you contribute 4 | Before we can use your code, you must sign the 5 | [Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual) 6 | (CLA), which you can do online. The CLA is necessary mainly because you own the 7 | copyright to your changes, even after your contribution becomes part of our 8 | codebase, so we need your permission to use and distribute your code. We also 9 | need to be sure of various other things—for instance that you'll tell us if you 10 | know that your code infringes on other people's patents. You don't have to sign 11 | the CLA until after you've submitted your code for review and a member has 12 | approved it, but you must do it before we can put your code into our codebase. 13 | 14 | ### Code reviews 15 | All submissions, including submissions by project members, require review. We 16 | use GitHub pull requests for this purpose. 17 | 18 | ### Code Style 19 | 20 | All code submissions should try to match the surrounding code. Wherever 21 | possible, code should adhere to the 22 | [Google Objective-C Style Guide](http://google-styleguide.googlecode.com/svn/trunk/objcguide.xml). 23 | 24 | ### The small print 25 | Contributions made by corporations are covered by a different agreement than 26 | the one above, the [Software Grant and Corporate Contributor License Agreement](https://developers.google.com/open-source/cla/corporate). 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MOLXPCConnection 2 | 3 | A wrapper around NSXPCListener and NSXPCConnection to provide client multiplexing, 4 | signature validation of connecting clients, forced connection establishment and 5 | different exported interfaces for privileged/unprivileged clients. 6 | 7 | ## Installation 8 | 9 | #### Using [Bazel](http://bazel.build) Modules 10 | 11 | Add the following to your MODULE.bazel: 12 | 13 | ```bazel 14 | bazel_dep("molxpcconnection", version = "2.1", repo_name = "MOLXPCConnection") 15 | git_override( 16 | module_name = "molxpcconnection", 17 | remote = "https://github.com/google/macops-molxpcconnection.git", 18 | tag = "v2.1", 19 | ) 20 | ``` 21 | 22 | #### Using [Bazel](http://bazel.build) WORKSPACE 23 | 24 | Add the following to your WORKSPACE: 25 | 26 | ``` 27 | load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository") 28 | 29 | # Needed for MOLXPConnection 30 | git_repository( 31 | name = "MOLCertificate", 32 | remote = "https://github.com/google/macops-molcertificate.git", 33 | tag = "v2.0", 34 | ) 35 | 36 | # Needed for MOLXPCConnection 37 | git_repository( 38 | name = "MOLCodesignChecker", 39 | remote = "https://github.com/google/macops-molcodesignchecker.git", 40 | tag = "v2.0", 41 | ) 42 | 43 | git_repository( 44 | name = "MOLXPCConnection", 45 | remote = "https://github.com/google/macops-molxpcconnection.git", 46 | tag = "v2.1", 47 | ) 48 | ``` 49 | 50 | ### Adding dependency in BUILD 51 | 52 | In your BUILD file, add MOLXPCConnection as a dependency: 53 | 54 |
 55 | objc_library(
 56 |     name = "MyAwesomeApp_lib",
 57 |     srcs = ["src/MyAwesomeApp.m", "src/MyAwesomeApp.h"],
 58 |     deps = ["@MOLXPCConnection//:MOLXPCConnection"],
 59 | )
 60 | 
61 | 62 | 63 | ## Example 64 | 65 | Example server started by `launchd` where the `launchd` job has a `MachServices` key: 66 | 67 | ```objc 68 | MOLXPCConnection *conn = [[MOLXPCConnection alloc] initServerWithName:@"MyServer"]; 69 | conn.privilegedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(MyServerProtocol)]; 70 | conn.exportedObject = myObject; 71 | [conn resume]; 72 | ``` 73 | 74 | Example client, connecting to above server: 75 | 76 | ```objc 77 | MOLXPCConnection *conn = [[MOLXPCConnection alloc] initClientWithName:"MyServer" withOptions:0]; 78 | conn.remoteInterface = [NSXPCInterface interfaceWithProtocol:@protocol(MyServerProtocol)]; 79 | conn.invalidationHandler = ^{ NSLog(@"Connection invalidated") }; 80 | [conn resume]; 81 | ``` 82 | 83 | The client can send a message to the server with: 84 | 85 | ```objc 86 | [conn.remoteObjectProxy selectorInRemoteInterface]; 87 | ``` 88 | 89 | One advantage of the way that MOLXPCConnection works over using NSXPCConnection directly is that from the client-side once the resume method has finished, the connection is either valid or the invalidation handler will be called. Ordinarily, the connection doesn't actually get made until the first message is sent across it. 90 | 91 | `messages are always delivered on a background thread!` 92 | 93 | ## Documentation 94 | 95 | Reference documentation is at CocoaDocs.org: 96 | 97 | http://cocoadocs.org/docsets/MOLXPCConnection 98 | 99 | ## Contributing 100 | 101 | Patches to this library are very much welcome. 102 | Please see the [CONTRIBUTING](https://github.com/google/macops-molxpcconnection/blob/master/CONTRIBUTING.md) file. 103 | 104 | -------------------------------------------------------------------------------- /Source/MOLXPCConnection/MOLXPCConnection.h: -------------------------------------------------------------------------------- 1 | /// Copyright 2017 Google Inc. All rights reserved. 2 | /// 3 | /// Licensed under the Apache License, Version 2.0 (the "License"); 4 | /// you may not use this file except in compliance with the License. 5 | /// You may obtain a copy of the License at 6 | /// 7 | /// http://www.apache.org/licenses/LICENSE-2.0 8 | /// 9 | /// Unless required by applicable law or agreed to in writing, software 10 | /// distributed under the License is distributed on an "AS IS" BASIS, 11 | /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | /// See the License for the specific language governing permissions and 13 | /// limitations under the License. 14 | 15 | #import 16 | 17 | /** 18 | A wrapper around NSXPCListener and NSXPCConnection to provide client multiplexing, signature 19 | validation of connecting clients and forced connection establishment. 20 | 21 | Example server started by @c launchd where the @c launchd job has a @c MachServices key: 22 | 23 | @code 24 | MOLXPCConnection *conn = [[MOLXPCConnection alloc] initServerWithName:@"MyServer"]; 25 | conn.privilegedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(MyPriamryServerProtocol)]; 26 | conn.unprivilegedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(MySecondaryServerProtocol)]; 27 | conn.exportedObject = myObject; 28 | [conn resume]; 29 | @endcode 30 | 31 | Example client, connecting to above server: 32 | 33 | @code 34 | MOLXPCConnection *conn = [[MOLXPCConnection alloc] initClientWithName:"MyServer" 35 | withOptions:0]; 36 | conn.remoteInterface = [NSXPCInterface interfaceWithProtocol:@protocol(MyServerProtocol)]; 37 | conn.invalidationHandler = ^{ NSLog(@"Connection invalidated") }; 38 | [conn resume]; 39 | @endcode 40 | 41 | The client can send a message to the server with: 42 | 43 | @code 44 | [conn.remoteObjectProxy selectorInRemoteInterface]; 45 | @endcode 46 | 47 | One advantage of the way that MOLXPCConnection works over using NSXPCConnection directly is that 48 | from the client-side once the resume method has finished, the connection is either valid or the 49 | invalidation handler will be called. Ordinarily, the connection doesn't actually get made until 50 | the first message is sent across it. 51 | 52 | @note messages are always delivered on a background thread! 53 | */ 54 | @interface MOLXPCConnection : NSObject 55 | 56 | /** 57 | Initialize a new server with a given listener, provided by `[NSXPCListener anonymousListener]`. 58 | */ 59 | - (nullable instancetype)initServerWithListener:(nonnull NSXPCListener *)listener; 60 | 61 | /** 62 | Initializer for the 'server' side of the connection, started by launchd. 63 | 64 | @param name MachService name, must match the MachServices key in the launchd.plist 65 | */ 66 | - (nullable instancetype)initServerWithName:(nonnull NSString *)name; 67 | 68 | /** 69 | Initialize a new client to a service exported by a LaunchDaemon. 70 | 71 | @param name MachService name 72 | @param privileged Use YES if the server is running as root. 73 | */ 74 | - (nullable instancetype)initClientWithName:(nonnull NSString *)name privileged:(BOOL)privileged; 75 | 76 | /** 77 | Initialize a new client to a service within a bundle. 78 | 79 | @param name service name 80 | */ 81 | - (nullable instancetype)initClientWithServiceName:(nonnull NSString *)name; 82 | 83 | /** 84 | Initialize a new client with a listener endpoint sent from another process. 85 | 86 | @param listener An NSXPCListenerEndpoint to connect to. 87 | */ 88 | - (nullable instancetype)initClientWithListener:(nonnull NSXPCListenerEndpoint *)listener; 89 | 90 | /** 91 | Call when the properties of the object have been set-up and you're ready for connections. 92 | 93 | For clients, this call can take up to 2s to complete for connection to finish establishing though 94 | in basically all cases it will actually complete in a few milliseconds. 95 | */ 96 | - (void)resume; 97 | 98 | /** 99 | Invalidate the connection(s). This must be done before the object can be released. 100 | */ 101 | - (void)invalidate; 102 | 103 | /** 104 | The interface the remote object should conform to. (client) 105 | */ 106 | @property(retain, nullable) NSXPCInterface *remoteInterface; 107 | 108 | /** 109 | A proxy to the object at the other end of the connection. (client) 110 | 111 | @note If the connection to the server failed, this will be nil, so you can safely send messages 112 | and rely on the invalidationHandler for handling the failure. 113 | */ 114 | @property(readonly, nonatomic, nullable) id remoteObjectProxy; 115 | 116 | /** 117 | A synchronous proxy to the object at the other end of the connection. (client) 118 | 119 | @note If the connection to the server failed, this will be nil, so you can safely send messages 120 | and rely on the invalidationHandler for handling the failure. 121 | */ 122 | @property(readonly, nonatomic, nullable) id synchronousRemoteObjectProxy API_AVAILABLE(macos(10.11)); 123 | 124 | /** 125 | The privileged interface this object exports. (server) 126 | */ 127 | @property(retain, nullable) NSXPCInterface *privilegedInterface; 128 | 129 | /** 130 | The unprivileged interface this object exports. (server) 131 | */ 132 | @property(retain, nullable) NSXPCInterface *unprivilegedInterface; 133 | 134 | /** 135 | Old interface property, please update to use privilegedExportedInterface and/or 136 | unprivilegedExportedInterface instead. 137 | */ 138 | @property(retain, nullable) NSXPCInterface *exportedInterface __attribute__(( 139 | deprecated("Use privilegedInterface and / or unprivilegedInterface instead."))); 140 | 141 | /** 142 | The object that responds to messages from the other end. (server) 143 | */ 144 | @property(retain, nullable) id exportedObject; 145 | 146 | /** 147 | A block to run when a/the connection is accepted and fully established. 148 | */ 149 | @property(copy, nullable) void (^acceptedHandler)(void); 150 | 151 | /** 152 | A block to run when a/the connection is invalidated/interrupted/rejected. 153 | */ 154 | @property(copy, nullable) void (^invalidationHandler)(void); 155 | 156 | @end 157 | 158 | // Strengthify Macros 159 | 160 | #define STRONGIFY(var) \ 161 | _Pragma("clang diagnostic push") \ 162 | _Pragma("clang diagnostic ignored \"-Wshadow\"") \ 163 | __strong __typeof(var) var = (Weak_##var); \ 164 | _Pragma("clang diagnostic pop") 165 | 166 | #define WEAKIFY(var) \ 167 | __weak __typeof(var) Weak_##var = (var); 168 | -------------------------------------------------------------------------------- /Tests/MOLXPCConnectionTests.m: -------------------------------------------------------------------------------- 1 | /// Copyright 2017 Google Inc. All rights reserved. 2 | /// 3 | /// Licensed under the Apache License, Version 2.0 (the "License"); 4 | /// you may not use this file except in compliance with the License. 5 | /// You may obtain a copy of the License at 6 | /// 7 | /// http://www.apache.org/licenses/LICENSE-2.0 8 | /// 9 | /// Unless required by applicable law or agreed to in writing, software 10 | /// distributed under the License is distributed on an "AS IS" BASIS, 11 | /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | /// See the License for the specific language governing permissions and 13 | /// limitations under the License. 14 | 15 | #import 16 | 17 | #import 18 | 19 | #import 20 | #import 21 | 22 | @interface MOLXPCConnectionTest : XCTestCase 23 | @end 24 | 25 | @protocol DummyXPCProtocol 26 | @end 27 | 28 | @protocol DeepThoughtProtocol 29 | - (void)theAnswerToLifeTheUniverseAndEverything:(void(^)(int))reply; 30 | @end 31 | 32 | @interface DeepThought : NSObject 33 | @end 34 | 35 | @implementation DeepThought 36 | - (void)theAnswerToLifeTheUniverseAndEverything:(void(^)(int))reply { 37 | reply(42); 38 | } 39 | @end 40 | 41 | @implementation MOLXPCConnectionTest 42 | 43 | - (NSXPCInterface *)deepThoughtInterface { 44 | static NSXPCInterface *interface; 45 | static dispatch_once_t onceToken; 46 | dispatch_once(&onceToken, ^{ 47 | interface = [NSXPCInterface interfaceWithProtocol:@protocol(DeepThoughtProtocol)]; 48 | }); 49 | return interface; 50 | } 51 | 52 | - (void)testPlainInit { 53 | XCTAssertThrows([[MOLXPCConnection alloc] init]); 54 | } 55 | 56 | - (void)testInitClient { 57 | id mockConnection = OCMClassMock([NSXPCConnection class]); 58 | OCMStub([mockConnection alloc]).andReturn(mockConnection); 59 | OCMExpect([mockConnection initWithMachServiceName:@"Client" 60 | options:0]).andReturn(mockConnection); 61 | 62 | MOLXPCConnection *sut = [[MOLXPCConnection alloc] initClientWithName:@"Client" privileged:NO]; 63 | XCTAssertNotNil(sut); 64 | 65 | OCMExpect([mockConnection initWithMachServiceName:@"Client" 66 | options:NSXPCConnectionPrivileged]).andReturn( 67 | mockConnection); 68 | sut = [[MOLXPCConnection alloc] initClientWithName:@"Client" privileged:YES]; 69 | XCTAssertNotNil(sut); 70 | 71 | OCMVerifyAll(mockConnection); 72 | [mockConnection stopMocking]; 73 | } 74 | 75 | - (void)testInitServer { 76 | id mockListener = OCMClassMock([NSXPCListener class]); 77 | OCMStub([mockListener alloc]).andReturn(mockListener); 78 | OCMExpect([mockListener initWithMachServiceName:@"TestServer"]).andReturn(mockListener); 79 | MOLXPCConnection *sut = [[MOLXPCConnection alloc] initServerWithName:@"TestServer"]; 80 | XCTAssertNotNil(sut); 81 | OCMVerifyAll(mockListener); 82 | [mockListener stopMocking]; 83 | } 84 | 85 | - (void)testConnectionRejection { 86 | pid_t pid = [[NSProcessInfo processInfo] processIdentifier]; 87 | id mockCodesignChecker = OCMClassMock([MOLCodesignChecker class]); 88 | OCMStub([mockCodesignChecker alloc]).andReturn(mockCodesignChecker); 89 | OCMExpect([mockCodesignChecker initWithPID:pid]).andReturn(mockCodesignChecker); 90 | OCMExpect([mockCodesignChecker signingInformationMatches:OCMOCK_ANY]).andReturn(NO); 91 | 92 | NSXPCListener *listener = [NSXPCListener anonymousListener]; 93 | 94 | MOLXPCConnection *sutServer = [[MOLXPCConnection alloc] initServerWithListener:listener]; 95 | sutServer.unprivilegedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(DummyXPCProtocol)]; 96 | [sutServer resume]; 97 | 98 | __block XCTestExpectation *exp1 = [self expectationWithDescription:@"Client Invalidated"]; 99 | MOLXPCConnection *sutClient = [[MOLXPCConnection alloc] initClientWithListener:listener.endpoint]; 100 | sutClient.invalidationHandler = ^{ 101 | [exp1 fulfill]; 102 | exp1 = nil; // precent multiple fulfill violation 103 | }; 104 | [sutClient resume]; 105 | 106 | [self waitForExpectationsWithTimeout:3.0 handler:NULL]; 107 | 108 | [mockCodesignChecker stopMocking]; 109 | } 110 | 111 | - (void)testConnectionAcceptance { 112 | NSXPCListener *listener = [NSXPCListener anonymousListener]; 113 | 114 | XCTestExpectation *exp1 = [self expectationWithDescription:@"Server Accepted"]; 115 | MOLXPCConnection *sutServer = [[MOLXPCConnection alloc] initServerWithListener:listener]; 116 | sutServer.unprivilegedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(DummyXPCProtocol)]; 117 | sutServer.acceptedHandler = ^{ 118 | [exp1 fulfill]; 119 | }; 120 | [sutServer resume]; 121 | 122 | XCTestExpectation *exp2 = [self expectationWithDescription:@"Client Accepted"]; 123 | MOLXPCConnection *sutClient = [[MOLXPCConnection alloc] initClientWithListener:listener.endpoint]; 124 | sutClient.acceptedHandler = ^{ 125 | [exp2 fulfill]; 126 | }; 127 | [sutClient resume]; 128 | 129 | [self waitForExpectationsWithTimeout:2.0 handler:NULL]; 130 | } 131 | 132 | - (void)testConnectionInterruption { 133 | NSXPCListener *listener = [NSXPCListener anonymousListener]; 134 | MOLXPCConnection *sutServer = [[MOLXPCConnection alloc] initServerWithListener:listener]; 135 | sutServer.unprivilegedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(DummyXPCProtocol)]; 136 | [sutServer resume]; 137 | 138 | __block XCTestExpectation *exp1 = [self expectationWithDescription:@"Client Invalidated"]; 139 | MOLXPCConnection *sutClient = [[MOLXPCConnection alloc] initClientWithListener:listener.endpoint]; 140 | sutClient.invalidationHandler = ^{ 141 | [exp1 fulfill]; 142 | exp1 = nil; // prevent multiple fulfill violation 143 | }; 144 | [sutClient resume]; 145 | 146 | [sutServer invalidate]; 147 | sutServer = nil; 148 | 149 | [self waitForExpectationsWithTimeout:1.0 handler:NULL]; 150 | } 151 | 152 | - (void)testSynchronous { 153 | NSXPCListener *listener = [NSXPCListener anonymousListener]; 154 | MOLXPCConnection *sutServer = [[MOLXPCConnection alloc] initServerWithListener:listener]; 155 | sutServer.unprivilegedInterface = [self deepThoughtInterface]; 156 | sutServer.exportedObject = [[DeepThought alloc] init]; 157 | [sutServer resume]; 158 | 159 | __block int answer = 0; 160 | MOLXPCConnection *sutClient = [[MOLXPCConnection alloc] initClientWithListener:listener.endpoint]; 161 | sutClient.remoteInterface = [self deepThoughtInterface]; 162 | [sutClient resume]; 163 | [[sutClient synchronousRemoteObjectProxy] theAnswerToLifeTheUniverseAndEverything:^(int reply) { 164 | answer = reply; 165 | }]; 166 | XCTAssertEqual(answer, 42); 167 | } 168 | 169 | @end 170 | -------------------------------------------------------------------------------- /Source/MOLXPCConnection/MOLXPCConnection.m: -------------------------------------------------------------------------------- 1 | /// Copyright 2017 Google Inc. All rights reserved. 2 | /// 3 | /// Licensed under the Apache License, Version 2.0 (the "License"); 4 | /// you may not use this file except in compliance with the License. 5 | /// You may obtain a copy of the License at 6 | /// 7 | /// http://www.apache.org/licenses/LICENSE-2.0 8 | /// 9 | /// Unless required by applicable law or agreed to in writing, software 10 | /// distributed under the License is distributed on an "AS IS" BASIS, 11 | /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | /// See the License for the specific language governing permissions and 13 | /// limitations under the License. 14 | 15 | #import "MOLXPCConnection.h" 16 | 17 | #import 18 | 19 | /** 20 | Protocol used during connection establishment, @see MOLXPCConnectionInterface 21 | */ 22 | @protocol MOLXPCConnectionProtocol 23 | - (void)connectWithReply:(void (^)(void))reply; 24 | @end 25 | 26 | /** 27 | Recipient object used during connection establishment. Each incoming connection 28 | has one of these objects created which accept the message in the protocol 29 | and call the block provided during creation before replying. 30 | 31 | This allows the server to reset the connection's exported interface and 32 | object to the correct values after the client has sent the establishment message. 33 | */ 34 | @interface MOLXPCConnectionInterface : NSObject 35 | @property(strong) void (^block)(void); 36 | @end 37 | 38 | @implementation MOLXPCConnectionInterface 39 | - (void)connectWithReply:(void (^)(void))reply { 40 | if (self.block) self.block(); 41 | reply(); 42 | } 43 | @end 44 | 45 | @interface MOLXPCConnection () 46 | @property NSXPCInterface *validationInterface; 47 | 48 | /// The XPC listener (server only). 49 | @property NSXPCListener *listenerObject; 50 | 51 | /// The current connection object (client only). 52 | @property NSXPCConnection *currentConnection; 53 | @end 54 | 55 | @implementation MOLXPCConnection 56 | 57 | #pragma mark Initializers 58 | 59 | - (instancetype)initServerWithListener:(NSXPCListener *)listener { 60 | self = [super init]; 61 | if (self) { 62 | _listenerObject = listener; 63 | _validationInterface = 64 | [NSXPCInterface interfaceWithProtocol:@protocol(MOLXPCConnectionProtocol)]; 65 | } 66 | return self; 67 | } 68 | 69 | - (instancetype)initServerWithName:(NSString *)name { 70 | return [self initServerWithListener:[[NSXPCListener alloc] initWithMachServiceName:name]]; 71 | } 72 | 73 | - (instancetype)initClientWithListener:(NSXPCListenerEndpoint *)listener { 74 | self = [super init]; 75 | if (self) { 76 | _currentConnection = [[NSXPCConnection alloc] initWithListenerEndpoint:listener]; 77 | if (!_currentConnection) return nil; 78 | _validationInterface = 79 | [NSXPCInterface interfaceWithProtocol:@protocol(MOLXPCConnectionProtocol)]; 80 | } 81 | return self; 82 | } 83 | 84 | - (instancetype)initClientWithName:(NSString *)name privileged:(BOOL)privileged { 85 | self = [super init]; 86 | if (self) { 87 | NSXPCConnectionOptions options = (privileged ? NSXPCConnectionPrivileged : 0); 88 | _currentConnection = [[NSXPCConnection alloc] initWithMachServiceName:name options:options]; 89 | if (!_currentConnection) return nil; 90 | _validationInterface = 91 | [NSXPCInterface interfaceWithProtocol:@protocol(MOLXPCConnectionProtocol)]; 92 | } 93 | return self; 94 | } 95 | 96 | - (instancetype)initClientWithServiceName:(NSString *)name { 97 | self = [super init]; 98 | if (self) { 99 | _currentConnection = [[NSXPCConnection alloc] initWithServiceName:name]; 100 | if (!_currentConnection) return nil; 101 | _validationInterface = 102 | [NSXPCInterface interfaceWithProtocol:@protocol(MOLXPCConnectionProtocol)]; 103 | } 104 | return self; 105 | } 106 | 107 | - (instancetype)init { 108 | [self doesNotRecognizeSelector:_cmd]; 109 | return nil; 110 | } 111 | 112 | #pragma mark Connection set-up 113 | 114 | - (void)resume { 115 | if (self.listenerObject) { 116 | self.listenerObject.delegate = self; 117 | [self.listenerObject resume]; 118 | } else { 119 | WEAKIFY(self); 120 | 121 | // Set-up the connection with the remote interface set to the validation interface, 122 | // send a message to the listener to finish establishing the connection 123 | dispatch_semaphore_t sema = dispatch_semaphore_create(0); 124 | self.currentConnection.remoteObjectInterface = self.validationInterface; 125 | self.currentConnection.interruptionHandler = self.currentConnection.invalidationHandler = ^{ 126 | STRONGIFY(self); 127 | if (self.invalidationHandler) self.invalidationHandler(); 128 | }; 129 | [self.currentConnection resume]; 130 | [[self.currentConnection remoteObjectProxy] connectWithReply:^{ 131 | STRONGIFY(self); 132 | // The connection is now established 133 | [self.currentConnection suspend]; 134 | self.currentConnection.remoteObjectInterface = self.remoteInterface; 135 | [self.currentConnection resume]; 136 | dispatch_semaphore_signal(sema); 137 | if (self.acceptedHandler) self.acceptedHandler(); 138 | }]; 139 | if (dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC))) { 140 | // This is unusual - as we're not inside a block - but necessary in case the caller sets an 141 | // invalidation handler that causes this instance to be released (which is a reasonable 142 | // approach). If establishing a connection fails, the invalidation handler will be called 143 | // and then shortly after this bit of code will run causing a crash. 144 | STRONGIFY(self); 145 | 146 | // Connection was not established in a reasonable time, invalidate. 147 | self.currentConnection.remoteObjectInterface = nil; // ensure clients don't try to use it. 148 | [self.currentConnection invalidate]; 149 | } 150 | } 151 | } 152 | 153 | - (BOOL)listener:(NSXPCListener *)listener shouldAcceptNewConnection:(NSXPCConnection *)connection { 154 | // Fail this connection if it's from an unprivileged user and we have been 155 | // configured to only allow root/admins 156 | NSXPCInterface *interface; 157 | if (connection.effectiveUserIdentifier == 0) { 158 | interface = self.privilegedInterface; 159 | } else { 160 | interface = self.unprivilegedInterface; 161 | } 162 | 163 | // TODO(any): Remove 1-2 releases after exportedInterface was marked deprecated. 164 | if (!interface) { 165 | // Silence warning about using exportedInterface temporarily until this is removed. 166 | #pragma clang diagnostic push 167 | #pragma clang diagnostic ignored "-Wdeprecated-declarations" 168 | interface = self.exportedInterface; 169 | #pragma clang diagnostic pop 170 | } 171 | 172 | if (!interface) return NO; 173 | 174 | pid_t pid = connection.processIdentifier; 175 | MOLCodesignChecker *otherCS = [[MOLCodesignChecker alloc] initWithPID:pid]; 176 | if (![otherCS signingInformationMatches:[[MOLCodesignChecker alloc] initWithSelf]]) { 177 | return NO; 178 | } 179 | 180 | // The client passed the code signature check, now we need to resume the listener and 181 | // return YES so that the client can send the connectWithReply message. Once the client does 182 | // we reset the connection's exportedInterface and exportedObject. 183 | MOLXPCConnectionInterface *ci = [[MOLXPCConnectionInterface alloc] init]; 184 | WEAKIFY(self); 185 | WEAKIFY(connection); 186 | ci.block = ^{ 187 | STRONGIFY(self) 188 | STRONGIFY(connection); 189 | [connection suspend]; 190 | connection.invalidationHandler = connection.interruptionHandler = ^{ 191 | if (self.invalidationHandler) self.invalidationHandler(); 192 | }; 193 | connection.exportedInterface = interface; 194 | connection.exportedObject = self.exportedObject; 195 | [connection resume]; 196 | 197 | // The connection is now established. 198 | if (self.acceptedHandler) self.acceptedHandler(); 199 | }; 200 | connection.exportedInterface = self.validationInterface; 201 | connection.exportedObject = ci; 202 | [connection resume]; 203 | 204 | return YES; 205 | } 206 | 207 | - (id)remoteObjectProxy { 208 | if (self.currentConnection.remoteObjectInterface && 209 | self.currentConnection.remoteObjectInterface != self.validationInterface) { 210 | return [self.currentConnection remoteObjectProxyWithErrorHandler:^(NSError *error) { 211 | [self.currentConnection invalidate]; 212 | }]; 213 | } 214 | return nil; 215 | } 216 | 217 | 218 | - (id)synchronousRemoteObjectProxy { 219 | if (self.currentConnection.remoteObjectInterface && 220 | self.currentConnection.remoteObjectInterface != self.validationInterface) { 221 | return [self.currentConnection synchronousRemoteObjectProxyWithErrorHandler:^(NSError *error) { 222 | [self.currentConnection invalidate]; 223 | }]; 224 | } 225 | return nil; 226 | } 227 | 228 | #pragma mark Connection tear-down 229 | 230 | - (void)invalidate { 231 | if (self.currentConnection) { 232 | [self.currentConnection invalidate]; 233 | self.currentConnection = nil; 234 | } else if (self.listenerObject) { 235 | [self.listenerObject invalidate]; 236 | } 237 | } 238 | 239 | @end 240 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | CONTRIBUTING 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | --------------------------------------------------------------------------------