Commit 904942bc authored by Petr Špaček's avatar Petr Špaček

Merge branch 'ci-pytests-new-proxy' into 'master'

pytests: update proxy + test_random_close

See merge request !732
parents 7809ecd1 7d8ff621
Pipeline #44677 passed with stages
in 17 minutes and 24 seconds
...@@ -61,6 +61,8 @@ _obj ...@@ -61,6 +61,8 @@ _obj
/tests/test_zonecut /tests/test_zonecut
/tests/dnstap/src/dnstap-test/vendor/github.com/ /tests/dnstap/src/dnstap-test/vendor/github.com/
/tests/dnstap/src/github.com/ /tests/dnstap/src/github.com/
/tests/pytests/*/tcproxy
/tests/pytests/*/tlsproxy
.pytest_cache .pytest_cache
kresd.amalg.c kresd.amalg.c
libkres.amalg.c libkres.amalg.c
......
image: $CI_REGISTRY/knot/knot-resolver/ci/debian-stable:knot-2.7
variables: variables:
DEBIAN_FRONTEND: noninteractive DEBIAN_FRONTEND: noninteractive
LC_ALL: C.UTF-8 LC_ALL: C.UTF-8
...@@ -11,6 +9,9 @@ variables: ...@@ -11,6 +9,9 @@ variables:
RESPDIFF_COUNT: 1 RESPDIFF_COUNT: 1
RESPDIFF_FORCE: 0 RESPDIFF_FORCE: 0
RESPERF_FORCE: 0 RESPERF_FORCE: 0
KNOT_VERSION: '2.7'
image: $CI_REGISTRY/knot/knot-resolver/ci/debian-buster:knot-$KNOT_VERSION
stages: stages:
- build - build
...@@ -52,7 +53,7 @@ lint:pedantic: ...@@ -52,7 +53,7 @@ lint:pedantic:
dependencies: [] # do not download build artifacts dependencies: [] # do not download build artifacts
except: except:
- master - master
image: $CI_REGISTRY/knot/knot-resolver/ci/debian-unstable:knot-2.7 # newer Debian for newer compilers image: $CI_REGISTRY/knot/knot-resolver/ci/debian-unstable:knot-$KNOT_VERSION # newer Debian for newer compilers
variables: variables:
CFLAGS: -Werror -Wall -Wpedantic -ggdb -std=gnu11 CFLAGS: -Werror -Wall -Wpedantic -ggdb -std=gnu11
script: script:
...@@ -97,7 +98,7 @@ lint:c: ...@@ -97,7 +98,7 @@ lint:c:
stage: test stage: test
except: except:
- master - master
image: $CI_REGISTRY/knot/knot-resolver/ci/debian-unstable:knot-2.7 # newer Debian for newer Clang image: $CI_REGISTRY/knot/knot-resolver/ci/debian-unstable:knot-$KNOT_VERSION # newer Debian for newer Clang
dependencies: [] # do not download build artifacts dependencies: [] # do not download build artifacts
script: script:
- make lint-c CLANG_TIDY="clang-tidy -quiet" - make lint-c CLANG_TIDY="clang-tidy -quiet"
...@@ -108,7 +109,7 @@ lint:clang-scan-build: ...@@ -108,7 +109,7 @@ lint:clang-scan-build:
stage: test stage: test
except: except:
- master - master
image: $CI_REGISTRY/knot/knot-resolver/ci/debian-unstable:knot-2.7 # newer Debian for newer Clang image: $CI_REGISTRY/knot/knot-resolver/ci/debian-unstable:knot-$KNOT_VERSION # newer Debian for newer Clang
dependencies: [] # do not download build artifacts dependencies: [] # do not download build artifacts
script: script:
- MAKEFLAGS="-k -j$(nproc)" SCAN_BUILD="scan-build -o scan-results --status-bugs -no-failure-reports" ./tests/clang_scan_build.sh make || true - MAKEFLAGS="-k -j$(nproc)" SCAN_BUILD="scan-build -o scan-results --status-bugs -no-failure-reports" ./tests/clang_scan_build.sh make || true
...@@ -162,6 +163,8 @@ docker:build: ...@@ -162,6 +163,8 @@ docker:build:
installcheck:linux:amd64: installcheck:linux:amd64:
# TODO use debian-buster once lua packet resize issue is resolved
image: $CI_REGISTRY/knot/knot-resolver/ci/debian-stable:knot-$KNOT_VERSION
stage: test stage: test
except: except:
- master - master
...@@ -300,9 +303,7 @@ pytests:run: ...@@ -300,9 +303,7 @@ pytests:run:
except: except:
- master - master
script: script:
- pushd tests/pytests/rehandshake - pushd tests/pytests/proxy && make all && popd
- make all
- popd
- PATH="$PREFIX/sbin:$PATH" ./ci/pytests/run.sh &> pytests.log.txt - PATH="$PREFIX/sbin:$PATH" ./ci/pytests/run.sh &> pytests.log.txt
after_script: after_script:
- tail -1 pytests.log.txt - tail -1 pytests.log.txt
......
FROM debian:buster-20181226
MAINTAINER Knot Resolver <knot-resolver@labs.nic.cz>
ARG KNOT_BRANCH=2.7
WORKDIR /root
CMD ["/bin/bash"]
# generic cleanup
RUN apt-get update -qq
# TODO: run upgrade once buster reaches a stable release
# RUN apt-get upgrade -y -qqq
# Knot and Knot Resolver dependecies
RUN apt-get install -y -qqq git make cmake pkg-config build-essential bsdmainutils libtool autoconf liburcu-dev libgnutls28-dev libedit-dev liblmdb-dev libcap-ng-dev libsystemd-dev libidn11-dev protobuf-c-compiler libfstrm-dev libuv1-dev libcmocka-dev libluajit-5.1-dev lua-sec lua-socket lua-http
# documentation dependecies
RUN apt-get install -y -qqq doxygen python3-sphinx python3-breathe python3-sphinx-rtd-theme
# Python packags required for Deckard CI
# Python: grab latest versions from PyPi
# (dnspython and Augeas binding in Debian packages are slow and buggy)
RUN apt-get install -y -qqq python3-pip wget augeas-tools
RUN pip3 install --upgrade pip
RUN pip3 install pylint
RUN pip3 install pep8
RUN pip3 install pytest-xdist
# tests/pytest dependencies
RUN pip3 install dnspython jinja2 pytest pytest-html pytest-xdist
# C dependencies for python-augeas
RUN apt-get install -y -qqq libaugeas-dev libffi-dev
# Python dependencies for Deckard
RUN wget https://gitlab.labs.nic.cz/knot/deckard/raw/master/requirements.txt -O /tmp/deckard-req.txt
RUN pip3 install -r /tmp/deckard-req.txt
# build and install latest version of Knot DNS
# (kresd depends on libknot and libdnssec)
RUN git clone --depth=1 --branch=$KNOT_BRANCH https://gitlab.labs.nic.cz/knot/knot-dns.git /tmp/knot
WORKDIR /tmp/knot
RUN pwd
RUN autoreconf -if
RUN ./configure --prefix=/usr
RUN make
RUN make install
RUN ldconfig
# Valgrind for kresd CI
RUN apt-get install valgrind -y -qqq
RUN wget https://raw.githubusercontent.com/LuaJIT/LuaJIT/v2.0.4/src/lj.supp -O /lj.supp
# TODO: rebuild LuaJIT with Valgrind support
# Lua lint for kresd CI
RUN apt-get install luarocks -y -qqq
RUN luarocks install luacheck
# respdiff for kresd CI
RUN apt-get install lmdb-utils -y -qqq
RUN git clone --depth=1 https://gitlab.labs.nic.cz/knot/respdiff /var/opt/respdiff
RUN pip3 install -r /var/opt/respdiff/requirements.txt
# Python static analysis for respdiff
RUN pip3 install mypy
RUN pip3 install flake8
# Python requests for CI scripts
RUN pip3 install requests
# Unbound for respdiff
RUN apt-get install unbound unbound-anchor -y -qqq
RUN printf "server:\n interface: 127.0.0.1@53535\n use-syslog: yes\n do-ip6: no\nremote-control:\n control-enable: no\n" >> /etc/unbound/unbound.conf
# BIND for respdiff
RUN apt-get install bind9 -y -qqq
RUN printf '\nOPTIONS="-4 $OPTIONS"' >> /etc/default/bind9
RUN printf 'options {\n directory "/var/cache/bind";\n listen-on port 53533 { 127.0.0.1; };\n listen-on-v6 port 53533 { ::1; };\n};\n' > /etc/bind/named.conf.options
# PowerDNS Recursor for Deckard CI
RUN apt-get install pdns-recursor -y -qqq
# code coverage
RUN apt-get install -y -qqq lcov
RUN luarocks install luacov
# LuaJIT binary for stand-alone scripting
RUN apt-get install -y -qqq luajit
# OpenBuildService CLI tool
RUN apt-get install -y osc
# curl (API)
RUN apt-get install -y curl
...@@ -48,7 +48,7 @@ Forward = namedtuple('Forward', ['proto', 'ip', 'port', 'hostname', 'ca_file']) ...@@ -48,7 +48,7 @@ Forward = namedtuple('Forward', ['proto', 'ip', 'port', 'hostname', 'ca_file'])
class Kresd(ContextDecorator): class Kresd(ContextDecorator):
def __init__( def __init__(
self, workdir, port=None, tls_port=None, ip=None, ip6=None, certname=None, self, workdir, port=None, tls_port=None, ip=None, ip6=None, certname=None,
verbose=True, hints=None, forward=None): verbose=True, hints=None, forward=None, policy_test_pass=False):
if ip is None and ip6 is None: if ip is None and ip6 is None:
raise ValueError("IPv4 or IPv6 must be specified!") raise ValueError("IPv4 or IPv6 must be specified!")
self.workdir = str(workdir) self.workdir = str(workdir)
...@@ -62,6 +62,7 @@ class Kresd(ContextDecorator): ...@@ -62,6 +62,7 @@ class Kresd(ContextDecorator):
self.verbose = verbose self.verbose = verbose
self.hints = {} if hints is None else hints self.hints = {} if hints is None else hints
self.forward = forward self.forward = forward
self.policy_test_pass = policy_test_pass
if certname: if certname:
self.tls_cert_path = os.path.join(CERTS_DIR, certname + '.cert.pem') self.tls_cert_path = os.path.join(CERTS_DIR, certname + '.cert.pem')
...@@ -160,7 +161,7 @@ class Kresd(ContextDecorator): ...@@ -160,7 +161,7 @@ class Kresd(ContextDecorator):
continue continue
finally: finally:
sock.close() sock.close()
raise RuntimeError("Kresd didn't start in time") raise RuntimeError("Kresd didn't start in time {}".format(dest))
def socket_dest(self, family, tls=False): def socket_dest(self, family, tls=False):
port = self.tls_port if tls else self.port port = self.tls_port if tls else self.port
...@@ -297,9 +298,7 @@ KRESD_LOG_IO_CLOSE = re.compile(r'^\[io\].*closed by peer.*') ...@@ -297,9 +298,7 @@ KRESD_LOG_IO_CLOSE = re.compile(r'^\[io\].*closed by peer.*')
@contextmanager @contextmanager
def make_kresd( def make_kresd(workdir, certname=None, ip='127.0.0.1', ip6='::1', **kwargs):
workdir, certname=None, ip='127.0.0.1', ip6='::1', forward=None, hints=None, with Kresd(workdir, ip=ip, ip6=ip6, certname=certname, **kwargs) as kresd:
port=None, tls_port=None):
with Kresd(workdir, port, tls_port, ip, ip6, certname, forward=forward, hints=hints) as kresd:
yield kresd yield kresd
print(kresd.partial_log()) print(kresd.partial_log())
from contextlib import contextmanager, ContextDecorator
import os
import subprocess
from typing import Any, Dict, Optional
import dns
import dns.rcode
import pytest
from kresd import CERTS_DIR, Forward, Kresd, make_kresd, make_port, PYTESTS_DIR
import utils
HINTS = {
'0.foo.': '127.0.0.1',
'1.foo.': '127.0.0.1',
'2.foo.': '127.0.0.1',
'3.foo.': '127.0.0.1',
}
def resolve_hint(sock, qname):
buff, msgid = utils.get_msgbuff(qname)
sock.sendall(buff)
answer = utils.receive_parse_answer(sock)
assert answer.id == msgid
assert answer.rcode() == dns.rcode.NOERROR
assert answer.answer[0][0].address == HINTS[qname]
class Proxy(ContextDecorator):
PATH = ''
def __init__(
self,
local_ip: str = '127.0.0.1',
local_port: Optional[int] = None,
upstream_ip: str = '127.0.0.1',
upstream_port: Optional[int] = None
) -> None:
self.local_ip = local_ip
self.local_port = local_port
self.upstream_ip = upstream_ip
self.upstream_port = upstream_port
self.proxy = None
def get_args(self):
args = []
args.append('--local')
args.append(self.local_ip)
if self.local_port is not None:
args.append('--lport')
args.append(str(self.local_port))
args.append('--upstream')
args.append(self.upstream_ip)
if self.upstream_port is not None:
args.append('--uport')
args.append(str(self.upstream_port))
return args
def __enter__(self):
if not os.path.exists(self.PATH):
pytest.skip("proxy executable '{}' not found (did you compile it?)".format(self.PATH))
cwd, cmd = os.path.split(self.PATH)
cmd = './' + cmd
args = [cmd] + self.get_args()
print(' '.join(args))
self.proxy = subprocess.Popen(
args, cwd=cwd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return self
def __exit__(self, exc_type, exc_value, traceback):
if self.proxy is not None:
self.proxy.terminate()
self.proxy = None
class TLSProxy(Proxy):
PATH = os.path.join(PYTESTS_DIR, 'proxy', 'tlsproxy')
def __init__(
self,
local_ip: str = '127.0.0.1',
local_port: Optional[int] = None,
upstream_ip: str = '127.0.0.1',
upstream_port: Optional[int] = None,
certname: Optional[str] = 'tt',
close: Optional[int] = None,
rehandshake: bool = False,
force_tls13: bool = False
) -> None:
super().__init__(local_ip, local_port, upstream_ip, upstream_port)
if certname is not None:
self.cert_path = os.path.join(CERTS_DIR, certname + '.cert.pem')
self.key_path = os.path.join(CERTS_DIR, certname + '.key.pem')
else:
self.cert_path = None
self.key_path = None
self.close = close
self.rehandshake = rehandshake
self.force_tls13 = force_tls13
def get_args(self):
args = super().get_args()
if self.cert_path is not None:
args.append('--cert')
args.append(self.cert_path)
if self.key_path is not None:
args.append('--key')
args.append(self.key_path)
if self.close is not None:
args.append('--close')
args.append(str(self.close))
if self.rehandshake:
args.append('--rehandshake')
if self.force_tls13:
args.append('--tls13')
return args
@contextmanager
def kresd_tls_client(
workdir: str,
proxy: TLSProxy,
kresd_tls_client_kwargs: Optional[Dict[Any, Any]] = None,
kresd_fwd_target_kwargs: Optional[Dict[Any, Any]] = None
) -> Kresd:
"""kresd_tls_client --(tls)--> tlsproxy --(tcp)--> kresd_fwd_target"""
ALLOWED_IPS = {'127.0.0.1', '::1'}
assert proxy.local_ip in ALLOWED_IPS, "only localhost IPs supported for proxy"
assert proxy.upstream_ip in ALLOWED_IPS, "only localhost IPs are supported for proxy"
if kresd_tls_client_kwargs is None:
kresd_tls_client_kwargs = dict()
if kresd_fwd_target_kwargs is None:
kresd_fwd_target_kwargs = dict()
# run forward target instance
dir1 = os.path.join(workdir, 'kresd_fwd_target')
os.makedirs(dir1)
with make_kresd(dir1, hints=HINTS, **kresd_fwd_target_kwargs) as kresd_fwd_target:
sock = kresd_fwd_target.ip_tcp_socket()
resolve_hint(sock, list(HINTS.keys())[0])
proxy.local_port = make_port('127.0.0.1', '::1')
proxy.upstream_port = kresd_fwd_target.port
with proxy:
# run test kresd instance
dir2 = os.path.join(workdir, 'kresd_tls_client')
os.makedirs(dir2)
forward = Forward(
proto='tls', ip=proxy.local_ip, port=proxy.local_port,
hostname='transport-test-server.com', ca_file=proxy.cert_path)
with make_kresd(dir2, forward=forward, **kresd_tls_client_kwargs) as kresd:
yield kresd
CC=gcc CC=gcc
CFLAGS_TLS=-DDEBUG -ggdb3 -O0 -lgnutls -luv CFLAGS_TLS=-DDEBUG -ggdb3 -O0 -lgnutls -luv -lasan -fsanitize=address -fno-omit-frame-pointer
CFLAGS_TCP=-DDEBUG -ggdb3 -O0 -luv
all: tcproxy tlsproxy all: tlsproxy
tlsproxy: tls-proxy.o tlsproxy.o tlsproxy: tls-proxy.o tlsproxy.o
$(CC) tls-proxy.o tlsproxy.o -o tlsproxy $(CFLAGS_TLS) $(CC) tls-proxy.o tlsproxy.o -o tlsproxy $(CFLAGS_TLS)
...@@ -13,16 +12,7 @@ tls-proxy.o: tls-proxy.c tls-proxy.h array.h ...@@ -13,16 +12,7 @@ tls-proxy.o: tls-proxy.c tls-proxy.h array.h
tlsproxy.o: tlsproxy.c tls-proxy.h tlsproxy.o: tlsproxy.c tls-proxy.h
$(CC) -c -o $@ $< $(CFLAGS_TLS) $(CC) -c -o $@ $< $(CFLAGS_TLS)
tcproxy: tcp-proxy.o tcproxy.o
$(CC) tcp-proxy.o tcproxy.o -o tcproxy $(CFLAGS_TCP)
tcp-proxy.o: tcp-proxy.c tcp-proxy.h array.h
$(CC) -c -o $@ $< $(CFLAGS_TCP)
tcproxy.o: tcproxy.c tcp-proxy.h
$(CC) -c -o $@ $< $(CFLAGS_TCP)
clean: clean:
rm -f tcp-proxy.o tcproxy.o tcproxy tls-proxy.o tlsproxy.o tlsproxy rm -f tls-proxy.o tlsproxy.o tlsproxy
.PHONY: all clean .PHONY: all clean
This diff is collapsed.
#pragma once #pragma once
#include <stdint.h>
#include <stdbool.h>
#include <netinet/in.h>
struct args {
const char *local_addr;
uint16_t local_port;
const char *upstream;
uint16_t upstream_port;
bool rehandshake;
bool close_connection;
bool accept_only;
bool tls_13;
uint64_t close_timeout;
uint32_t max_conn_sequence;
const char *cert_file;
const char *key_file;
};
struct tls_proxy_ctx; struct tls_proxy_ctx;
struct tls_proxy_ctx *tls_proxy_allocate(); struct tls_proxy_ctx *tls_proxy_allocate();
void tls_proxy_free(struct tls_proxy_ctx *proxy); void tls_proxy_free(struct tls_proxy_ctx *proxy);
int tls_proxy_init(struct tls_proxy_ctx *proxy, int tls_proxy_init(struct tls_proxy_ctx *proxy, const struct args *a);
const char *server_addr, int server_port,
const char *upstream_addr, int upstream_port,
const char *cert_file, const char *key_file);
int tls_proxy_start_listen(struct tls_proxy_ctx *proxy); int tls_proxy_start_listen(struct tls_proxy_ctx *proxy);
int tls_proxy_run(struct tls_proxy_ctx *proxy); int tls_proxy_run(struct tls_proxy_ctx *proxy);
#include <stdio.h>
#include <getopt.h>
#include <stdlib.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <gnutls/gnutls.h>
#include "tls-proxy.h"
static char default_local_addr[] = "127.0.0.1";
static char default_upstream_addr[] = "127.0.0.1";
static char default_cert_path[] = "../certs/tt.cert.pem";
static char default_key_path[] = "../certs/tt.key.pem";
void help(char *argv[], struct args *a)
{
printf("Usage: %s [parameters] [rundir]\n", argv[0]);
printf("\nParameters:\n"
" -l, --local=[addr] Server address to bind to (default: %s).\n"
" -p, --lport=[port] Server port to bind to (default: %u).\n"
" -u, --upstream=[addr] Upstream address (default: %s).\n"
" -d, --uport=[port] Upstream port (default: %u).\n"
" -t, --cert=[path] Path to certificate file (default: %s).\n"
" -k, --key=[path] Path to key file (default: %s).\n"
" -c, --close=[N] Close connection to client after\n"
" every N ms (default: %li).\n"
" -f, --fail=[N] Delay every Nth incoming connection by 10 sec,\n"
" 0 disables delaying (default: 0).\n"
" -r, --rehandshake Do TLS rehandshake after every 8 bytes\n"
" sent to the client (default: no).\n"
" -a, --acceptonly Accept incoming connections, but don't\n"
" connect to upstream (default: no).\n"
" -v, --tls13 Force use of TLSv1.3. If not turned on,\n"
" TLSv1.2 will be used (default: no).\n"
,
a->local_addr, a->local_port,
a->upstream, a->upstream_port,
a->cert_file, a->key_file,
a->close_timeout);
}
void init_args(struct args *a)
{
a->local_addr = default_local_addr;
a->local_port = 54000;
a->upstream = default_upstream_addr;
a->upstream_port = 53000;
a->cert_file = default_cert_path;
a->key_file = default_key_path;
a->rehandshake = false;
a->accept_only = false;
a->tls_13 = false;
a->close_connection = false;
a->close_timeout = 1000;
a->max_conn_sequence = 0; /* disabled */
}
int main(int argc, char **argv)
{
long int li_value = 0;
int c = 0, li = 0;
struct option opts[] = {
{"local", required_argument, 0, 'l'},
{"lport", required_argument, 0, 'p'},
{"upstream", required_argument, 0, 'u'},
{"uport", required_argument, 0, 'd'},
{"cert", required_argument, 0, 't'},
{"key", required_argument, 0, 'k'},
{"close", required_argument, 0, 'c'},
{"fail", required_argument, 0, 'f'},
{"rehandshake", no_argument, 0, 'r'},
{"acceptonly", no_argument, 0, 'a'},
#if GNUTLS_VERSION_NUMBER >= 0x030604
{"tls13", no_argument, 0, 'v'},
#endif
{0, 0, 0, 0}
};
struct args args;
init_args(&args);
while ((c = getopt_long(argc, argv, "l:p:u:d:t:k:c:f:rav", opts, &li)) != -1) {
switch (c)
{
case 'l':
args.local_addr = optarg;
break;
case 'u':
args.upstream = optarg;
break;
case 't':
args.cert_file = optarg;
break;
case 'k':
args.key_file = optarg;
break;
case 'p':
li_value = strtol(optarg, NULL, 10);
if (li_value <= 0 || li_value > UINT16_MAX) {
printf("error: '-p' requires a positive"
" number less or equal to 65535, not '%s'\n", optarg);
return -1;
}
args.local_port = (uint16_t)li_value;
break;
case 'd':
li_value = strtol(optarg, NULL, 10);
if (li_value <= 0 || li_value > UINT16_MAX) {
printf("error: '-d' requires a positive"
" number less or equal to 65535, not '%s'\n", optarg);
return -1;
}
args.upstream_port = (uint16_t)li_value;
break;
case 'c':
li_value = strtol(optarg, NULL, 10);
if (li_value <= 0) {
printf("[system] error '-c' requires a positive"
" number, not '%s'\n", optarg);
return -1;
}
args.close_connection = true;
args.close_timeout = li_value;
break;
case 'f':
li_value = strtol(optarg, NULL, 10);
if (li_value <= 0 || li_value > UINT32_MAX) {
printf("error: '-f' requires a positive"
" number less or equal to %i, not '%s'\n",
UINT32_MAX, optarg);
return -1;
}
args.max_conn_sequence = (uint32_t)li_value;
break;
case 'r':
args.rehandshake = true;
break;
case 'a':
args.accept_only = true;
break;
case 'v':
#if GNUTLS_VERSION_NUMBER >= 0x030604
args.tls_13 = true;
#endif
break;
default:
init_args(&args);
help(argv, &args);
return -1;
}
}
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
fprintf(stderr, "failed to set up SIGPIPE handler to ignore(%s)\n",
strerror(errno));
}
struct tls_proxy_ctx *proxy = tls_proxy_allocate();
if (!proxy) {
fprintf(stderr, "can't allocate tls_proxy structure\n");
return 1;
}
int res = tls_proxy_init(proxy, &args);
if (res) {
fprintf(stderr, "can't initialize tls_proxy structure\n");
return res;
}
res = tls_proxy_start_listen(proxy);
if (res) {
fprintf(stderr, "error starting listen, error code: %i\n", res);
return res;
}
fprintf(stdout, "Listen on %s#%u\n"
"Upstream is expected on %s#%u\n"
"Certificate file %s\n"
"Key file %s\n"
"Rehandshake %s\n"
"Close %s\n"
"Refuse incoming connections every %ith%s\n"
"Only accept, don't forward %s\n"
"Force TLSv1.3 %s\n"
,
args.local_addr, args.local_port,
args.upstream, args.upstream_port,
args.cert_file, args.key_file,
args.rehandshake ? "yes" : "no",
args.close_connection ? "yes" : "no",
args.max_conn_sequence, args.max_conn_sequence ? "" : " (disabled)",
args.accept_only ? "yes" : "no",
#if GNUTLS_VERSION_NUMBER >= 0x030604
args.tls_13 ? "yes" : "no"
#else
"Not supported"
#endif
);
res = tls_proxy_run(proxy);
tls_proxy_free(proxy);
return res;
}
from contextlib import contextmanager
import os
import subprocess
import dns
import dns.rcode
from kresd import CERTS_DIR
import utils
HINTS = {
'0.foo.': '127.0.0.1',
'1.foo.': '127.0.0.1',
'2.foo.': '127.0.0.1',
'3.foo.': '127.0.0.1',
}
PROXY_CA_FILE = os.path.join(CERTS_DIR, 'tt.cert.pem')
def resolve_hint(sock, qname):
buff, msgid = utils.get_msgbuff(qname)
sock.sendall(buff)
answer = utils.receive_parse_answer(sock)
assert answer.id == msgid
assert answer.rcode() == dns.rcode.NOERROR
assert answer.answer[0][0].address == HINTS[qname]
@contextmanager
def proxy(path):
cwd, cmd = os.path.split(path)
cmd = './' + cmd
try:
proxy = subprocess.Popen(
[cmd], cwd=cwd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
yield proxy
finally:
proxy.terminate()