Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 101 additions & 1 deletion packages/nativescript-websockets/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,114 @@ ns plugin add @valor/nativescript-websockets

## Usage

To use this plugin simply add this to your `polyfills.ts` on angular (before importing zone.js) or on your entrypoint (app.ts, main.ts) on other flavors:
### As a global polyfill

Add this to your `polyfills.ts` on angular (before importing zone.js) or on your entrypoint (app.ts, main.ts) on other flavors:

```ts
import '@valor/nativescript-websockets';
```

This installs the plugin as `global.WebSocket`, unless a `WebSocket` implementation already exists. To replace an existing one, call `installWebsocketPolyfill()` yourself:

```ts
import { installWebsocketPolyfill } from '@valor/nativescript-websockets/websocket';

installWebsocketPolyfill();
```

Beware that import order matters! If needed you can also add the plugin to your bundle directly with webpack.

### Without the polyfill

Import the class directly. Nothing global is touched:

```ts
import { WebSocket } from '@valor/nativescript-websockets/websocket';

const ws = new WebSocket('wss://example.com/socket');
```

Prefer this when you use the `ssl` options below. With the polyfill, nothing guarantees that `global.WebSocket` is this plugin (another library may have installed its own), and an implementation that ignores `ssl` would connect without your pins.

## Options

The constructor takes an optional third argument:

```ts
new WebSocket(url, protocols, {
headers: { Authorization: 'Bearer ...' },
ssl: { ... },
});
```

The DOM `WebSocket` type has no third argument, so import `WebSocket` (and the `WebSocketOptions` type) from `@valor/nativescript-websockets/websocket` to get it typed.

## TLS: certificate validation, pinning and custom CAs

```ts
ssl?: {
validation?: 'system' | 'pins-only' | 'none'; // default 'system'
pins?: Array<{ type: 'pem'; cert: string } | { type: 'sha256'; hash: string }>;
ca?: string | string[]; // PEM
}
```

| `validation` | Certificate checks | `pins` | `ca` |
| -------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | ----------- |
| `'system'` (default) | Chain, hostname and expiry are validated against the system trust store, or against `ca` when given. | Optional. At least one certificate of the **validated** chain (leaf, intermediate or root) must match. | Optional |
| `'pins-only'` | None. The chain, hostname and expiry are not checked. | Required. The server's **leaf** certificate must match. | Not allowed |
| `'none'` | None. Any server is accepted, which makes the connection open to man-in-the-middle attacks. | Not allowed | Not allowed |

Pins match a certificate's **public key** (the SHA-256 of its SubjectPublicKeyInfo, the same format as OkHttp's `CertificatePinner` and HPKP). Renewing a certificate with the same key keeps the pin valid. A pin can be given as:

- `{ type: 'pem', cert }`: the plugin pins the public key of the given certificate.
- `{ type: 'sha256', hash }`: the base64 hash, which you can compute with:

```sh
openssl x509 -in server.pem -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | base64
```

Invalid or contradictory options throw from the constructor, as does `pins` or `ca` on a `ws://` URL.

### Pinning a public server

Keep the normal validation and pin your CA's intermediate (or your own key), plus a backup, so routine renewals don't lock the app out:

```ts
new WebSocket('wss://api.example.com', [], {
ssl: {
pins: [
{ type: 'sha256', hash: 'primary...=' },
{ type: 'sha256', hash: 'backup...=' },
],
},
});
```

### Private CA

Trust only your CA instead of the system store. Hostname and expiry are still validated, so the server certificate must list the host (or IP address) you connect to in its subjectAltName:

```ts
new WebSocket('wss://internal.example.com', [], { ssl: { ca: CA_PEM } });
```

### Self-signed certificate (including servers reached by IP address)

Accept exactly one server key, and nothing else. Since only the key is checked, this works for self-signed certificates without a subjectAltName, for IP addresses, and for long-lived certificates that iOS would otherwise reject:

```ts
new WebSocket('wss://192.168.0.10:8443', [], {
ssl: { validation: 'pins-only', pins: [{ type: 'pem', cert: SERVER_PEM }] },
});
```

### Platform notes

`ssl` applies only to the socket it is passed to. On Android, no app configuration (such as `network_security_config.xml`) is needed.

On Android, a pin mismatch with `validation: 'pins-only'` is reported as OkHttp's `Hostname <host> not verified` error.

## License

Expand Down
106 changes: 97 additions & 9 deletions packages/nativescript-websockets/bridge.android.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { HeaderType } from './common';
import { NativeBridgeDefinition } from './websocket.definition';
import { ResolvedSslOptions } from './common';
import { NativeBridgeDefinition, WebSocketBridgeConnectOptions } from './websocket.definition';

interface ExtendedArrayBuffer extends ArrayBuffer {
from?(nativeBuffer: java.nio.ByteBuffer): ArrayBuffer;
Expand Down Expand Up @@ -66,22 +66,102 @@ function getDefaultOrigin(uri: string) {
}
}

function certificateFromBase64(der: string): java.security.cert.X509Certificate {
try {
const bytes = android.util.Base64.decode(der, android.util.Base64.DEFAULT);
return java.security.cert.CertificateFactory.getInstance('X.509').generateCertificate(new java.io.ByteArrayInputStream(bytes)) as java.security.cert.X509Certificate;
} catch {
throw new TypeError('Invalid certificate');
}
}

function sslSocketFactory(trustManager: javax.net.ssl.X509TrustManager): javax.net.ssl.SSLSocketFactory {
const trustManagers = Array.create(javax.net.ssl.TrustManager, 1);
trustManagers[0] = trustManager;
const context = javax.net.ssl.SSLContext.getInstance('TLS');
context.init(null as never, trustManagers, null as never);
return context.getSocketFactory();
}

function trustManagerForRoots(roots: java.security.cert.X509Certificate[]): javax.net.ssl.X509TrustManager {
const keyStore = java.security.KeyStore.getInstance(java.security.KeyStore.getDefaultType());
keyStore.load(null as never, null as never);
roots.forEach((root, i) => keyStore.setCertificateEntry(`ca${i}`, root));
const factory = javax.net.ssl.TrustManagerFactory.getInstance(javax.net.ssl.TrustManagerFactory.getDefaultAlgorithm());
factory.init(keyStore);
return factory.getTrustManagers()[0] as javax.net.ssl.X509TrustManager;
}

// NativeScript runs these callbacks on the main thread, where a thrown exception crashes the app instead of
// failing the handshake. So nothing here throws: the trust manager accepts every chain and the decision is made
// by the hostname verifier, which OkHttp calls right after the handshake and before any request is written.
const acceptAnyChain = new javax.net.ssl.X509TrustManager({
checkClientTrusted() {
// server-side only
},
checkServerTrusted() {
// see the comment above
},
getAcceptedIssuers() {
// OkHttp needs a non-null array
return Array.create(java.security.cert.X509Certificate, 0);
},
});

function hostnameVerifier(accept: (leaf: java.security.cert.Certificate) => boolean): javax.net.ssl.HostnameVerifier {
return new javax.net.ssl.HostnameVerifier({
verify(hostname: string, session: javax.net.ssl.SSLSession) {
try {
const chain = session.getPeerCertificates();
return chain.length > 0 && accept(chain[0]);
} catch {
return false;
}
},
});
}

function configureSsl(builder: okhttp3.OkHttpClient.Builder, host: string, ssl: ResolvedSslOptions) {
// CertificatePinner's 'sha256/<base64 SPKI hash>' format
const pins = new Set([...ssl.pinHashes.map((hash) => `sha256/${hash}`), ...ssl.pinCertificates.map((der) => okhttp3.CertificatePinner.pin(certificateFromBase64(der)))]);
const roots = ssl.ca.map(certificateFromBase64);

switch (ssl.validation) {
case 'system': {
if (roots.length) {
const trustManager = trustManagerForRoots(roots);
builder.sslSocketFactory(sslSocketFactory(trustManager), trustManager);
}
if (pins.size) {
const pinArray = Array.create(java.lang.String, pins.size);
Array.from(pins).forEach((pin, i) => (pinArray[i] = pin));
builder.certificatePinner(new okhttp3.CertificatePinner.Builder().add(host, pinArray).build());
}
break;
}
case 'pins-only':
builder.sslSocketFactory(sslSocketFactory(acceptAnyChain), acceptAnyChain);
// Only the leaf is bound to the handshake; any other certificate in the presented chain is attacker-controlled.
builder.hostnameVerifier(hostnameVerifier((leaf) => pins.has(okhttp3.CertificatePinner.pin(leaf))));
break;
case 'none':
builder.sslSocketFactory(sslSocketFactory(acceptAnyChain), acceptAnyChain);
builder.hostnameVerifier(hostnameVerifier(() => true));
break;
}
}

export class NativeBridge extends NativeBridgeDefinition {
client!: okhttp3.OkHttpClient;
listener!: WebSocketListenerImpl;
nativeWs!: okhttp3.WebSocket;
startLooper?: android.os.Looper;
handler?: android.os.Handler;
private _restrictedCodes = new Set([1004, 1005, 1006, 1015]);
connect(url: string, protocols: string[], headers: HeaderType): void {
connect({ url, protocols, headers, ssl }: WebSocketBridgeConnectOptions): void {
this.startLooper = android.os.Looper.myLooper();
this.handler = new android.os.Handler(this.startLooper);
protocols = protocols || [];
this.client = new okhttp3.OkHttpClient.Builder()
.connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
.writeTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
.readTimeout(0, java.util.concurrent.TimeUnit.MINUTES) // Disable timeouts for read
.build();
const requestBuilder = new okhttp3.Request.Builder();
requestBuilder.url(url);

Expand All @@ -97,8 +177,16 @@ export class NativeBridge extends NativeBridgeDefinition {
}
// TODO: cookies? There isn't a default cookie jar in android/nativescript

const request = requestBuilder.build();
// readTimeout 0 disables read timeouts
const clientBuilder = new okhttp3.OkHttpClient.Builder().connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS).writeTimeout(10, java.util.concurrent.TimeUnit.SECONDS).readTimeout(0, java.util.concurrent.TimeUnit.MINUTES);
if (ssl) {
configureSsl(clientBuilder, request.url().host(), ssl);
}
this.client = clientBuilder.build();

this.listener = new WebSocketListenerImpl(this);
this.nativeWs = this.client.newWebSocket(requestBuilder.build(), this.listener);
this.nativeWs = this.client.newWebSocket(request, this.listener);
}
send(data: string | ArrayBuffer | ArrayBufferView | Blob): void {
if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
Expand Down
43 changes: 40 additions & 3 deletions packages/nativescript-websockets/bridge.ios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,42 @@
* @flow
*/

import { HeaderType } from './common';
import { NativeBridgeDefinition } from './websocket.definition';
import { ResolvedSslOptions } from './common';
import { NativeBridgeDefinition, WebSocketBridgeConnectOptions } from './websocket.definition';

// RCTSRSSLValidationMode
const VALIDATION_MODE = { system: 0, 'pins-only': 1, none: 2 } as const;

function dataFromBase64(base64: string): NSData {
return NSData.alloc().initWithBase64EncodedStringOptions(base64, 0 as NSDataBase64DecodingOptions);
}

/** Returns the certificate's public key hash; throws if the data isn't a valid certificate. */
function certificatePublicKeyHash(der: string): NSData {
const hash = RCTSRWebSocket.RCTSR_publicKeySHA256ForCertificateData(dataFromBase64(der));
if (!hash) {
throw new TypeError('Invalid certificate');
}
return hash;
}

function configureSsl(request: NSMutableURLRequest, ssl: ResolvedSslOptions) {
const pins = NSMutableArray.new<NSData>();
for (const hash of ssl.pinHashes) {
pins.addObject(dataFromBase64(hash));
}
for (const der of ssl.pinCertificates) {
pins.addObject(certificatePublicKeyHash(der));
}
const roots = NSMutableArray.new<NSData>();
for (const der of ssl.ca) {
certificatePublicKeyHash(der);
roots.addObject(dataFromBase64(der));
}
request.RCTSR_SSLValidationMode = VALIDATION_MODE[ssl.validation];
request.RCTSR_SSLPinnedPublicKeyHashes = pins;
request.RCTSR_SSLTrustedRootCertificates = roots;
}

@NativeClass
class RCTSRWebSocketDelegateImpl extends NSObject implements RCTSRWebSocketDelegate {
Expand Down Expand Up @@ -41,7 +75,7 @@ export class NativeBridge extends NativeBridgeDefinition {
// store the delegate so it isn't garbage collected
// TODO: fix the iOS runtime so we don't need this
delegate!: RCTSRWebSocketDelegateImpl;
connect(url: string, protocols: string[], headers: HeaderType) {
connect({ url, protocols, headers, ssl }: WebSocketBridgeConnectOptions): void {
const nativeUrl = NSURL.URLWithString(url);
const request = NSMutableURLRequest.requestWithURL(nativeUrl);
// NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
Expand All @@ -63,6 +97,9 @@ export class NativeBridge extends NativeBridgeDefinition {
for (const k of Object.keys(headers.headers)) {
request.addValueForHTTPHeaderField(`${headers.headers[k]}`, k);
}
if (ssl) {
configureSsl(request, ssl);
}

const webSocket = RCTSRWebSocket.alloc().initWithURLRequestProtocols(request, protocols);
this.nativeSocket = webSocket;
Expand Down
Loading
Loading