mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-19 22:46:14 -05:00
feat: prepare 3.0.0 release
This commit is contained in:
252 files changed
+26210
-7457
No files matched your search
@@ -0,0 +1,84 @@
|
||||
"""Local TLS GlobalProtect fixture accepting HIP and raw SSL tunnel setup."""
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
import threading
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
cert, key, records = sys.argv[1:]
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
context.load_cert_chain(cert, key)
|
||||
listener = socket.socket()
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
listener.listen()
|
||||
state = {"configs": 0, "checks": 0, "reports": 0}
|
||||
lock = threading.Lock()
|
||||
|
||||
|
||||
def serve(connection):
|
||||
try:
|
||||
connection.settimeout(5)
|
||||
with context.wrap_socket(connection, server_side=True) as stream:
|
||||
buffer = b""
|
||||
while True:
|
||||
while b"\r\n\r\n" not in buffer:
|
||||
data = stream.recv(4096)
|
||||
if not data:
|
||||
return
|
||||
buffer += data
|
||||
headers, buffer = buffer.split(b"\r\n\r\n", 1)
|
||||
method, path, _ = headers.split(b"\r\n", 1)[0].decode().split()
|
||||
print(f"Gateway received {method} {path.split('?')[0]}", file=sys.stderr, flush=True)
|
||||
if method == "GET" and path.startswith("/ssl-tunnel-connect.sslvpn?"):
|
||||
stream.sendall(b"START_TUNNEL")
|
||||
while stream.recv(4096):
|
||||
pass
|
||||
return
|
||||
length = 0
|
||||
for header in headers.split(b"\r\n")[1:]:
|
||||
name, value = header.split(b":", 1)
|
||||
if name.lower() == b"content-length":
|
||||
length = int(value)
|
||||
while len(buffer) < length:
|
||||
data = stream.recv(4096)
|
||||
if not data:
|
||||
raise EOFError(f"Incomplete body for {path}: {len(buffer)}/{length}")
|
||||
buffer += data
|
||||
body, buffer = buffer[:length], buffer[length:]
|
||||
form = parse_qs(body.decode())
|
||||
status = "200 OK"
|
||||
with lock:
|
||||
if path == "/ssl-vpn/getconfig.esp":
|
||||
state["configs"] += 1
|
||||
ip = "10.0.0.1"
|
||||
response = f"<response><ip-address>{ip}</ip-address><gw-address>127.0.0.1</gw-address><ssl-tunnel-url>/ssl-tunnel-connect.sslvpn</ssl-tunnel-url></response>"
|
||||
elif path == "/ssl-vpn/hipreportcheck.esp":
|
||||
state["checks"] += 1
|
||||
needed = "no" if state["checks"] == 4 else "yes"
|
||||
response = f"<response><hip-report-needed>{needed}</hip-report-needed></response>"
|
||||
elif path == "/ssl-vpn/hipreport.esp":
|
||||
state["reports"] += 1
|
||||
seq = state["reports"]
|
||||
expected_ip = "10.0.0.1"
|
||||
assert form.get("authcookie") == ["test" if seq < 3 else "refreshed"]
|
||||
expected = f'<hip seq="{seq}" ip="{expected_ip}"/>'
|
||||
assert form.get("report") == [expected], form
|
||||
assert form.get("client-ip") == [expected_ip], form
|
||||
with open(records, "a", encoding="utf-8") as output:
|
||||
output.write(expected + "\n")
|
||||
if seq == 4:
|
||||
status = "403 Forbidden"
|
||||
response = "<response/>"
|
||||
else:
|
||||
raise AssertionError(path)
|
||||
payload = response.encode()
|
||||
stream.sendall(f"HTTP/1.1 {status}\r\nContent-Length: {len(payload)}\r\nContent-Type: text/xml\r\nConnection: keep-alive\r\n\r\n".encode() + payload)
|
||||
print(f"Gateway responded {status} to {path.split('?')[0]}", file=sys.stderr, flush=True)
|
||||
except (ConnectionError, ssl.SSLError):
|
||||
pass
|
||||
|
||||
|
||||
print(listener.getsockname()[1], flush=True)
|
||||
while True:
|
||||
connection, _ = listener.accept()
|
||||
threading.Thread(target=serve, args=(connection,), daemon=True).start()
|
||||
@@ -0,0 +1,157 @@
|
||||
/* Integration harness: exercise setup and the actual connected periodic branch. */
|
||||
#include <config.h>
|
||||
#include "openconnect-internal.h"
|
||||
#include <assert.h>
|
||||
#include <stdarg.h>
|
||||
|
||||
struct state { int generated, accepted; };
|
||||
static int accept_cert(void *data, const char *reason) { return 0; }
|
||||
static void progress(void *data, int level, const char *format, ...) {
|
||||
if (level > PRG_INFO) return;
|
||||
va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args);
|
||||
}
|
||||
static int generate(void *data, const struct openconnect_gp_hip_request *request,
|
||||
const struct openconnect_gp_hip_control *control, char *output, size_t capacity, size_t *written)
|
||||
{
|
||||
struct state *state = data;
|
||||
int length;
|
||||
assert(!control->check(control->data));
|
||||
assert(!strcmp(request->client_os, "Linux"));
|
||||
assert(!strcmp(request->client_version, "6.3.3"));
|
||||
assert(!strcmp(request->host_id, "test-host"));
|
||||
assert(request->cookie && request->md5 && strlen(request->md5) == 32);
|
||||
/* Shared golden fixture with gpapi's non-tunnel HIP transport. */
|
||||
assert(!strcmp(request->md5, "20f30054f721fd212925866b5778447d"));
|
||||
if (state->generated >= 2) assert(strstr(request->cookie, "authcookie=refreshed"));
|
||||
state->generated++;
|
||||
length = snprintf(output, capacity, "<hip seq=\"%d\" ip=\"%s\"/>", state->generated, request->client_ip);
|
||||
assert(length > 0 && length < capacity);
|
||||
*written = length;
|
||||
return 0;
|
||||
}
|
||||
static void submitted(void *data, const char *report, size_t length) {
|
||||
struct state *state = data;
|
||||
assert(report && length > 0);
|
||||
state->accepted++;
|
||||
}
|
||||
static int periodic(struct openconnect_info *vpninfo) {
|
||||
int timeout = 1000;
|
||||
vpninfo->trojan_interval = 1;
|
||||
vpninfo->last_trojan = time(NULL) - 2;
|
||||
return gpst_mainloop(vpninfo, &timeout, 0);
|
||||
}
|
||||
|
||||
static int validate_script(void *data, const struct openconnect_gp_hip_control *control)
|
||||
{
|
||||
return control->check(control->data);
|
||||
}
|
||||
|
||||
static void script_registration_lifecycle(struct openconnect_info *vpninfo)
|
||||
{
|
||||
const char *environment[] = { "PATH=/usr/bin:/bin", NULL };
|
||||
char *path, **saved_environment, *cwd;
|
||||
int validator_data;
|
||||
uid_t uid = getuid();
|
||||
gid_t gid;
|
||||
|
||||
assert(!openconnect_set_gp_hip_script(vpninfo, "/bin/true", 1, uid,
|
||||
&validator_data, validate_script, environment, "/"));
|
||||
path = vpninfo->csd_wrapper;
|
||||
saved_environment = vpninfo->gp_hip_environment;
|
||||
cwd = vpninfo->gp_hip_cwd;
|
||||
gid = vpninfo->gid_csd;
|
||||
|
||||
/* A refused update must preserve the entire registered policy. */
|
||||
assert(openconnect_set_gp_hip_script(vpninfo, "/bin/false", 1, (uid_t)-1,
|
||||
NULL, NULL, NULL, NULL) < 0);
|
||||
assert(vpninfo->csd_wrapper == path);
|
||||
assert(vpninfo->gp_hip_environment == saved_environment);
|
||||
assert(vpninfo->gp_hip_cwd == cwd);
|
||||
assert(vpninfo->uid_csd_given == 1 && vpninfo->uid_csd == uid && vpninfo->gid_csd == gid);
|
||||
assert(vpninfo->gp_hip_validate == validate_script);
|
||||
assert(vpninfo->gp_hip_validate_data == &validator_data);
|
||||
|
||||
/* Re-registration may use pointers borrowed from the existing policy. */
|
||||
assert(!openconnect_set_gp_hip_script(vpninfo, path, 0, 0,
|
||||
&validator_data, validate_script, (const char *const *)saved_environment, cwd));
|
||||
assert(!strcmp(vpninfo->csd_wrapper, "/bin/true"));
|
||||
assert(!strcmp(vpninfo->gp_hip_environment[0], environment[0]));
|
||||
assert(!strcmp(vpninfo->gp_hip_cwd, "/"));
|
||||
assert(!vpninfo->uid_csd_given);
|
||||
|
||||
/* Legacy replacement must not retain another script's approval policy. */
|
||||
assert(!openconnect_setup_csd(vpninfo, uid, 1, "/bin/false"));
|
||||
assert(!strcmp(vpninfo->csd_wrapper, "/bin/false"));
|
||||
assert(vpninfo->uid_csd_given == 2 && vpninfo->uid_csd == uid && vpninfo->gid_csd == gid);
|
||||
assert(!vpninfo->gp_hip_validate && !vpninfo->gp_hip_validate_data);
|
||||
assert(!vpninfo->gp_hip_environment && !vpninfo->gp_hip_cwd);
|
||||
assert(!openconnect_set_gp_hip_script(vpninfo, NULL, 0, 0, NULL, NULL, NULL, NULL));
|
||||
assert(!vpninfo->csd_wrapper);
|
||||
}
|
||||
|
||||
static int close_count;
|
||||
static int count_session_close(struct openconnect_info *vpninfo, const char *reason)
|
||||
{
|
||||
assert(!strcmp(reason, "fixture exit"));
|
||||
close_count++;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void native_session_logout(void)
|
||||
{
|
||||
struct openconnect_info *vpninfo = openconnect_vpninfo_new("logout owner test",
|
||||
accept_cert, NULL, NULL, progress, NULL);
|
||||
const struct vpn_proto *original;
|
||||
struct vpn_proto protocol;
|
||||
assert(vpninfo);
|
||||
assert(!openconnect_set_protocol(vpninfo, "gp"));
|
||||
original = vpninfo->proto;
|
||||
protocol = *original;
|
||||
protocol.vpn_close_session = count_session_close;
|
||||
vpninfo->proto = &protocol;
|
||||
vpninfo->quit_reason = "fixture exit";
|
||||
/* All exit causes use this same mainloop cleanup path. */
|
||||
openconnect_mainloop(vpninfo, 0, 0);
|
||||
assert(close_count == 1);
|
||||
openconnect_mainloop(vpninfo, 0, 0);
|
||||
assert(close_count == 2);
|
||||
vpninfo->proto = original;
|
||||
openconnect_vpninfo_free(vpninfo);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
struct state state = {0};
|
||||
struct openconnect_info *vpninfo;
|
||||
assert(argc == 2);
|
||||
native_session_logout();
|
||||
openconnect_init_ssl();
|
||||
vpninfo = openconnect_vpninfo_new("HIP protocol test", accept_cert, NULL, NULL, progress, &state);
|
||||
assert(vpninfo);
|
||||
script_registration_lifecycle(vpninfo);
|
||||
assert(!openconnect_set_protocol(vpninfo, "gp"));
|
||||
assert(!openconnect_set_reported_os(vpninfo, "linux"));
|
||||
assert(!openconnect_parse_url(vpninfo, argv[1]));
|
||||
assert(!openconnect_set_cookie(vpninfo, "user=test&authcookie=test&persistent-cookie=persistent%2Bcookie&portal=test&domain=test&preferred-ip=192.0.2.1&preferred-ipv6=2001%3Adb8%3A%3A1&computer=test"));
|
||||
assert(!openconnect_set_gp_app_version(vpninfo, "6.3.3"));
|
||||
assert(!openconnect_set_gp_host_id(vpninfo, "test-host"));
|
||||
openconnect_disable_dtls(vpninfo);
|
||||
openconnect_set_gp_hip_generator(vpninfo, &state, generate);
|
||||
openconnect_set_gp_hip_report_callback(vpninfo, &state, submitted);
|
||||
assert(!openconnect_make_cstp_connection(vpninfo));
|
||||
assert(vpninfo->ssl_fd >= 0 && state.generated == 1 && state.accepted == 1);
|
||||
assert(!periodic(vpninfo));
|
||||
assert(state.generated == 2 && state.accepted == 2);
|
||||
/* A real reconnect re-fetches configuration and uses refreshed session inputs. */
|
||||
openconnect_close_https(vpninfo, 0);
|
||||
assert(!openconnect_set_cookie(vpninfo, "user=test&authcookie=refreshed&persistent-cookie=persistent%2Bcookie&portal=test&domain=test&preferred-ip=192.0.2.2&preferred-ipv6=2001%3Adb8%3A%3A2&computer=test"));
|
||||
assert(!openconnect_make_cstp_connection(vpninfo));
|
||||
assert(state.generated == 3 && state.accepted == 3);
|
||||
/* Fourth gateway check says no report needed. */
|
||||
assert(!periodic(vpninfo));
|
||||
assert(state.generated == 3 && state.accepted == 3);
|
||||
/* Fifth submission is rejected; observer must not see it. */
|
||||
assert(periodic(vpninfo));
|
||||
assert(state.generated == 4 && state.accepted == 3);
|
||||
openconnect_vpninfo_free(vpninfo);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
use std::{
|
||||
fs,
|
||||
io::{BufRead, BufReader},
|
||||
os::unix::process::CommandExt,
|
||||
path::PathBuf,
|
||||
process::{Child, Command, Stdio},
|
||||
sync::mpsc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
struct ChildGuard(Child);
|
||||
impl Drop for ChildGuard {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
libc::kill(-(self.0.id() as i32), libc::SIGKILL);
|
||||
}
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
struct TestDirectory(PathBuf);
|
||||
impl Drop for TestDirectory {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn c_protocol_submits_initial_periodic_and_reconnect_reports() {
|
||||
let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let build = PathBuf::from(env!("OPENCONNECT_PROTOCOL_BUILD"));
|
||||
let source = PathBuf::from(env!("OPENCONNECT_PROTOCOL_SOURCE"));
|
||||
let directory = TestDirectory(std::env::temp_dir().join(format!("gp-hip-protocol-{}", std::process::id())));
|
||||
fs::create_dir(&directory.0).unwrap();
|
||||
let executable = directory.0.join("hip-protocol");
|
||||
let flags = Command::new("pkg-config")
|
||||
.args([
|
||||
"--cflags",
|
||||
"libxml-2.0",
|
||||
if cfg!(target_os = "macos") { "openssl" } else { "gnutls" },
|
||||
])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(flags.status.success());
|
||||
let compile_command = Command::new(build.join("libtool"))
|
||||
.args(["--mode=link", "cc"])
|
||||
.arg(manifest.join("tests/hip_protocol.c"))
|
||||
.arg("-I")
|
||||
.arg(&build)
|
||||
.arg("-I")
|
||||
.arg(&source)
|
||||
.arg("-I")
|
||||
.arg(source.join("json"))
|
||||
.args(String::from_utf8(flags.stdout).unwrap().split_whitespace())
|
||||
.arg(build.join("libopenconnect.la"))
|
||||
.arg("-o")
|
||||
.arg(&executable)
|
||||
.process_group(0)
|
||||
.stdout(Stdio::from(fs::File::create(directory.0.join("compile.log")).unwrap()))
|
||||
.stderr(Stdio::from(
|
||||
fs::File::options()
|
||||
.append(true)
|
||||
.open(directory.0.join("compile.log"))
|
||||
.unwrap(),
|
||||
))
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut compile_command = ChildGuard(compile_command);
|
||||
wait_bounded(
|
||||
&mut compile_command,
|
||||
Duration::from_secs(30),
|
||||
&directory.0.join("compile.log"),
|
||||
);
|
||||
let records = directory.0.join("submissions");
|
||||
let certificates = manifest.join("deps/openconnect/tests/certs");
|
||||
let server = Command::new("python3")
|
||||
.arg(manifest.join("tests/hip_gateway.py"))
|
||||
.arg(certificates.join("server-cert.pem"))
|
||||
.arg(certificates.join("server-key.pem"))
|
||||
.arg(&records)
|
||||
.process_group(0)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut server = ChildGuard(server);
|
||||
let stdout = server.0.stdout.take().unwrap();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let reader = std::thread::spawn(move || {
|
||||
let mut port = String::new();
|
||||
let result = BufReader::new(stdout).read_line(&mut port).map(|_| port);
|
||||
let _ = tx.send(result);
|
||||
});
|
||||
let port = match rx.recv_timeout(Duration::from_secs(3)) {
|
||||
Ok(result) => result.expect("Fake gateway startup failed"),
|
||||
Err(error) => {
|
||||
let _ = server.0.kill();
|
||||
let _ = server.0.wait();
|
||||
let _ = reader.join();
|
||||
panic!("Fake gateway startup timed out: {error}");
|
||||
}
|
||||
};
|
||||
reader.join().unwrap();
|
||||
let port: u16 = port.trim().parse().expect("Fake gateway did not start");
|
||||
let log = fs::File::create(directory.0.join("client.log")).unwrap();
|
||||
let mut client = ChildGuard(
|
||||
Command::new(build.join("libtool"))
|
||||
.args(["--mode=execute"])
|
||||
.arg(executable)
|
||||
.arg(format!("https://127.0.0.1:{port}"))
|
||||
.process_group(0)
|
||||
.stdout(log.try_clone().unwrap())
|
||||
.stderr(log)
|
||||
.spawn()
|
||||
.unwrap(),
|
||||
);
|
||||
wait_bounded(&mut client, Duration::from_secs(15), &directory.0.join("client.log"));
|
||||
let reports = fs::read_to_string(records).unwrap();
|
||||
assert_eq!(
|
||||
reports,
|
||||
"<hip seq=\"1\" ip=\"10.0.0.1\"/>\n<hip seq=\"2\" ip=\"10.0.0.1\"/>\n<hip seq=\"3\" ip=\"10.0.0.1\"/>\n<hip seq=\"4\" ip=\"10.0.0.1\"/>\n"
|
||||
);
|
||||
}
|
||||
|
||||
fn wait_bounded(child: &mut ChildGuard, timeout: Duration, log: &std::path::Path) {
|
||||
let deadline = Instant::now() + timeout;
|
||||
loop {
|
||||
if let Some(status) = child.0.try_wait().unwrap() {
|
||||
assert!(status.success(), "{}", fs::read_to_string(log).unwrap());
|
||||
return;
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"HIP protocol test process timed out: {}",
|
||||
fs::read_to_string(log).unwrap()
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user