Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Demo: Offer TLS settings for remote connections #338

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
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
140 changes: 109 additions & 31 deletions internal/examples/agent/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ type Agent struct {
agentType string
agentVersion string

// use insecure connection until offered settings has a CA
awaitCA bool

effectiveConfig string

instanceId uuid.UUID
Expand All @@ -66,45 +69,55 @@ type Agent struct {
// certificate is used.
opampClientCert *tls.Certificate

tls *tls.Config

certRequested bool
clientPrivateKeyPEM []byte
}

func NewAgent(logger types.Logger, agentType string, agentVersion string) *Agent {
func NewAgent(logger types.Logger, agentType string, agentVersion string, awaitCA bool) *Agent {
agent := &Agent{
effectiveConfig: localConfig,
logger: logger,
agentType: agentType,
agentVersion: agentVersion,
awaitCA: awaitCA,
tls: &tls.Config{},
}

agent.createAgentIdentity()
agent.logger.Debugf(context.Background(), "Agent starting, id=%v, type=%s, version=%s.",
agent.instanceId, agentType, agentVersion)

agent.loadLocalConfig()
if err := agent.connect(); err != nil {
if awaitCA {
agent.tls.InsecureSkipVerify = true
} else {
tlsConfig, err := internal.CreateClientTLSConfig(
agent.opampClientCert,
"../../certs/certs/ca.cert.pem",
)
if err != nil {
agent.logger.Errorf(context.Background(), "Cannot load client TLS config: %v", err)
return nil
}
agent.tls = tlsConfig
}
if err := agent.connect(agent.tls); err != nil {
agent.logger.Errorf(context.Background(), "Cannot connect OpAMP client: %v", err)
return nil
}

return agent
}

func (agent *Agent) connect() error {
func (agent *Agent) connect(tlsConfig *tls.Config) error {
agent.opampClient = client.NewWebSocket(agent.logger)

tlsConfig, err := internal.CreateClientTLSConfig(
agent.opampClientCert,
"../../certs/certs/ca.cert.pem",
)
if err != nil {
return err
}

agent.tls = tlsConfig
settings := types.StartSettings{
OpAMPServerURL: "wss://127.0.0.1:4320/v1/opamp",
TLSConfig: tlsConfig,
TLSConfig: agent.tls,
InstanceUid: types.InstanceUid(agent.instanceId),
Callbacks: types.CallbacksStruct{
OnConnectFunc: func(ctx context.Context) {
Expand Down Expand Up @@ -133,7 +146,7 @@ func (agent *Agent) connect() error {
protobufs.AgentCapabilities_AgentCapabilities_AcceptsOpAMPConnectionSettings,
}

err = agent.opampClient.SetAgentDescription(agent.agentDescription)
err := agent.opampClient.SetAgentDescription(agent.agentDescription)
if err != nil {
return err
}
Expand Down Expand Up @@ -485,44 +498,109 @@ func (agent *Agent) onMessage(ctx context.Context, msg *types.MessageData) {
agent.requestClientCertificate()
}

func (agent *Agent) tryChangeOpAMPCert(ctx context.Context, cert *tls.Certificate) {
agent.logger.Debugf(ctx, "Reconnecting to verify offered client certificate.\n")

func (agent *Agent) tryChangeOpAMP(ctx context.Context, cert *tls.Certificate, cfg *tls.Config) {
agent.logger.Debugf(ctx, "Reconnecting to verify new OpAMP settings.\n")
agent.disconnect(ctx)

agent.opampClientCert = cert
if err := agent.connect(); err != nil {
agent.logger.Errorf(ctx, "Cannot connect using offered certificate: %s. Ignoring the offer\n", err)
agent.opampClientCert = nil
oldCfg := agent.tls
if cfg == nil {
cfg = oldCfg.Clone()
}
if cert != nil {
agent.logger.Debugf(ctx, "Using new certificate\n")
cfg.Certificates = []tls.Certificate{*cert}
}

if err := agent.connect(); err != nil {
agent.logger.Errorf(ctx, "Unable to reconnect after restoring client certificate: %v\n", err)
if err := agent.connect(cfg); err != nil {
agent.logger.Errorf(ctx, "Cannot connect after using new tls config: %s. Ignoring the offer\n", err)
if err := agent.connect(oldCfg); err != nil {
agent.logger.Errorf(ctx, "Unable to reconnect after restoring tls config: %s\n", err)
}
return
}

agent.logger.Debugf(ctx, "Successfully connected to server. Accepting new client certificate.\n")

// TODO: we can also persist the successfully accepted certificate and use it when the
agent.logger.Debugf(ctx, "Successfully connected to server. Accepting new tls config.\n")
// TODO: we can also persist the successfully accepted settigns and use it when the
// agent connects to the server after the restart.
}

func (agent *Agent) onOpampConnectionSettings(ctx context.Context, settings *protobufs.OpAMPConnectionSettings) error {
if settings == nil || settings.Certificate == nil {
agent.logger.Debugf(ctx, "Received nil certificate offer, ignoring.\n")
if settings == nil {
agent.logger.Debugf(ctx, "Received nil settings, ignoring.\n")
return nil
}

cert, err := agent.getCertFromSettings(settings.Certificate)
if err != nil {
return err
var cert *tls.Certificate
var err error
if settings.Certificate != nil {
cert, err = agent.getCertFromSettings(settings.Certificate)
if err != nil {
return err
}
}

var tlsConfig *tls.Config
if settings.Tls != nil {
tlsMin, err := getTLSVersionNumber(settings.Tls.MinVersion)
if err != nil {
return fmt.Errorf("unable to convert settings.tls.min_version: %w", err)
}
tlsMax, err := getTLSVersionNumber(settings.Tls.MaxVersion)
if err != nil {
return fmt.Errorf("unable to convert settings.tls.max_version: %w", err)
}

tlsConfig = &tls.Config{
InsecureSkipVerify: settings.Tls.InsecureSkipVerify,
MinVersion: tlsMin,
MaxVersion: tlsMax,
RootCAs: x509.NewCertPool(),
// TODO support cipher_suites values
}

if settings.Tls.IncludeSystemCaCertsPool {
tlsConfig.RootCAs, err = x509.SystemCertPool()
if err != nil {
return fmt.Errorf("unable to use system cert pool: %w", err)
}
}

if settings.Tls.CaPemContents != "" {
ok := tlsConfig.RootCAs.AppendCertsFromPEM([]byte(settings.Tls.CaPemContents))
if !ok {
return fmt.Errorf("unable to add PEM CA")
}
// no need to await once we have a CA
if agent.awaitCA {
agent.logger.Debugf(ctx, "CA in offered settings.\n")
}
agent.awaitCA = false
}
}
// TODO: also use settings.DestinationEndpoint and settings.Headers for future connections.
go agent.tryChangeOpAMPCert(ctx, cert)
go agent.tryChangeOpAMP(ctx, cert, tlsConfig)

return nil
}

func getTLSVersionNumber(input string) (uint16, error) {
switch input {
case "1.0":
return tls.VersionTLS10, nil
case "1.1":
return tls.VersionTLS11, nil
case "1.2":
return tls.VersionTLS12, nil
case "1.3":
return tls.VersionTLS13, nil
case "":
// Do nothing if no value is set
return 0, nil
default:
return 0, fmt.Errorf("unsupported value: %s", input)
}
}

func (agent *Agent) getCertFromSettings(certificate *protobufs.TLSCertificate) (*tls.Certificate, error) {
// Parse the key pair to a TLS certificate that can be used for network connections.

Expand Down
5 changes: 4 additions & 1 deletion internal/examples/agent/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,12 @@ func main() {
var agentVersion string
flag.StringVar(&agentVersion, "v", "1.0.0", "Agent Version String")

var awaitCA bool
flag.BoolVar(&awaitCA, "await-ca", false, "Await the CA that the OpAMP server uses.")

flag.Parse()

agent := agent.NewAgent(&agent.Logger{log.Default()}, agentType, agentVersion)
agent := agent.NewAgent(&agent.Logger{log.Default()}, agentType, agentVersion, awaitCA)

interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
Expand Down
8 changes: 7 additions & 1 deletion internal/examples/server/main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"flag"
"log"
"os"
"os/signal"
Expand All @@ -20,8 +21,13 @@ func main() {

logger.Println("OpAMP Server starting...")

var sendCA bool
flag.BoolVar(&sendCA, "send-ca", false, "Send the CA the OpAMP server uses in the initial response as part of offered settings.")

flag.Parse()

uisrv.Start(curDir)
opampSrv := opampsrv.NewServer(&data.AllAgents)
opampSrv := opampsrv.NewServer(&data.AllAgents, sendCA)
opampSrv.Start()

logger.Println("OpAMP Server running...")
Expand Down
28 changes: 27 additions & 1 deletion internal/examples/server/opampsrv/opampsrv.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,11 @@ import (
type Server struct {
opampSrv server.OpAMPServer
agents *data.Agents
sendCA bool
logger *Logger
}

func NewServer(agents *data.Agents) *Server {
func NewServer(agents *data.Agents, sendCA bool) *Server {
logger := &Logger{
log.New(
log.Default().Writer(),
Expand All @@ -33,6 +34,7 @@ func NewServer(agents *data.Agents) *Server {

srv := &Server{
agents: agents,
sendCA: sendCA,
logger: logger,
}

Expand Down Expand Up @@ -109,6 +111,30 @@ func (srv *Server) onMessage(ctx context.Context, conn types.Connection, msg *pr
// Process the status report and continue building the response.
agent.UpdateStatus(msg, response)

if srv.sendCA && msg.ConnectionSettingsRequest != nil {
srv.logger.Debugf(ctx, "agent: %v send ca\n", instanceId)
srv.setOpAMPCA(response, "../../certs/certs/ca.cert.pem")
}

// Send the response back to the Agent.
return response
}

func (srv *Server) setOpAMPCA(response *protobufs.ServerToAgent, pathToPEM string) {
p, err := os.ReadFile(pathToPEM)
if err != nil {
srv.logger.Errorf(context.Background(), "Unable to read ca PEM file (%s): %v", pathToPEM, err)
return
}

if response.ConnectionSettings == nil {
response.ConnectionSettings = &protobufs.ConnectionSettingsOffers{}
}
if response.ConnectionSettings.Opamp == nil {
response.ConnectionSettings.Opamp = &protobufs.OpAMPConnectionSettings{}
}
if response.ConnectionSettings.Opamp.Tls == nil {
response.ConnectionSettings.Opamp.Tls = &protobufs.TLSConnectionSettings{}
}
response.ConnectionSettings.Opamp.Tls.CaPemContents = string(p)
}
17 changes: 17 additions & 0 deletions internal/examples/server/uisrv/html/agent.html
Original file line number Diff line number Diff line change
Expand Up @@ -124,5 +124,22 @@ <h3>Client Certificate</h3>
{{end}}
</form>

<h3>OpAMP Connection Settings</h3>

<br/>

<form action="/opamp_connection_settings" method="post">
<input type="hidden" name="instanceid" value="{{ .InstanceIdStr }}"/>
<input type="radio" name="tls_min" value="TLSv1.0">
<label for="TLSv1.0">TLSv1.0</label><br/>
<input type="radio" name="tls_min" value="TLSv1.1">
<label for="TLSv1.1">TLSv1.1</label><br/>
<input type="radio" name="tls_min" value="TLSv1.2">
<label for="TLSv1.2">TLSv1.2</label><br/>
<input type="radio" name="tls_min" value="TLSv1.3">
<label for="TLSv1.3">TLSv1.3</label><br/>
<input type="submit" value="Set min TLS version"/>
</form>

</body>
</html>
Loading