跳转到内容
搜索文档

配置移动应用或 IoT 设备

最后更新 查看 MarkdownAgent 设置

本教程演示如何配置物联网 (IoT) 设备和移动应用,以将客户端证书与 API Shield 配合使用。

场景详情

本演练以一台采集温度读数并通过向 Cloudflare 保护的 API 发送 POST 请求来传输数据的设备为例。一个用 Swift 为 iOS 构建的移动应用检索这些读数并显示它们。

为保持示例简单,API 实现为 Cloudflare Worker(代码借鉴自 To-Do List 教程:构建 jamstack 应用)。

温度使用源 IP 地址作为键存储在 Workers KV 中,但您可以轻松使用客户端证书中的值,例如指纹。

下面的示例 API 代码在发起 POST 时将温度和时间戳保存到 KV,并在发起 GET 请求时返回最近的五条温度记录。

const defaultData = { temperatures: [] };

const getCache = (key) => TEMPERATURES.get(key);
const setCache = (key, data) => TEMPERATURES.put(key, data);

async function addTemperature(request) {
	// Pull previously recorded temperatures for this client.
	const ip = request.headers.get("CF-Connecting-IP");
	const cacheKey = `data-${ip}`;
	let data;
	const cache = await getCache(cacheKey);
	if (!cache) {
		await setCache(cacheKey, JSON.stringify(defaultData));
		data = defaultData;
	} else {
		data = JSON.parse(cache);
	}

	// Append the recorded temperatures with the submitted reading (assuming it has both temperature and a timestamp).
	try {
		const body = await request.text();
		const val = JSON.parse(body);

		if (val.temperature && val.time) {
			data.temperatures.push(val);
			await setCache(cacheKey, JSON.stringify(data));
			return new Response("", { status: 201 });
		} else {
			return new Response(
				"Unable to parse temperature and/or timestamp from JSON POST body",
				{ status: 400 },
			);
		}
	} catch (err) {
		return new Response(err, { status: 500 });
	}
}

function compareTimestamps(a, b) {
	return -1 * (Date.parse(a.time) - Date.parse(b.time));
}

// Return the 5 most recent temperature measurements.
async function getTemperatures(request) {
	const ip = request.headers.get("CF-Connecting-IP");
	const cacheKey = `data-${ip}`;

	const cache = await getCache(cacheKey);
	if (!cache) {
		return new Response(JSON.stringify(defaultData), {
			status: 200,
			headers: { "content-type": "application/json" },
		});
	} else {
		data = JSON.parse(cache);
		const retval = JSON.stringify(
			data.temperatures.sort(compareTimestamps).splice(0, 5),
		);
		return new Response(retval, {
			status: 200,
			headers: { "content-type": "application/json" },
		});
	}
}

export default {
	async fetch(request, env, ctx) {
		return request.method === "POST"
			? addTemperature(request)
			: getTemperatures(request);
	},
};

1. 验证 API

向 API POST 示例数据

在添加 mTLS 身份验证之前验证 API,POST 一条随机温度读数:

$ TEMPERATURE=$(echo $((361 + RANDOM %11)) | awk '{printf("%.2f",$1/10.0)}')
$ TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

$ echo -e "$TEMPERATURE\n$TIMESTAMP"
36.70
2020-09-28T02:54:56Z

$ curl --verbose --header "Content-Type: application/json" --data '{"temperature":'''$TEMPERATURE''', "time": "'''$TIMESTAMP'''"}' https://shield.upinatoms.com/temps 2>&1 | grep "< HTTP/2"
< HTTP/2 201

从 API GET 示例数据

temps 端点发起 GET 请求会返回最近的读数,包括上面示例中提交的那条:

$ curl --silent https://shield.upinatoms.com/temps | jq .
[
  {
    "temperature": 36.3,
    "time": "2020-09-28T02:57:49Z"
  },
  {
    "temperature": 36.7,
    "time": "2020-09-28T02:54:56Z"
  },
  {
    "temperature": 36.2,
    "time": "2020-09-28T02:33:08Z"
  }
]

2. 创建 Cloudflare 签发的证书

在使用 API Shield 保护 API 或 Web 应用之前,请创建 Cloudflare 签发的客户端证书。

您可以在 Cloudflare 仪表板中创建客户端证书

不过,由于大多数大规模开发者通过 API 自行生成私钥和证书签名请求,本示例使用 Cloudflare API 创建客户端证书。

要为 iOS 应用和 IoT 设备创建引导证书,本示例使用 Cloudflare 的公钥基础设施工具包 CFSSL

# Generate a private key and CSR for the iOS device.

$ cat <<'EOF' | tee -a csr.json
{
    "hosts": [
        "ios-bootstrap.devices.upinatoms.com"
    ],
    "CN": "ios-bootstrap.devices.upinatoms.com",
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [{
        "C": "US",
        "L": "Austin",
        "O": "Temperature Testers, Inc.",
        "OU": "Tech Operations",
        "ST": "Texas"
    }]
}
EOF

$ cfssl genkey csr.json | cfssljson -bare certificate

2020/09/27 21:28:46 [INFO] generate received request
2020/09/27 21:28:46 [INFO] received CSR
2020/09/27 21:28:46 [INFO] generating key: rsa-2048
2020/09/27 21:28:47 [INFO] encoded CSR

$ mv certificate-key.pem ios-key.pem
$ mv certificate.csr ios.csr

# Do the same for the IoT sensor.

$ sed -i.bak 's/ios-bootstrap/sensor-001/g' csr.json
$ cfssl genkey csr.json | cfssljson -bare certificate
...
$ mv certificate-key.pem sensor-key.pem
$ mv certificate.csr sensor.csr

# now ask that these CSRs be signed by the private CA issued for your zone
# we need to replace actual newlines in the CSR with ‘\n’ before POST’ing
$ CSR=$(cat ios.csr | perl -pe 's/\n/\\n/g')
$ request_body=$(< <(cat <<EOF
{
  "validity_days": 3650,
  "csr":"$CSR"
}
EOF
))

# save the response so we can view it and then extra the certificate
$ curl https://api.cloudflare.com/client/v4/zones/{zone_id}/client_certificates \
--header "X-Auth-Email: <EMAIL>" \
--header "X-Auth-Key: <API_KEY>" \
--header "Content-Type: application/json" \
--data "$request_body" > response.json

$ cat response.json | jq .

{
  "success": true,
  "errors": [],
  "messages": [],
  "result": {
    "id": "7bf7f70c-7600-42e1-81c4-e4c0da9aa515",
    "certificate_authority": {
      "id": "8f5606d9-5133-4e53-b062-a2e5da51be5e",
      "name": "Cloudflare Managed CA for account 11cbe197c050c9e422aaa103cfe30ed8"
    },
    "certificate": "-----BEGIN CERTIFICATE-----\nMIIEkzCCA...\n-----END CERTIFICATE-----\n",
    "csr": "-----BEGIN CERTIFICATE REQUEST-----\nMIIDITCCA...\n-----END CERTIFICATE REQUEST-----\n",
    "ski": "eb2a48a19802a705c0e8a39489a71bd586638fdf",
    "serial_number": "133270673305904147240315902291726509220894288063",
    "signature": "SHA256WithRSA",
    "common_name": "ios-bootstrap.devices.upinatoms.com",
    "organization": "Temperature Testers, Inc.",
    "organizational_unit": "Tech Operations",
    "country": "US",
    "state": "Texas",
    "location": "Austin",
    "expires_on": "2030-09-26T02:41:00Z",
    "issued_on": "2020-09-28T02:41:00Z",
    "fingerprint_sha256": "84b045d498f53a59bef53358441a3957de81261211fc9b6d46b0bf5880bdaf25",
    "validity_days": 3650
  }
}

$ cat response.json | jq .result.certificate | perl -npe 's/\\n/\n/g; s/"//g' > ios.pem

# Now ask that the second client certificate signing request be signed.

$ CSR=$(cat sensor.csr | perl -pe 's/\n/\\n/g')
$ request_body=$(< <(cat <<EOF
{
  "validity_days": 3650,
  "csr":"$CSR"
}
EOF
))

$ curl https://api.cloudflare.com/client/v4/zones/{zone_id}/client_certificates \
--header "X-Auth-Email: <EMAIL>" \
--header "X-Auth-Key: <API_KEY>" \
--header "Content-Type: application/json" \
--data "$request_body" | perl -npe 's/\\n/\n/g; s/"//g' > sensor.pem

3. 在移动应用中嵌入客户端证书

要配置移动应用以安全请求 IoT 设备提交的温度数据,请在移动应用中嵌入客户端证书。

为简单起见,本示例将“引导”证书和密钥以 PKCS#12 格式文件嵌入应用包:

$ openssl pkcs12 -export -out bootstrap-cert.pfx -inkey ios-key.pem -in ios.pem
Enter Export Password:
Verifying - Enter Export Password:

在实际部署中,引导证书应仅与用户凭据结合使用,以向可返回唯一用户证书的 API 端点进行身份验证。企业用户会希望使用移动设备管理 (MDM) 分发证书。

在 Android 应用中嵌入客户端证书

以下是在 Android 应用中使用客户端证书发起 HTTP 调用的示例。您需要在 AndroidManifest.xml 中添加以下权限以允许 Internet 连接。

<uses-permission android:name="android.permission.INTERNET" />

出于演示目的,本示例中的证书存储在 app/src/main/res/raw/cert.pem,私钥存储在 app/src/main/res/raw/key.pem。您也可以用其他安全方式存储这些文件。

以下示例使用 OkHttpClient,但您也可以用类似方式使用其他客户端,例如 HttpURLConnection。关键是使用 SSLSocketFactory

private OkHttpClient setUpClient() {
    try {
        final String SECRET = "secret"; // You may also store this String somewhere more secure.
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

        // Get private key
        InputStream privateKeyInputStream = getResources().openRawResource(R.raw.key);
        byte[] privateKeyByteArray = new byte[privateKeyInputStream.available()];
        privateKeyInputStream.read(privateKeyByteArray);

        String privateKeyContent = new String(privateKeyByteArray, Charset.defaultCharset())
                .replace("-----BEGIN PRIVATE KEY-----", "")
                .replaceAll(System.lineSeparator(), "")
                .replace("-----END PRIVATE KEY-----", "");

        byte[] rawPrivateKeyByteArray = Base64.getDecoder().decode(privateKeyContent);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(rawPrivateKeyByteArray);

        // Get certificate
        InputStream certificateInputStream = getResources().openRawResource(R.raw.cert);
        Certificate certificate = certificateFactory.generateCertificate(certificateInputStream);

        // Set up KeyStore
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, SECRET.toCharArray());
        keyStore.setKeyEntry("client", keyFactory.generatePrivate(keySpec), SECRET.toCharArray(), new Certificate[]{certificate});
        certificateInputStream.close();

        // Set up Trust Managers
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

        // Set up Key Managers
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, SECRET.toCharArray());
        KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

        // Obtain SSL Socket Factory
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagers, new SecureRandom());
        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        // Finally, return the client, which will then be used to make HTTP calls.
        OkHttpClient client = new OkHttpClient.Builder()
                .sslSocketFactory(sslSocketFactory, (X509TrustManager) trustManagers[0])
                .build();

        return client;

    } catch (CertificateException | IOException | NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | KeyManagementException | InvalidKeySpecException e) {
        e.printStackTrace();
        return null;
    }
}

上述函数返回嵌入了客户端证书的 OkHttpClient。您现在可以使用此客户端向受 mTLS 保护的 API 端点发起 HTTP 请求。


4. 在 IoT 设备上嵌入客户端证书

为使 IoT 设备能够与 API 端点进行安全通信,请在设备上嵌入证书,并配置设备在发起 POST 请求时使用该证书。

本示例假设证书和私钥已安全复制到 /etc/ssl/private/sensor-key.pem/etc/ssl/certs/sensor.pem

示例脚本已修改为指向这些文件:

import requests
import json
from datetime import datetime

def readSensor():

    # Takes a reading from a temperature sensor and store it to temp_measurement

    dateTimeObj = datetime.now()
    timestampStr = dateTimeObj.strftime('%Y-%m-%dT%H:%M:%SZ')

    measurement = {'temperature':str(temp_measurement),'time':timestampStr}
    return measurement

def main():

    print("Cloudflare API Shield [IoT device demonstration]")

    temperature = readSensor()
    payload = json.dumps(temperature)

    url = 'https://shield.upinatoms.com/temps'
    json_headers = {'Content-Type': 'application/json'}
    cert_file = ('/etc/ssl/certs/sensor.pem', '/etc/ssl/private/sensor-key.pem')

    r = requests.post(url, headers = json_headers, data = payload, cert = cert_file)

    print("Request body: ", r.request.body)
    print("Response status code: %d" % r.status_code)

当脚本尝试连接到 https://shield.upinatoms.com/temps 时,Cloudflare 要求发送客户端证书,脚本会发送 /etc/ssl/certs/sensor.pem 的内容。然后,为完成 SSL/TLS 握手,脚本会证明其持有 /etc/ssl/private/sensor-key.pem

没有客户端证书时,Cloudflare 会拒绝请求:

Cloudflare API Shield [IoT device demonstration]
Request body:  {"temperature": "36.5", "time": "2020-09-28T15:52:19Z"}
Response status code: 403

当 IoT 设备出示有效的客户端证书时,POST 请求成功,温度读数被记录:

Cloudflare API Shield [IoT device demonstration]
Request body:  {"temperature": "36.5", "time": "2020-09-28T15:56:45Z"}
Response status code: 201

5. 启用 mTLS

创建 Cloudflare 签发的证书后,下一步是为要使用 API Shield 保护的主机启用 mTLS


6. 配置 API Shield 要求客户端证书

要配置 API Shield 要求客户端证书,请创建 mTLS 规则

这篇文档对您有帮助吗?