GithubHelp home page GithubHelp logo

strongswan / govici Goto Github PK

View Code? Open in Web Editor NEW
58.0 58.0 16.0 194 KB

Go implementation of the VICI protocol

License: MIT License

Makefile 0.19% Go 99.81%
go golang strongswan vici vici-protocol

govici's Introduction

strongSwan Configuration

Overview

strongSwan is an OpenSource IPsec-based VPN solution.

This document is just a short introduction of the strongSwan swanctl command which uses the modern vici Versatile IKE Configuration Interface. The deprecated ipsec command using the legacy stroke configuration interface is described here. For more detailed information consult the man pages, our new documentation site and the legacy wiki.

Quickstart

Certificates for users, hosts and gateways are issued by a fictitious strongSwan CA. In our example scenarios the CA certificate strongswanCert.pem must be present on all VPN endpoints in order to be able to authenticate the peers. For your particular VPN application you can either use certificates from any third-party CA or generate the needed private keys and certificates yourself with the strongSwan pki tool, the use of which will be explained in one of the sections following below.

Site-to-Site Case

In this scenario two security gateways moon and sun will connect the two subnets moon-net and sun-net with each other through a VPN tunnel set up between the two gateways:

10.1.0.0/16 -- | 192.168.0.1 | === | 192.168.0.2 | -- 10.2.0.0/16
  moon-net          moon                 sun           sun-net

Configuration on gateway moon:

/etc/swanctl/x509ca/strongswanCert.pem
/etc/swanctl/x509/moonCert.pem
/etc/swanctl/private/moonKey.pem

/etc/swanctl/swanctl.conf:

    connections {
        net-net {
            remote_addrs = 192.168.0.2

            local {
                auth = pubkey
                certs = moonCert.pem
            }
            remote {
                auth = pubkey
                id = "C=CH, O=strongSwan, CN=sun.strongswan.org"
            }
            children {
                net-net {
                    local_ts  = 10.1.0.0/16
                    remote_ts = 10.2.0.0/16
                    start_action = trap
                }
            }
        }
    }

Configuration on gateway sun:

/etc/swanctl/x509ca/strongswanCert.pem
/etc/swanctl/x509/sunCert.pem
/etc/swanctl/private/sunKey.pem

/etc/swanctl/swanctl.conf:

    connections {
        net-net {
            remote_addrs = 192.168.0.1

            local {
                auth = pubkey
                certs = sunCert.pem
            }
            remote {
                auth = pubkey
                id = "C=CH, O=strongSwan, CN=moon.strongswan.org"
            }
            children {
                net-net {
                    local_ts  = 10.2.0.0/16
                    remote_ts = 10.1.0.0/16
                    start_action = trap
                }
            }
        }
    }

The local and remote identities used in this scenario are the subjectDistinguishedNames contained in the end entity certificates. The certificates and private keys are loaded into the charon daemon with the command

swanctl --load-creds

whereas

swanctl --load-conns

loads the connections defined in swanctl.conf. With start_action = trap the IPsec connection is automatically set up with the first plaintext payload IP packet wanting to go through the tunnel.

Host-to-Host Case

This is a setup between two single hosts which don't have a subnet behind them. Although IPsec transport mode would be sufficient for host-to-host connections we will use the default IPsec tunnel mode.

| 192.168.0.1 | === | 192.168.0.2 |
     moon                sun

Configuration on host moon:

/etc/swanctl/x509ca/strongswanCert.pem
/etc/swanctl/x509/moonCert.pem
/etc/swanctl/private/moonKey.pem

/etc/swanctl/swanctl.conf:

    connections {
        host-host {
            remote_addrs = 192.168.0.2

            local {
                auth=pubkey
                certs = moonCert.pem
            }
            remote {
                auth = pubkey
                id = "C=CH, O=strongSwan, CN=sun.strongswan.org"
            }
            children {
                net-net {
                    start_action = trap
                }
            }
        }
    }

Configuration on host sun:

/etc/swanctl/x509ca/strongswanCert.pem
/etc/swanctl/x509/sunCert.pem
/etc/swanctl/private/sunKey.pem

/etc/swanctl/swanctl.conf:

    connections {
        host-host {
            remote_addrs = 192.168.0.1

            local {
                auth = pubkey
                certs = sunCert.pem
            }
            remote {
                auth = pubkey
                id = "C=CH, O=strongSwan, CN=moon.strongswan.org"
            }
            children {
                host-host {
                    start_action = trap
                }
            }
        }
    }

Roadwarrior Case

This is a very common case where a strongSwan gateway serves an arbitrary number of remote VPN clients usually having dynamic IP addresses.

10.1.0.0/16 -- | 192.168.0.1 | === | x.x.x.x |
  moon-net          moon              carol

Configuration on gateway moon:

/etc/swanctl/x509ca/strongswanCert.pem
/etc/swanctl/x509/moonCert.pem
/etc/swanctl/private/moonKey.pem

/etc/swanctl/swanctl.conf:

    connections {
        rw {
            local {
                auth = pubkey
                certs = moonCert.pem
                id = moon.strongswan.org
            }
            remote {
                auth = pubkey
            }
            children {
                net-net {
                    local_ts  = 10.1.0.0/16
                }
            }
        }
    }

Configuration on roadwarrior carol:

/etc/swanctl/x509ca/strongswanCert.pem
/etc/swanctl/x509/carolCert.pem
/etc/swanctl/private/carolKey.pem

/etc/swanctl/swanctl.conf:

    connections {
        home {
            remote_addrs = moon.strongswan.org

            local {
                auth = pubkey
                certs = carolCert.pem
                id = [email protected]
            }
            remote {
                auth = pubkey
                id = moon.strongswan.org
            }
            children {
                home {
                    local_ts  = 10.1.0.0/16
                    start_action = start
                }
            }
        }
    }

For remote_addrs the hostname moon.strongswan.org was chosen which will be resolved by DNS at runtime into the corresponding IP destination address. In this scenario the identity of the roadwarrior carol is the email address [email protected] which must be included as a subjectAlternativeName in the roadwarrior certificate carolCert.pem.

Roadwarrior Case with Virtual IP

Roadwarriors usually have dynamic IP addresses assigned by the ISP they are currently attached to. In order to simplify the routing from moon-net back to the remote access client carol it would be desirable if the roadwarrior had an inner IP address chosen from a pre-defined pool.

10.1.0.0/16 -- | 192.168.0.1 | === | x.x.x.x | -- 10.3.0.1
  moon-net          moon              carol       virtual IP

In our example the virtual IP address is chosen from the address pool 10.3.0.0/16 which can be configured by adding the section

pools {
    rw_pool {
        addrs = 10.3.0.0/16
    }
}

to the gateway's swanctl.conf from where they are loaded into the charon daemon using the command

swanctl --load-pools

To request an IP address from this pool a roadwarrior can use IKEv1 mode config or IKEv2 configuration payloads. The configuration for both is the same

vips = 0.0.0.0

Configuration on gateway moon:

/etc/swanctl/x509ca/strongswanCert.pem
/etc/swanctl/x509/moonCert.pem
/etc/swanctl/private/moonKey.pem

/etc/swanctl/swanctl.conf:

    connections {
        rw {
            pools = rw_pool

            local {
                auth = pubkey
                certs = moonCert.pem
                id = moon.strongswan.org
            }
            remote {
                auth = pubkey
            }
            children {
                net-net {
                    local_ts  = 10.1.0.0/16
                }
            }
        }
    }

    pools {
        rw_pool {
            addrs = 10.30.0.0/16
        }
    }

Configuration on roadwarrior carol:

/etc/swanctl/x509ca/strongswanCert.pem
/etc/swanctl/x509/carolCert.pem
/etc/swanctl/private/carolKey.pem

/etc/swanctl/swanctl.conf:

    connections {
        home {
            remote_addrs = moon.strongswan.org
            vips = 0.0.0.0

            local {
                auth = pubkey
                certs = carolCert.pem
                id = [email protected]
            }
            remote {
                auth = pubkey
                id = moon.strongswan.org
            }
            children {
                home {
                    local_ts  = 10.1.0.0/16
                    start_action = start
                }
            }
        }
    }

Roadwarrior Case with EAP Authentication

This is a very common case where a strongSwan gateway serves an arbitrary number of remote VPN clients which authenticate themselves via a password based Extended Authentication Protocol as e.g. EAP-MD5 or EAP-MSCHAPv2.

10.1.0.0/16 -- | 192.168.0.1 | === | x.x.x.x |
  moon-net          moon              carol

Configuration on gateway moon:

/etc/swanctl/x509ca/strongswanCert.pem
/etc/swanctl/x509/moonCert.pem
/etc/swanctl/private/moonKey.pem

/etc/swanctl/swanctl.conf:

    connections {
        rw {
            local {
                auth = pubkey
                certs = moonCert.pem
                id = moon.strongswan.org
            }
            remote {
                auth = eap-md5
            }
            children {
                net-net {
                    local_ts  = 10.1.0.0/16
                }
            }
            send_certreq = no
        }
    }

The swanctl.conf file additionally contains a secrets section defining all client credentials

    secrets {
        eap-carol {
            id = [email protected]
            secret = Ar3etTnp
        }
        eap-dave {
            id = [email protected]
            secret = W7R0g3do
        }
    }

Configuration on roadwarrior carol:

/etc/swanctl/x509ca/strongswanCert.pem

/etc/swanctl/swanctl.conf:

    connections {
        home {
            remote_addrs = moon.strongswan.org

            local {
                auth = eap
                id = [email protected]
            }
            remote {
                auth = pubkey
                id = moon.strongswan.org
            }
            children {
                home {
                    local_ts  = 10.1.0.0/16
                    start_action = start
                }
            }
        }
    }

    secrets {
        eap-carol {
            id = [email protected]
            secret = Ar3etTnp
        }
    }

Roadwarrior Case with EAP Identity

Often a client EAP identity is exchanged via EAP which differs from the external IKEv2 identity. In this example the IKEv2 identity defaults to the IPv4 address of the client.

10.1.0.0/16 -- | 192.168.0.1 | === | x.x.x.x |
  moon-net          moon              carol

Configuration on gateway moon:

/etc/swanctl/x509ca/strongswanCert.pem
/etc/swanctl/x509/moonCert.pem
/etc/swanctl/private/moonKey.pem

/etc/swanctl/swanctl.conf:

    connections {
        rw {
            local {
                auth = pubkey
                certs = moonCert.pem
                id = moon.strongswan.org
            }
            remote {
                auth = eap-md5
                eap_id = %any
            }
            children {
                net-net {
                    local_ts  = 10.1.0.0/16
                }
            }
            send_certreq = no
        }
    }

    secrets {
        eap-carol {
            id = carol
            secret = Ar3etTnp
        }
        eap-dave {
            id = dave
            secret = W7R0g3do
        }
    }

Configuration on roadwarrior carol:

/etc/swanctl/x509ca/strongswanCert.pem

/etc/swanctl/swanctl.conf:

    connections {
        home {
            remote_addrs = moon.strongswan.org

            local {
                auth = eap
                eap_id = carol
            }
            remote {
                auth = pubkey
                id = moon.strongswan.org
            }
            children {
                home {
                    local_ts  = 10.1.0.0/16
                    start_action = start
                }
            }
        }
    }

    secrets {
        eap-carol {
            id = carol
            secret = Ar3etTnp
        }
    }

Generating Certificates and CRLs

This section is not a full-blown tutorial on how to use the strongSwan pki tool. It just lists a few points that are relevant if you want to generate your own certificates and CRLs for use with strongSwan.

Generating a CA Certificate

The pki statement

pki --gen --type ed25519 --outform pem > strongswanKey.pem

generates an elliptic Edwards-Curve key with a cryptographic strength of 128 bits. The corresponding public key is packed into a self-signed CA certificate with a lifetime of 10 years (3652 days)

pki --self --ca --lifetime 3652 --in strongswanKey.pem \
           --dn "C=CH, O=strongSwan, CN=strongSwan Root CA" \
           --outform pem > strongswanCert.pem

which can be listed with the command

pki --print --in strongswanCert.pem

subject:  "C=CH, O=strongSwan, CN=strongSwan Root CA"
issuer:   "C=CH, O=strongSwan, CN=strongSwan Root CA"
validity:  not before May 18 08:32:06 2017, ok
           not after  May 18 08:32:06 2027, ok (expires in 3651 days)
serial:    57:e0:6b:3a:9a:eb:c6:e0
flags:     CA CRLSign self-signed
subjkeyId: 2b:95:14:5b:c3:22:87:de:d1:42:91:88:63:b3:d5:c1:92:7a:0f:5d
pubkey:    ED25519 256 bits
keyid:     a7:e1:6a:3f:e7:6f:08:9d:89:ec:23:92:a9:a1:14:3c:78:a8:7a:f7
subjkey:   2b:95:14:5b:c3:22:87:de:d1:42:91:88:63:b3:d5:c1:92:7a:0f:5d

If you prefer the CA private key and X.509 certificate to be in binary DER format then just omit the --outform pem option. The directory /etc/swanctl/x509ca contains all required CA certificates either in binary DER or in Base64 PEM format. Irrespective of the file suffix the correct format will be determined by strongSwan automagically.

Generating a Host or User End Entity Certificate

Again we are using the command

pki --gen --type ed25519 --outform pem > moonKey.pem

to generate an Ed25519 private key for the host moon. Alternatively you could type

pki --gen --type rsa --size 3072 > moonKey.der

to generate a traditional 3072 bit RSA key and store it in binary DER format. As an alternative a TPM 2.0 Trusted Platform Module available on every recent Intel platform could be used as a virtual smartcard to securely store an RSA or ECDSA private key. For details, refer to the TPM 2.0 HOWTO.

In a next step the command

pki --req --type priv --in moonKey.pem \
          --dn "C=CH, O=strongswan, CN=moon.strongswan.org" \
          --san moon.strongswan.org --outform pem > moonReq.pem

creates a PKCS#10 certificate request that has to be signed by the CA. Through the [multiple] use of the --san parameter any number of desired subjectAlternativeNames can be added to the request. These can be of the form

--san sun.strongswan.org     # fully qualified host name
--san [email protected]   # RFC822 user email address
--san 192.168.0.1            # IPv4 address
--san fec0::1                # IPv6 address

Based on the certificate request the CA issues a signed end entity certificate with the following command

pki --issue --cacert strongswanCert.pem --cakey strongswanKey.pem \
            --type pkcs10 --in moonReq.pem --serial 01 --lifetime 1826 \
            --outform pem > moonCert.pem

If the --serial parameter with a hexadecimal argument is omitted then a random serial number is generated. Some third party VPN clients require that a VPN gateway certificate contains the TLS Server Authentication Extended Key Usage (EKU) flag which can be included with the following option

--flag serverAuth

If you want to use the dynamic CRL fetching feature described in one of the following sections then you may include one or several crlDistributionPoints in your end entity certificates using the --crl parameter

--crl  http://crl.strongswan.org/strongswan.crl
--crl "ldap://ldap.strongswan.org/cn=strongSwan Root CA, o=strongSwan,c=CH?certificateRevocationList"

The issued host certificate can be listed with

pki --print --in moonCert.pem

subject:  "C=CH, O=strongSwan, CN=moon.strongswan.org"
issuer:   "C=CH, O=strongSwan, CN=strongSwan Root CA"
validity:  not before May 19 10:28:19 2017, ok
           not after  May 19 10:28:19 2022, ok (expires in 1825 days)
serial:    01
altNames:  moon.strongswan.org
flags:     serverAuth
CRL URIs:  http://crl.strongswan.org/strongswan.crl
authkeyId: 2b:95:14:5b:c3:22:87:de:d1:42:91:88:63:b3:d5:c1:92:7a:0f:5d
subjkeyId: 60:9d:de:30:a6:ca:b9:8e:87:bb:33:23:61:19:18:b8:c4:7e:23:8f
pubkey:    ED25519 256 bits
keyid:     39:1b:b3:c2:34:72:1a:01:08:40:ce:97:75:b8:be:ce:24:30:26:29
subjkey:   60:9d:de:30:a6:ca:b9:8e:87:bb:33:23:61:19:18:b8:c4:7e:23:8f

Usually, a Windows, OSX, Android or iOS based VPN client needs its private key, its host or user certificate and the CA certificate. The most convenient way to load this information is to put everything into a PKCS#12 container:

openssl pkcs12 -export -inkey carolKey.pem \
               -in carolCert.pem -name "carol" \
               -certfile strongswanCert.pem -caname "strongSwan Root CA" \
               -out carolCert.p12

The strongSwan pki tool currently is not able to create PKCS#12 containers so that openssl must be used.

Generating a CRL

An empty CRL that is signed by the CA can be generated with the command

pki --signcrl --cacert strongswanCert.pem --cakey strongswanKey.pem \
              --lifetime 30 > strongswan.crl

If you omit the --lifetime option then the default value of 15 days is used. CRLs can either be uploaded to a HTTP or LDAP server or put in binary DER or Base64 PEM format into the /etc/swanctl/x509crl directory from where they are loaded into the charon daemon with the command

swanctl --load-creds

Revoking a Certificate

A specific end entity certificate is revoked with the command

pki --signcrl --cacert strongswanCert.pem --cakey strongswanKey.pem \
              --lifetime 30 --lastcrl strongswan.crl \
              --reason key-compromise --cert moonCert.pem > new.crl

Instead of the certificate file (in our example moonCert.pem), the serial number of the certificate to be revoked can be indicated using the --serial parameter. The pki --signcrl --help command documents all possible revocation reasons but the --reason parameter can also be omitted. The content of the new CRL file can be listed with the command

pki --print --type crl --in new.crl

issuer:   "C=CH, O=strongSwan, CN=strongSwan Root CA"
update:    this on May 19 11:13:01 2017, ok
           next on Jun 18 11:13:01 2017, ok (expires in 29 days)
serial:    02
authKeyId: 2b:95:14:5b:c3:22:87:de:d1:42:91:88:63:b3:d5:c1:92:7a:0f:5d
1 revoked certificate:
  01: May 19 11:13:01 2017, key compromise

Local Caching of CRLs

The strongswan.conf option

charon {
    cache_crls = yes
}

activates the local caching of CRLs that were dynamically fetched from an HTTP or LDAP server. Cached copies are stored in /etc/swanctl/x509crl using a unique filename formed from the issuer's subjectKeyIdentifier and the suffix .crl.

With the cached copy the CRL is immediately available after startup. When the local copy has become stale, an updated CRL is automatically fetched from one of the defined CRL distribution points during the next IKEv2 authentication.

govici's People

Contributors

enr0n avatar jared2501 avatar laura-zelenku avatar lixit avatar mlitvin avatar mmellison avatar shassard avatar tobiasbrunner avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

govici's Issues

More examples required

I feel like more examples and maybe more unit tests are required. Usually if the documentation is not enough, you can go through the unit tests to see how the mod is supposed to work. After an hour of hacking, I managed to get some code working to get a list of EAP IDs:

package main

import (
	"fmt"

	"github.com/strongswan/govici"
)

func main() {
	session, err := vici.NewSession()
	if err != nil {
		fmt.Println(err)
		return
	}
	defer session.Close()

	ms, err := session.StreamedCommandRequest("list-sas", "list-sa", nil)
	if err != nil {
		fmt.Println("got error starting message stream: ", err)
		return
	}

	userCounter := 1
	for _, m := range ms.Messages() {
		for _, k := range m.Keys() {
			sa := m.Get(k)
			remoteID := struct {
				RemoteID string `vici:"remote-eap-id"`
			}{}
			err := vici.UnmarshalMessage(sa.(*vici.Message), &remoteID)
			if err != nil {
				fmt.Println("got error: ", err)
			} else {
				fmt.Println("user ", userCounter, " is ", remoteID)
				userCounter++
			}
		}
	}
}

Printing stuff out and unmarshalling after that is also a bit painful. It would help to have predefined types with all the messages you can get.

tag go module v0.1.0

Moving to Go modules is straight forward, but one thing to consider is whether this package should change its import path. Right now, we do not use the canonical import path (a vestige from before moving the package to its final home). This means that if your source files are goimports -s-ed, then you have:

import (
        vici "github.com/strongswan/govici"
)

Since this is not best practice for a package, I would like to use migration to Go modules as an opportunity to make sure this package does follow best practices.

I think the simplest option is to initialize the go module as github.com/strongswan/govici, and move the existing *.go files to vici/ sub-directory. This does mean that existing users of the package will have to change their import paths to github.com/strongswan/govici/vici when they uprev to v0.1.0.

vici: investigate use of generics in API

With go 1.18 coming, it would be good to investigate the use of generics in the vici API. On area that may be useful is around the Message type, since we currently use a map[string]interface{} under the hood. Using generics in the vici package would introduce breaking changes, which is why this is an issue targeted for a future v1.0 tag.

swanctl --load-creds equivalent in govici

I started looking at govici documentation and sample code. I see that, it has implemented some of the 'swanctl load-*' commands like load-conn. I could not find 'load-creds' equivalent command though.
Is this implemented already?

rekey fails and child SA disappears

I have started using govici a while ago.

I have noticed the default rekey time for child SA is 1h and connection is 4h. I noticed that, after 1h, child attempts to rekey and eventually fails.
To check this, I disabled connection rekey_time to 0 (so that rekey is disabled). for child SA, I set it to 180 seconds.
My expectation is child SA will try to rekey once rekey timer reaches 0 and timer should again start from 180.
But after 180 seconds, rekeying process starts and it does not succeed.

In child SA section , I am only setting following fields:
mark_in, mark_out, start_action=start, local_ts, remote_ts, rekey_time=180.

Am I missing something for rekey to succeed?

Here is the 'ipsec statusall' output 1. just before rekey starts, 2. during rekeying process and 3. eventual failure.

  1. just before rekey starts:
    Security Associations (1 up, 0 connecting):
    conn[1]: ESTABLISHED 2 minutes ago, 21.0.109.180[104.134.28.12]...35.242.127.5[35.242.127.5]
    conn[1]: IKEv2 SPIs: f2103158733a4a12_i* 79e84ab3fc1b1427_r, rekeying disabled
    conn[1]: IKE proposal: AES_GCM_8_128/PRF_AES128_XCBC/MODP_2048
    connchild{1}: INSTALLED, TUNNEL, reqid 1, ESP in UDP SPIs: c6a77bac_i 789afd30_o
    connchild{1}: AES_CBC_128/HMAC_SHA2_256_128, 0 bytes_i, 0 bytes_o, rekeying in 1 second
    connchild{1}: 0.0.0.0/0 === 0.0.0.0/0

  2. during rekeying
    conn[1]: ESTABLISHED 2 minutes ago, 21.0.109.180[104.134.28.12]...35.242.127.5[35.242.127.5]
    conn[1]: IKEv2 SPIs: f2103158733a4a12_i* 79e84ab3fc1b1427_r, rekeying disabled
    conn[1]: IKE proposal: AES_GCM_8_128/PRF_AES128_XCBC/MODP_2048
    connchild{1}: INSTALLED, TUNNEL, reqid 1, ESP in UDP SPIs: c6a77bac_i 789afd30_o
    connchild{1}: AES_CBC_128/HMAC_SHA2_256_128, 0 bytes_i, 0 bytes_o, rekeying active
    connchild{1}: 0.0.0.0/0 === 0.0.0.0/0

  3. eventually after few seconds
    conn[1]: ESTABLISHED 3 minutes ago, 21.0.109.180[104.134.28.12]...35.242.127.5[35.242.127.5]
    conn[1]: IKEv2 SPIs: f2103158733a4a12_i* 79e84ab3fc1b1427_r, rekeying disabled
    conn[1]: IKE proposal: AES_GCM_8_128/PRF_AES128_XCBC/MODP_2048
    ====> why is this happening ?

message: "empty message element" needs to be explicitly defined, documented, and verified

Since go 1.13 introduced the Value.IsZero convenience method to the reflect package, I tried using this function instead of the emptyMessageElement function. I.e.,

diff --git a/vici/message.go b/vici/message.go
index 8daf7c9..7f2cf6e 100644
--- a/vici/message.go
+++ b/vici/message.go
@@ -829,7 +829,7 @@ func (m *Message) marshalFromStruct(rv reflect.Value) error {
 			continue
 		}
 
-		if emptyMessageElement(rfv) {
+		if rfv.IsZero() {
 			continue
 		}

However, this causes TestMarshalBoolFalse to fail...

=== RUN   TestMarshalBoolFalse
    TestMarshalBoolFalse: message_marshal_test.go:128: Marshalled boolean value is invalid.
        Expected: no
        Received: <nil>

...meaning our definition of an "empty" element is not consistent with the reflect package (42761e7 should have been a clue). As it stands, the emptyMessageElement is "correct" according to our test cases, but I am of the opinion this function should be consistent with reflect.Value.IsZero since it was originally written due to the absence of such a method in reflect.

I was looking into this code because I wanted to add an omitempty tag option to allow more flexibility to marshaling.

Possible Deadlock when Vici Socket Disappears

We've been investigating possible deadlock when the Vici socket disappears (e.g. StrongSwan crashes or otherwise goes away). It appears deadlock happens under the following order of circumstances:

  1. An event is registered with govici Session.
  2. Socket goes away.
  3. Close method is called on the govici Session.
  4. Blocked indefinitely.

Deadlock does not occur unless an event is registered.


We've isolated it to a hard loop in the event listener once vici: transport error: EOF occurs.

Due to the recv method being called on the event listener repeatedly even after the first EOF occurs, the event channel (el.ec) fills up with 16 errors. Once this happens, the following code causes deadlock since the channel is now blocked and the mutex remains locked:

			el.emux.Lock()
			if len(el.events) > 0 {
				el.ec <- Event{err: err}
			}
			el.emux.Unlock()

Calling session.Close then remains blocked forever.


We were able to create a temporary patch by returning the EOF error directly from the recv method and in the event we receive an EOF, we return from the listener instead of continuing:

                        el.emux.Lock()
			if len(el.events) > 0 {
				el.ec <- Event{err: err}
			}
			el.emux.Unlock()

			if err == io.EOF {
				return
			}

Test Program:

	session, err := vici.NewSession()
	if err != nil {
		panic(err)
	}

	err = session.Subscribe("child-updown")
	if err != nil {
		panic(err)
	}

	fmt.Println("About to Sleep: Stop StrongSwan Now")
	time.Sleep(5 * time.Second)
	fmt.Println("Waking Up, closing Session")

	err = session.Close()
	if err != nil {
		panic(err)
	}

	fmt.Println("Done")

Event notification channels are not closed when event transport recv() fails

Describe the bug
Channels registered with NotifyEvents() are not closed when session transport recv() fails thus making it impossible to detect session disconnect from strongSwan.

To Reproduce
Subscribe to some events, register notification channel with NotifyEvents() and then restart strongSwan.

Expected behavior
Registered notification channel should be closed or there must be some another way to detect session disconnect and consequent event listener loop stop.

Screenshots
N/A

Version information

  • vici package version: 0.6.0
  • StrongSwan version: 5.8.2

Additional context
swanctl --monitor-sa doesn't detect strongSwan restarts too but Python implementation does. And as I understand old deprecated NextEvent() call handles this situation correctly.

Basic command request example ends up in segfault

Hello.

The very 1st example from the readme isn't workig:

daemon: charon-systemd
version: 5.7.2
sysname: Linux
release: 4.19.0-6-amd64
machine: x86_64
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x48 pc=0x531840]

goroutine 1 [running]:
github.com/strongswan/govici.(*eventListener).Close(0x0, 0xc0000ae000, 0xc000040eb8)
        /root/go/src/github.com/strongswan/govici/events.go:75 +0x20
github.com/strongswan/govici.(*Session).Close(0xc000078630, 0x0, 0x2)
        /root/go/src/github.com/strongswan/govici/session.go:76 +0x33
main.main()
        /root/go/src/gitlab.oubcom.net/linux/nagios-plugins/nrpe/check_swan_cert/main.go:126 +0x2fc

It seems to be caused by an attempt to Close() the Session, which in turn tries to Close() the eventListener. As there is no eventListener registered at this point, the program crashes.

Quick hack in the Close() function in session.go seems to resolve the issue:

if s.el != nil {
  if err := s.el.Close(); err != nil {
    return err
  }
}

session/events: expose event name from packet

As suggested by @seglberg in #17, the packet/event name should be exposed when the event is received. This will allow code like:

for {
        e, err := s.NextEvent()
        if err != nil {
                // handle err
        }
        switch e.Name() { // Just an example
        case "event1":
                // handle event1
        case "event2":
                // handle event2
        }
}

Since the package has not yet reached v1.0.0, we will likely break the API here rather than adding an awkward extension.

vici: remove MessageStream from API

The MessageStream type is an unneeded abstraction for a list of Message's. Removing this would be a breaking change, but may be worth it for API simplicity in v1.0.

test load_conn command failed

I use the example test case in getting started article .

type connection struct {
	Name string // This field will NOT be marshaled!

	LocalAddrs []string            `vici:"local_addrs"`
	Local      *localOpts          `vici:"local"`
	Remote     *remoteOpts         `vici:"remote"`
	Children   map[string]*childSA `vici:"children"`
	Version    int                 `vici:"version"`
	Proposals  []string            `vici:"proposals"`
}

type localOpts struct {
	Auth  string   `vici:"auth"`
	Certs []string `vici:"certs"`
	ID    string   `vici:"id"`
}

type remoteOpts struct {
	Auth string `vici:"auth"`
}

type childSA struct {
	LocalTrafficSelectors []string `vici:"local_ts"`
	Updown                string   `vici:"updown"`
	ESPProposals          []string `vici:"esp_proposals"`
}

func loadConn(conn connection) error {
	s, err := vici.NewSession()
	if err != nil {
		return err
	}
        defer s.Close()

	c, err := vici.MarshalMessage(&conn)
	if err != nil {
		return err
	}

        m := vici.NewMessage()
        if err := m.Set(conn.Name, c); err != nil {
                return err
        }

	_, err = s.CommandRequest("load-conn", m)

	return err
}

Function of CommandRequest return failed, charon vici module create cert failed, the log like this:

15[LIB]   file coded in unknown format, discarded
15[LIB] building CRED_CERTIFICATE - X509 failed, tried 4 builders

strongswan version is 5.9.0.

Expose ability to pass in conn

Currently, the only public API is vici.WithSocketPath. I'd like to be able to do vici.WithConn, and pass in an already constructed connection. Or, at the very least, be able to pass in a "network", "address", and net.Dialer.

Use case: I'm using govici library and running strongswan in a couple docker containers. I have the vici interface configured to listen on a TCP port so that I can expose it from the container.

session/events: re-work event listening API

The event listening API is currently a little awkward. A caller must register for all event types at once in a call to Listen, and can only unsubscribe (all or nothing) by closing the Session or cancelling the context provided to Listen. Ideally, a caller should be able to dynamically sub/unsub from a given event(s).

The new (not backwards compatible) API might look like:

func (s *Session) Subscribe(events ...string) error
func (s *Session) Unsubscribe(events ...string) error
func (s *Session) UnsubscribeAll() error

See the original suggestion from @seglberg .

Event dispatching could silently drop messages if a receiver channel is full

Describe the bug

The select pattern

select {
will default to dropping a message if the receiver buffer is full.

To Reproduce

// You can edit this code!
// Click here and start typing.
package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {

	var c = make(chan int, 16)

	var wg sync.WaitGroup
	wg.Add(1)

	go func() {
		defer wg.Done()
		for {
			select {
			case v, ok := <-c:
				if !ok {
					return
				}
				fmt.Println(v)
				time.Sleep(time.Microsecond)
			}
		}
	}()

	for i := 0; i < 100; i++ {
		select {
		case c <- i:
		default:
			fmt.Printf("dropping %d\n", i)
		}

	}
	close(c)
	wg.Wait()
}

https://go.dev/play/p/hUQThyF0Tmf

Expected behavior

Message delivery should be reliant; current behavior could potentially cause a loss of events. The previous implementation blocks rather than dropping messages. If this pattern is preferable for your implementation, please provide some drop counters per event as exported field/function to be transparent on the loss of events.

Screenshots
If applicable, add screenshots to help explain your problem.

Version information
v0.6.0

Additional context
Add any other context about the problem here.

transport: partial/interrupted Read()'s cause incorrect packet length decoding

I have another issue, I don't know how does this happen, this is the code:

func (t *transport) recv() (*packet, error) {
buf := make([]byte, headerLength)
t.conn.SetReadDeadline(time.Now().Add(time.Second * 20))
_, err := t.conn.Read(buf)
if err != nil {
if ne, ok := err.(net.Error); ok && ne.Timeout() {
return nil, ne
}
return nil, fmt.Errorf("%v: %v", errTransport, err)
}

================================================================
pl := binary.BigEndian.Uint32(buf)
//netbank.cn
need check the validity of buf length, because sometime the length may be a very very big number, I don't know why
if pl > 1024*10 {
fmt.Fprintf(os.Stderr, "vici recv len %v\n, %s", pl, debug.Stack())
return nil, fmt.Errorf("vici error: recv wrong data len %v", pl)
}
//netbank.cn
================================================================

buf = make([]byte, int(pl))
_, err = t.conn.Read(buf)
if err != nil {
	return nil, fmt.Errorf("%v: %v", errTransport, err)
}

p := &packet{}
err = p.parse(buf)
if err != nil {
	return nil, err
}

return p, nil
}

Best,

If charon is dead, the vici session cannot be closed.

Hi guys,

I have a bug, this is my code:

func TestFunc() {
s, err := vici.NewSession()
if err != nil {
fmt.Fprintf(os.Stderr, "vici NewSession failed!")
return
}
// Register event listener for 'ike-updown' events.
if err := s.Listen(context.Background(), "ike-updown"); err != nil {
fmt.Fprintf(os.Stderr,"vici Listen failed!")
s.Close()
return
}
for {
e, err := s.NextEvent()
if err != nil {
s.Close()
fmt.Fprintf(os.Stderr,"vici is closed.")
return
} else {
fmt.Fprintf(os.Stderr,"receive an event.")
}
}
}

When the charon is alive,  everything goes well, but when charon is restarted, s.NextEvent() will get an error, if I call s.Close() to close the session, the function will be hung, but if I don't call s.Close(), the file handle opened cannot be closed.

I debug the code, and find the s.Close is hung by chan.

func (s *Session) Close() error {
...............................................
s.emux.RLock()
if s.el != nil {
if err := s.el.Close(); err != nil {------------>The code is hung here
return err
}
}
...........................................
return nil
}

To find more exact code in s.el.Close,
func (el *eventListener) Close() error {
// Cancel the event listener context, and
// wait for the destroy context to be done.
el.cancel()
<-el.dctx.Done() ---------------------------->this is the exact code line
return nil
}

In func s.Listen()

func (el *eventListener) listen(events []string) (err error) {
...............................
go func() {
defer el.destroy()
for {
...........................................................
default:
var e event
_ = el.conn.SetReadDeadline(time.Now().Add(time.Second))

			p, err := el.recv()
			if err != nil {
				if ne, ok := err.(net.Error); ok && ne.Timeout() {
					continue
				}
				e.err = err
                                 // Send error event and continue in loop.
			**el.ec <- e ----------------------------->I find the code is hung here, so no one call  el.destroy(), that's why I cannot close the session.**
                                    continue
			}

			if p.ptype == pktEvent {
				e.msg = p.msg
				el.ec <- e
			}
		}
	}
}()

return nil

}

Best,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.