#!/bin/sh
# Validate the GlobalProtect NLB GPTC request and encrypted response wire format.
set -eu
BUILD_CONFIG=""
if test -n "${top_builddir:-}"; then
	BUILD_CONFIG="$(cd "$top_builddir" && pwd)/config.h"
fi
cd "$(dirname "$0")/.."
CC="${CC:-cc}"
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT

CFLAGS="${CFLAGS:-}"
LIBS="${LIBS:-}"
if test -n "$BUILD_CONFIG" && grep -q '^#define OPENCONNECT_GNUTLS 1' "$BUILD_CONFIG"; then
	CFLAGS="$CFLAGS -DUSE_GNUTLS $(pkg-config --cflags gnutls)"
	LIBS="$LIBS $(pkg-config --libs gnutls)"
elif pkg-config --exists openssl 2>/dev/null; then
	CFLAGS="$CFLAGS $(pkg-config --cflags openssl)"
	LIBS="$LIBS $(pkg-config --libs openssl)"
elif pkg-config --exists libssl 2>/dev/null; then
	CFLAGS="$CFLAGS $(pkg-config --cflags libssl)"
	LIBS="$LIBS $(pkg-config --libs libssl)"
else
	CFLAGS="$CFLAGS -I/usr/include -I/usr/local/include -I/opt/homebrew/include"
	LIBS="$LIBS -lcrypto -lssl"
fi

cat > "$TMP/test.c" <<'EOF'
#include <arpa/inet.h>
#ifdef USE_GNUTLS
#include <gnutls/crypto.h>
#else
#include <openssl/evp.h>
#endif
#include <stdint.h>
#include <stdio.h>
#include <string.h>

#include "gpst_nlb.h"

#define HEADER_LEN GP_NLB_CONTROL_HEADER_LEN
#define TOC_LEN 5
#define TAG_LEN 16
#define IV_LEN 12

static const char b64[] =
	"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

static void store_be16(void *p, uint16_t value)
{
	value = htons(value);
	memcpy(p, &value, sizeof(value));
}

static uint16_t load_be16(const void *p)
{
	uint16_t value;

	memcpy(&value, p, sizeof(value));
	return ntohs(value);
}

static void set_toc(unsigned char *entry, unsigned char type,
		    uint16_t offset, uint16_t len)
{
	entry[0] = type;
	store_be16(entry + 1, offset);
	store_be16(entry + 3, len);
}

static int base64_encode(const unsigned char *in, int in_len, unsigned char *out)
{
	int i, pos = 0;

	for (i = 0; i < in_len; i += 3) {
		unsigned int value = (unsigned int)in[i] << 16;

		if (i + 1 < in_len)
			value |= (unsigned int)in[i + 1] << 8;
		if (i + 2 < in_len)
			value |= in[i + 2];
		out[pos++] = b64[(value >> 18) & 0x3f];
		out[pos++] = b64[(value >> 12) & 0x3f];
		out[pos++] = i + 1 < in_len ? b64[(value >> 6) & 0x3f] : '=';
		out[pos++] = i + 2 < in_len ? b64[value & 0x3f] : '=';
	}
	return pos;
}

static int base64_value(unsigned char c)
{
	const char *p = strchr(b64, c);

	return p ? (int)(p - b64) : -1;
}

static int base64_decode(const unsigned char *in, int in_len, unsigned char *out)
{
	int i, pos = 0;

	if (in_len % 4)
		return -1;
	for (i = 0; i < in_len; i += 4) {
		int a = base64_value(in[i]);
		int b = base64_value(in[i + 1]);
		int c = in[i + 2] == '=' ? 0 : base64_value(in[i + 2]);
		int d = in[i + 3] == '=' ? 0 : base64_value(in[i + 3]);
		unsigned int value;

		if (a < 0 || b < 0 || c < 0 || d < 0)
			return -1;
		value = ((unsigned int)a << 18) | ((unsigned int)b << 12) |
			((unsigned int)c << 6) | d;
		out[pos++] = value >> 16;
		if (in[i + 2] != '=')
			out[pos++] = value >> 8;
		if (in[i + 3] != '=')
			out[pos++] = value;
	}
	return pos;
}

static int encrypt_gcm(const unsigned char *key, const unsigned char *iv,
		       const unsigned char *plain, int plain_len,
		       unsigned char *cipher, unsigned char *tag)
{
#ifdef USE_GNUTLS
	gnutls_cipher_hd_t ctx = NULL;
	gnutls_datum_t key_d = { (unsigned char *)key, 32 };
	gnutls_datum_t iv_d = { (unsigned char *)iv, IV_LEN };
	int ret;

	ret = gnutls_cipher_init(&ctx, GNUTLS_CIPHER_AES_256_GCM, &key_d, &iv_d);
	if (ret)
		return -1;
	memcpy(cipher, plain, plain_len);
	ret = gnutls_cipher_encrypt(ctx, cipher, plain_len);
	if (!ret)
		ret = gnutls_cipher_tag(ctx, tag, TAG_LEN);
	gnutls_cipher_deinit(ctx);
	return ret ? -1 : 0;
#else
	EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
	int len = 0, final_len = 0;
	int ok;

	if (!ctx)
		return -1;
	ok = EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, key, iv) == 1 &&
		EVP_EncryptUpdate(ctx, cipher, &len, plain, plain_len) == 1 &&
		EVP_EncryptFinal_ex(ctx, cipher + len, &final_len) == 1 &&
		len + final_len == plain_len &&
		EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, TAG_LEN, tag) == 1;
	EVP_CIPHER_CTX_free(ctx);
	return ok ? 0 : -1;
#endif
}

static int decrypt_gcm(const unsigned char *key, const unsigned char *iv,
		       const unsigned char *cipher, int cipher_len,
		       const unsigned char *tag, unsigned char *plain)
{
#ifdef USE_GNUTLS
	gnutls_cipher_hd_t ctx = NULL;
	gnutls_datum_t key_d = { (unsigned char *)key, 32 };
	gnutls_datum_t iv_d = { (unsigned char *)iv, IV_LEN };
	unsigned char calculated_tag[TAG_LEN];
	int ret;

	ret = gnutls_cipher_init(&ctx, GNUTLS_CIPHER_AES_256_GCM, &key_d, &iv_d);
	if (ret)
		return -1;
	memcpy(plain, cipher, cipher_len);
	ret = gnutls_cipher_decrypt(ctx, plain, cipher_len);
	if (!ret)
		ret = gnutls_cipher_tag(ctx, calculated_tag, TAG_LEN);
	gnutls_cipher_deinit(ctx);
	return ret || memcmp(calculated_tag, tag, TAG_LEN) ? -1 : 0;
#else
	EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
	int len = 0, final_len = 0;
	int ok;

	if (!ctx)
		return -1;
	ok = EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, key, iv) == 1 &&
		EVP_DecryptUpdate(ctx, plain, &len, cipher, cipher_len) == 1 &&
		EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, TAG_LEN, (void *)tag) == 1 &&
		EVP_DecryptFinal_ex(ctx, plain + len, &final_len) == 1 &&
		len + final_len == cipher_len;
	EVP_CIPHER_CTX_free(ctx);
	return ok ? 0 : -1;
#endif
}

static int check_request(void)
{
	static const unsigned char prefix[] = {
		0x00, 0x00, 0x00, 0x00, 'G', 'P', 'T', 'C',
		0x01, 0x01, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x04,
		0x01, 0x00, 0x25, 0x00, 0x03,
		0x02, 0x00, 0x28, 0x00, 0x06,
		0x04, 0x00, 0x2e, 0x00, 0x02,
		0x05, 0x00, 0x30, 0x00, 0x40
	};
	static const unsigned char hash[] =
		"75cd47bf39517f376924a519c2355292a26ce63fd04eca117fb566aa0a222b41";
	unsigned char request[112] = { 0 };
	int offset = HEADER_LEN + 4 * TOC_LEN;

	memcpy(request + 4, "GPTC", 4);
	request[8] = request[9] = 1;
	request[12] = 1;
	request[13] = 2;
	request[14] = 3;
	request[15] = 4;
	request[16] = 4;
	set_toc(request + 17, 1, offset, 3);
	memcpy(request + offset, "enc", 3);
	offset += 3;
	set_toc(request + 22, 2, offset, 6);
	memcpy(request + offset, "opaque", 6);
	offset += 6;
	set_toc(request + 27, 4, offset, 2);
	request[offset++] = 0xaa;
	request[offset++] = 0xbb;
	set_toc(request + 32, 5, offset, sizeof(hash) - 1);
	memcpy(request + offset, hash, sizeof(hash) - 1);
	offset += sizeof(hash) - 1;

	if (offset != (int)sizeof(request) || memcmp(request, prefix, sizeof(prefix)) ||
	    memcmp(request + 37, "encopaque\xaa\xbb", 11) ||
	    memcmp(request + 48, hash, sizeof(hash) - 1))
		return -1;
	return 0;
}

static int check_response(void)
{
	static const unsigned char xml[] =
		"<response status=\"success\"><ip-address>10.0.0.8</ip-address>"
		"<in-tunnel-gw-ip>10.0.0.1</in-tunnel-gw-ip></response>";
	unsigned char key[32], iv[IV_LEN], tag[TAG_LEN];
	unsigned char cipher[sizeof(xml)], block[TAG_LEN + IV_LEN + sizeof(xml)];
	unsigned char encoded[4 * ((sizeof(block) + 2) / 3) + 1];
	unsigned char decoded[sizeof(block) + 3], plain[sizeof(xml)];
	unsigned char response[HEADER_LEN + TOC_LEN + sizeof(encoded)] = { 0 };
	int encoded_len, decoded_len, cipher_len, i;

	for (i = 0; i < (int)sizeof(key); i++)
		key[i] = i;
	for (i = 0; i < (int)sizeof(iv); i++)
		iv[i] = 0xa0 + i;
	if (encrypt_gcm(key, iv, xml, sizeof(xml), cipher, tag))
		return -1;
	memcpy(block, tag, TAG_LEN);
	memcpy(block + TAG_LEN, iv, IV_LEN);
	memcpy(block + TAG_LEN + IV_LEN, cipher, sizeof(xml));
	encoded_len = base64_encode(block, sizeof(block), encoded);

	/* The issue #526 gateway replies with zero-prefixed GPTC framing
	 * rather than the alternate CTPG marker. */
	memcpy(response + 4, "GPTC", 4);
	response[16] = 1;
	set_toc(response + HEADER_LEN, 4, HEADER_LEN + TOC_LEN, encoded_len);
	memcpy(response + HEADER_LEN + TOC_LEN, encoded, encoded_len);

	if (!gp_nlb_is_tunnel_response(response, sizeof(response)) ||
	    memcmp(response + 4, "GPTC", 4) || response[16] != 1 ||
	    response[17] != 4 || load_be16(response + 18) != HEADER_LEN + TOC_LEN ||
	    load_be16(response + 20) != encoded_len)
		return -1;
	decoded_len = base64_decode(response + HEADER_LEN + TOC_LEN,
				    encoded_len, decoded);
	cipher_len = decoded_len - TAG_LEN - IV_LEN;
	if (cipher_len != (int)sizeof(xml) ||
	    decrypt_gcm(key, decoded + TAG_LEN, decoded + TAG_LEN + IV_LEN,
			cipher_len, decoded, plain) || memcmp(plain, xml, sizeof(xml)))
		return -1;
	return 0;
}

static int check_response_headers(void)
{
	unsigned char header[HEADER_LEN] = { 0 };

	memcpy(header + 4, "GPTC", 4);
	if (!gp_nlb_is_tunnel_response(header, sizeof(header)))
		return -1;

	header[3] = 1;
	if (gp_nlb_is_tunnel_response(header, sizeof(header)))
		return -1;
	memcpy(header + 4, "CTPG", 4);
	if (!gp_nlb_is_tunnel_response(header, sizeof(header)))
		return -1;

	header[3] = 0;
	memcpy(header + 4, "NONE", 4);
	if (!gp_nlb_is_tunnel_response(header, sizeof(header)) ||
	    gp_nlb_is_tunnel_response(header, HEADER_LEN - 1))
		return -1;
	return 0;
}

int main(void)
{
	if (check_request()) {
		fprintf(stderr, "GPTC request layout mismatch\n");
		return 1;
	}
	if (check_response()) {
		fprintf(stderr, "NLB response crypto/layout mismatch\n");
		return 1;
	}
	if (check_response_headers()) {
		fprintf(stderr, "NLB response header recognition mismatch\n");
		return 1;
	}
	puts("gp-nlb-control: OK");
	return 0;
}
EOF

$CC $CFLAGS -I. -o "$TMP/test" "$TMP/test.c" $LIBS
"$TMP/test"
