structured logs

This commit is contained in:
m5r 2024-07-19 02:24:11 +02:00
parent c202885684
commit 61cf3ec24d
Signed by: mokhtar
GPG Key ID: 1509B54946D08A95
8 changed files with 142 additions and 106 deletions

View File

@ -8,13 +8,13 @@ import (
"crypto/x509" "crypto/x509"
"encoding/json" "encoding/json"
"encoding/pem" "encoding/pem"
"log"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/go-acme/lego/v4/lego" "github.com/go-acme/lego/v4/lego"
"github.com/go-acme/lego/v4/registration" "github.com/go-acme/lego/v4/registration"
"local-ip.sh/utils"
) )
type Account struct { type Account struct {
@ -42,28 +42,28 @@ func LoadAccount() *Account {
RegisterAccount() RegisterAccount()
return LoadAccount() return LoadAccount()
} }
log.Fatal(err) utils.Logger.Fatal().Err(err).Msg("Failed to load account from existing file")
} }
account := &Account{} account := &Account{}
err = json.Unmarshal(jsonBytes, account) err = json.Unmarshal(jsonBytes, account)
if err != nil { if err != nil {
log.Fatal(err) utils.Logger.Fatal().Err(err).Msg("Failed to unmarshal account JSON file")
} }
privKey, err := os.ReadFile(keyFilePath) privKey, err := os.ReadFile(keyFilePath)
if err != nil { if err != nil {
log.Fatal(err) utils.Logger.Fatal().Err(err).Msg("Failed to read account's private key file")
} }
privateKey := decode(string(privKey))
account.key = privateKey account.key = decode(string(privKey))
return account return account
} }
func RegisterAccount() { func RegisterAccount() {
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil { if err != nil {
log.Fatal(err) utils.Logger.Fatal().Err(err).Msg("Failed to generate account key")
} }
account := &Account{ account := &Account{
@ -74,35 +74,39 @@ func RegisterAccount() {
config.CADirURL = caDirUrl config.CADirURL = caDirUrl
legoClient, err := lego.NewClient(config) legoClient, err := lego.NewClient(config)
if err != nil { if err != nil {
log.Fatal(err) utils.Logger.Fatal().Err(err).Str("CA Directory URL", config.CADirURL).Msg("Failed to initialize lego client")
} }
reg, err := legoClient.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true}) reg, err := legoClient.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
if err != nil { if err != nil {
log.Fatal(err) utils.Logger.Fatal().Err(err).Str("CA Directory URL", config.CADirURL).Msg("Failed to register account to ACME server")
} }
if reg.Body.Status != "valid" { if reg.Body.Status != "valid" {
log.Fatalf("registration failed with status %s", reg.Body.Status) utils.Logger.Fatal().Err(err).Str("CA Directory URL", config.CADirURL).Msgf("Registration failed with status %s", reg.Body.Status)
} }
log.Println(reg.Body.TermsOfServiceAgreed)
utils.Logger.Debug().
Str("CA Directory URL", config.CADirURL).
Bool("TermsOfServiceAgreed", reg.Body.TermsOfServiceAgreed).
Msg("Successfully registered account to ACME server")
account.Registration = reg account.Registration = reg
os.MkdirAll(filepath.Dir(keyFilePath), os.ModePerm) os.MkdirAll(filepath.Dir(keyFilePath), os.ModePerm)
privKey := encode(privateKey) privKey := encode(privateKey)
err = os.WriteFile(keyFilePath, []byte(privKey), 0o644) err = os.WriteFile(keyFilePath, []byte(privKey), 0o644)
if err != nil { if err != nil {
log.Fatal(err) utils.Logger.Fatal().Err(err).Str("path", keyFilePath).Msg("Failed to write account's private key file")
} }
jsonBytes, err := json.MarshalIndent(account, "", "\t") jsonBytes, err := json.MarshalIndent(account, "", "\t")
if err != nil { if err != nil {
log.Fatal(err) utils.Logger.Fatal().Err(err).Msg("Failed to marshal account JSON file")
} }
os.MkdirAll(filepath.Dir(accountFilePath), os.ModePerm) os.MkdirAll(filepath.Dir(accountFilePath), os.ModePerm)
err = os.WriteFile(accountFilePath, jsonBytes, 0o600) err = os.WriteFile(accountFilePath, jsonBytes, 0o600)
if err != nil { if err != nil {
log.Fatal(err) utils.Logger.Fatal().Err(err).Str("path", accountFilePath).Msg("Failed to write account's JSON file")
} }
} }

View File

@ -3,7 +3,6 @@ package certs
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"log"
"os" "os"
"strings" "strings"
"time" "time"
@ -12,6 +11,7 @@ import (
"github.com/go-acme/lego/v4/certificate" "github.com/go-acme/lego/v4/certificate"
"github.com/go-acme/lego/v4/challenge/dns01" "github.com/go-acme/lego/v4/challenge/dns01"
"github.com/go-acme/lego/v4/lego" "github.com/go-acme/lego/v4/lego"
"local-ip.sh/utils"
"local-ip.sh/xip" "local-ip.sh/xip"
) )
@ -36,20 +36,20 @@ func (c *certsClient) requestCertificate(certType string) {
lastCertificate = c.lastRootCertificate lastCertificate = c.lastRootCertificate
domains = []string{"local-ip.sh"} domains = []string{"local-ip.sh"}
} else { } else {
log.Fatalf("Unexpected certType %s. Only \"wildcard\" and \"root\" are supported", certType) utils.Logger.Fatal().Msgf("Unexpected certType %s. Only \"wildcard\" and \"root\" are supported", certType)
} }
log.Printf("requesting %s certificate\n", certType) utils.Logger.Info().Str("certType", certType).Msg("Requesting certificate")
if lastCertificate != nil { if lastCertificate != nil {
certificates, err := certcrypto.ParsePEMBundle(c.lastWildcardCertificate.Certificate) certificates, err := certcrypto.ParsePEMBundle(c.lastWildcardCertificate.Certificate)
if err != nil { if err != nil {
log.Fatal(err) utils.Logger.Fatal().Err(err).Msg("Failed to parse PEM bundle from last certificate")
} }
x509Cert := certificates[0] x509Cert := certificates[0]
timeLeft := x509Cert.NotAfter.Sub(time.Now().UTC()) timeLeft := x509Cert.NotAfter.Sub(time.Now().UTC())
if timeLeft > time.Hour*24*30 { if timeLeft > time.Hour*24*30 {
log.Printf("%d days left before expiration, will not renew", int(timeLeft.Hours()/24)) utils.Logger.Info().Msgf("%d days left before expiration, skip renewal", int(timeLeft.Hours()/24))
return return
} }
@ -57,36 +57,34 @@ func (c *certsClient) requestCertificate(certType string) {
return return
} }
certificates, err := c.legoClient.Certificate.Obtain(certificate.ObtainRequest{ cert, err := c.legoClient.Certificate.Obtain(certificate.ObtainRequest{Domains: domains, Bundle: true})
Domains: domains,
Bundle: true,
})
if err != nil { if err != nil {
log.Fatal(err) utils.Logger.Fatal().Err(err).Msg("Failed to obtain certificate from lego client")
} }
if certType == "wildcard" { if certType == "wildcard" {
c.lastWildcardCertificate = certificates c.lastWildcardCertificate = cert
} else if certType == "root" { } else if certType == "root" {
c.lastRootCertificate = certificates c.lastRootCertificate = cert
} }
persistFiles(certificates, certType) persistFiles(cert, certType)
} }
func (c *certsClient) renewCertificates() { func (c *certsClient) renewCertificates() {
log.Println("renewing currently existing certificate") utils.Logger.Info().Msg("Renewing certificates")
wildcardCertificate, err := c.legoClient.Certificate.Renew(*c.lastWildcardCertificate, true, false, "") wildcardCertificate, err := c.legoClient.Certificate.Renew(*c.lastWildcardCertificate, true, false, "")
if err != nil { if err != nil {
log.Fatal(err) utils.Logger.Fatal().Err(err).Msg("Failed to renew wildcard certificate")
} }
c.lastWildcardCertificate = wildcardCertificate c.lastWildcardCertificate = wildcardCertificate
persistFiles(wildcardCertificate, "wildcard") persistFiles(wildcardCertificate, "wildcard")
rootCertificate, err := c.legoClient.Certificate.Renew(*c.lastRootCertificate, true, false, "") rootCertificate, err := c.legoClient.Certificate.Renew(*c.lastRootCertificate, true, false, "")
if err != nil { if err != nil {
log.Fatal(err) utils.Logger.Fatal().Err(err).Msg("Failed to renew root certificate")
} }
c.lastRootCertificate = rootCertificate c.lastRootCertificate = rootCertificate
persistFiles(rootCertificate, "root") persistFiles(rootCertificate, "root")
@ -94,14 +92,30 @@ func (c *certsClient) renewCertificates() {
} }
func persistFiles(certificates *certificate.Resource, certType string) { func persistFiles(certificates *certificate.Resource, certType string) {
os.MkdirAll(fmt.Sprintf("/certs/%s", certType), 0o755) err := os.MkdirAll(fmt.Sprintf("/certs/%s", certType), 0o755)
os.WriteFile(fmt.Sprintf("/certs/%s/server.pem", certType), certificates.Certificate, 0o644) if err != nil {
utils.Logger.Fatal().Err(err).Msgf("Failed to mkdir /certs/%s", certType)
}
err = os.WriteFile(fmt.Sprintf("/certs/%s/server.pem", certType), certificates.Certificate, 0o644)
if err != nil {
utils.Logger.Fatal().Err(err).Msgf("Failed to save /certs/%s/server.pem", certType)
}
os.WriteFile(fmt.Sprintf("/certs/%s/server.key", certType), certificates.PrivateKey, 0o644) os.WriteFile(fmt.Sprintf("/certs/%s/server.key", certType), certificates.PrivateKey, 0o644)
if err != nil {
utils.Logger.Fatal().Err(err).Msgf("Failed to save /certs/%s/server.key", certType)
}
jsonBytes, err := json.MarshalIndent(certificates, "", "\t") jsonBytes, err := json.MarshalIndent(certificates, "", "\t")
if err != nil { if err != nil {
log.Fatal(err) utils.Logger.Fatal().Err(err).Msg("Failed to marshal certificates to JSON")
}
err = os.WriteFile(fmt.Sprintf("/certs/%s/output.json", certType), jsonBytes, 0o644)
if err != nil {
utils.Logger.Fatal().Err(err).Msgf("Failed to save /certs/%s/output.json", certType)
} }
os.WriteFile(fmt.Sprintf("/certs/%s/output.json", certType), jsonBytes, 0o644)
} }
func NewCertsClient(xip *xip.Xip, user *Account) *certsClient { func NewCertsClient(xip *xip.Xip, user *Account) *certsClient {
@ -109,7 +123,7 @@ func NewCertsClient(xip *xip.Xip, user *Account) *certsClient {
config.CADirURL = caDirUrl config.CADirURL = caDirUrl
legoClient, err := lego.NewClient(config) legoClient, err := lego.NewClient(config)
if err != nil { if err != nil {
log.Fatal(err) utils.Logger.Fatal().Err(err).Msg("Failed to initialize lego client")
} }
provider := newProviderLocalIp(xip) provider := newProviderLocalIp(xip)
@ -131,23 +145,20 @@ func getLastCertificate(legoClient *lego.Client, certType string) *certificate.R
if strings.Contains(err.Error(), "no such file or directory") { if strings.Contains(err.Error(), "no such file or directory") {
return nil return nil
} }
log.Println(err) utils.Logger.Error().Err(err).Msg("Failling back to getting a brand new cert")
log.Println("falling back to getting a brand new cert")
return nil return nil
} }
lastCertificate := &certificate.Resource{} lastCertificate := &certificate.Resource{}
err = json.Unmarshal(jsonBytes, lastCertificate) err = json.Unmarshal(jsonBytes, lastCertificate)
if err != nil { if err != nil {
log.Println(err) utils.Logger.Error().Err(err).Msg("Failling back to getting a brand new cert")
log.Println("falling back to getting a brand new cert")
return nil return nil
} }
lastCertificate, err = legoClient.Certificate.Get(lastCertificate.CertURL, true) lastCertificate, err = legoClient.Certificate.Get(lastCertificate.CertURL, true)
if err != nil { if err != nil {
log.Println(err) utils.Logger.Error().Err(err).Msg("Failling back to getting a brand new cert")
log.Println("falling back to getting a brand new cert")
return nil return nil
} }

View File

@ -3,6 +3,7 @@ package certs
import ( import (
"github.com/go-acme/lego/v4/challenge/dns01" "github.com/go-acme/lego/v4/challenge/dns01"
"local-ip.sh/utils"
"local-ip.sh/xip" "local-ip.sh/xip"
) )
@ -11,12 +12,14 @@ type DNSProviderLocalIp struct {
} }
func (d *DNSProviderLocalIp) Present(domain, token, keyAuth string) error { func (d *DNSProviderLocalIp) Present(domain, token, keyAuth string) error {
utils.Logger.Debug().Str("domain", domain).Msg("DNS01 challenge - present")
fqdn, value := dns01.GetRecord(domain, keyAuth) fqdn, value := dns01.GetRecord(domain, keyAuth)
d.xip.SetTXTRecord(fqdn, value) d.xip.SetTXTRecord(fqdn, value)
return nil return nil
} }
func (d *DNSProviderLocalIp) CleanUp(domain, token, keyAuth string) error { func (d *DNSProviderLocalIp) CleanUp(domain, token, keyAuth string) error {
utils.Logger.Debug().Str("domain", domain).Msg("DNS01 challenge - cleanup")
fqdn, _ := dns01.GetRecord(domain, keyAuth) fqdn, _ := dns01.GetRecord(domain, keyAuth)
d.xip.UnsetTXTRecord(fqdn) d.xip.UnsetTXTRecord(fqdn)
return nil return nil

11
go.mod
View File

@ -1,20 +1,23 @@
module local-ip.sh module local-ip.sh
go 1.21 go 1.22
require ( require (
github.com/go-acme/lego/v4 v4.10.1 github.com/go-acme/lego/v4 v4.10.1
github.com/miekg/dns v1.1.57 github.com/miekg/dns v1.1.57
github.com/rs/zerolog v1.33.0
golang.org/x/net v0.17.0
gopkg.in/natefinch/lumberjack.v2 v2.2.1
) )
require ( require (
github.com/cenkalti/backoff/v4 v4.2.0 // indirect github.com/cenkalti/backoff/v4 v4.2.0 // indirect
github.com/go-jose/go-jose/v3 v3.0.0 // indirect github.com/go-jose/go-jose/v3 v3.0.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
golang.org/x/crypto v0.14.0 // indirect golang.org/x/crypto v0.14.0 // indirect
golang.org/x/mod v0.12.0 // indirect golang.org/x/mod v0.12.0 // indirect
golang.org/x/net v0.17.0 // indirect golang.org/x/sys v0.22.0 // indirect
golang.org/x/sys v0.13.0 // indirect
golang.org/x/text v0.13.0 // indirect golang.org/x/text v0.13.0 // indirect
golang.org/x/tools v0.13.0 // indirect golang.org/x/tools v0.13.0 // indirect
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect
) )

76
go.sum
View File

@ -1,79 +1,61 @@
github.com/cenkalti/backoff/v4 v4.2.0 h1:HN5dHm3WBOgndBH6E8V0q2jIYIR3s9yglV8k/+MN3u4= github.com/cenkalti/backoff/v4 v4.2.0 h1:HN5dHm3WBOgndBH6E8V0q2jIYIR3s9yglV8k/+MN3u4=
github.com/cenkalti/backoff/v4 v4.2.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/cenkalti/backoff/v4 v4.2.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-acme/lego/v4 v4.10.1 h1:MiJvoBXNdmAwEK/SImyhwZ8ZL4IR0jtWDD1wST+N138= github.com/go-acme/lego/v4 v4.10.1 h1:MiJvoBXNdmAwEK/SImyhwZ8ZL4IR0jtWDD1wST+N138=
github.com/go-acme/lego/v4 v4.10.1/go.mod h1:EMbf0Jmqwv94nJ5WL9qWnSXIBZnvsS9gNypansHGc6U= github.com/go-acme/lego/v4 v4.10.1/go.mod h1:EMbf0Jmqwv94nJ5WL9qWnSXIBZnvsS9gNypansHGc6U=
github.com/go-jose/go-jose/v3 v3.0.0 h1:s6rrhirfEP/CGIoc6p+PZAeogN2SxKav6Wp7+dyMWVo= github.com/go-jose/go-jose/v3 v3.0.0 h1:s6rrhirfEP/CGIoc6p+PZAeogN2SxKav6Wp7+dyMWVo=
github.com/go-jose/go-jose/v3 v3.0.0/go.mod h1:RNkWWRld676jZEYoV3+XK8L2ZnNSvIsxFMht0mSX+u8= github.com/go-jose/go-jose/v3 v3.0.0/go.mod h1:RNkWWRld676jZEYoV3+XK8L2ZnNSvIsxFMht0mSX+u8=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/google/go-cmp v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w=
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/miekg/dns v1.1.50 h1:DQUfb9uc6smULcREF09Uc+/Gd46YWqJd5DbpPE9xkcA= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/miekg/dns v1.1.50/go.mod h1:e3IlAVfNqAllflbibAZEWOXOQ+Ynzk/dDozDxY7XnME= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/miekg/dns v1.1.57 h1:Jzi7ApEIzwEPLHWRcafCN9LZSBbqQpxjt/wpgvg7wcM= github.com/miekg/dns v1.1.57 h1:Jzi7ApEIzwEPLHWRcafCN9LZSBbqQpxjt/wpgvg7wcM=
github.com/miekg/dns v1.1.57/go.mod h1:uqRjCRUuEAA6qsOiJvDd+CFo/vW+y5WR6SNmHE55hZk= github.com/miekg/dns v1.1.57/go.mod h1:uqRjCRUuEAA6qsOiJvDd+CFo/vW+y5WR6SNmHE55hZk=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8=
github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190911031432-227b76d455e7/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190911031432-227b76d455e7/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.5.0 h1:U/0M97KRkSFvyD/3FSmdP5W5swImpNgle/EHFhOsQPE=
golang.org/x/crypto v0.5.0/go.mod h1:NK/OQwhpMQP3MwtdjgLlYHnH9ebylxKWv3e0fK+mkQU=
golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc= golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.8.0 h1:LUYupSeNrTNCGzR/hVBk2NHZO4hXcVaW1k4Qx7rjPx8=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc= golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc=
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985 h1:4CSI6oo7cOjJKajidEljs9h+uP0rRZBPPPhcCbj5mw8=
golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g=
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM=
golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.4.0 h1:zxkM55ReGkDlKSM+Fu41A+zmbZuaPVbGMzvvdUPznYQ=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.4.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c h1:F1jZWGFhYfh0Ci55sIpILtKKK8p3i2/krTr0H1rg74I= golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.6-0.20210726203631-07bc1bf47fb2 h1:BonxutuHCTL0rBDnZlKjpGIQFTjyUVTexFOdWkB6Fg0=
golang.org/x/tools v0.1.6-0.20210726203631-07bc1bf47fb2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.12 h1:VveCTK38A2rkS8ZqFY25HIDFscX5X9OoEhJd3quQmXU=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0 h1:BOw41kyTf3PuCW1pVQf8+Cyg8pMlkYB1oo9iJ6D/lKM=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.13.0 h1:Iey4qkscZuv0VvIt8E0neZjtPVQFSc870HQ448QgEmQ= golang.org/x/tools v0.13.0 h1:Iey4qkscZuv0VvIt8E0neZjtPVQFSc870HQ448QgEmQ=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 h1:H2TDz8ibqkAF6YGhCdN3jS9O0/s90v0rJh3X/OLHEUk=
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@ -1,14 +1,16 @@
package http package http
import ( import (
"log"
"net/http" "net/http"
"os" "os"
"strings" "strings"
"time" "time"
"local-ip.sh/utils"
) )
func ServeHttp() { func ServeHttp() {
utils.Logger.Info().Msg("Waiting until \"local-ip.sh\" certificate is delivered to start up HTTP server...")
waitForCertificate() waitForCertificate()
go http.ListenAndServe(":80", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { go http.ListenAndServe(":80", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@ -44,8 +46,12 @@ func ServeHttp() {
w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Content-Type", "text/html; charset=utf-8")
http.ServeFile(w, r, "./http/static/index.html") http.ServeFile(w, r, "./http/static/index.html")
}) })
log.Printf("Serving HTTPS server on :443\n")
http.ListenAndServeTLS(":443", "/certs/root/server.pem", "/certs/root/server.key", nil) utils.Logger.Info().Msg("Starting up HTTPS server on :443\n")
err := http.ListenAndServeTLS(":443", "/certs/root/server.pem", "/certs/root/server.key", nil)
if err != nil {
utils.Logger.Fatal().Err(err).Msg("Failed to start HTTPS server")
}
} }
func waitForCertificate() { func waitForCertificate() {
@ -56,7 +62,7 @@ func waitForCertificate() {
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
continue continue
} }
log.Fatal(err) utils.Logger.Fatal().Err(err).Msg("Unexpected error while looking for /certs/root/output.json")
} }
break break
} }

21
utils/logger.go Normal file
View File

@ -0,0 +1,21 @@
package utils
import (
"os"
"time"
"github.com/rs/zerolog"
"gopkg.in/natefinch/lumberjack.v2"
)
var consoleWriter = zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339}
var fileWriter = &lumberjack.Logger{
Filename: "/var/log/local-ip.sh.log",
MaxBackups: 3,
MaxSize: 1, // megabytes
MaxAge: 1, // days
Compress: true, // disabled by default
}
var multi = zerolog.MultiLevelWriter(consoleWriter, fileWriter)
var Logger = zerolog.New(multi).With().Timestamp().Logger()

View File

@ -2,7 +2,6 @@ package xip
import ( import (
"fmt" "fmt"
"log"
"net" "net"
"os" "os"
"regexp" "regexp"
@ -10,6 +9,7 @@ import (
"time" "time"
"github.com/miekg/dns" "github.com/miekg/dns"
"local-ip.sh/utils"
) )
type Xip struct { type Xip struct {
@ -96,9 +96,9 @@ var (
) )
func (xip *Xip) SetTXTRecord(fqdn string, value string) { func (xip *Xip) SetTXTRecord(fqdn string, value string) {
log.Printf("trying to set TXT record \"%s\" for fqdn \"%s\"", value, fqdn) utils.Logger.Debug().Str("fqdn", fqdn).Str("value", value).Msg("Trying to set TXT record")
if fqdn != "_acme-challenge.local-ip.sh." { if fqdn != "_acme-challenge.local-ip.sh." {
log.Println("not allowed, abort") utils.Logger.Debug().Msg("Not allowed, abort")
return return
} }
@ -109,9 +109,9 @@ func (xip *Xip) SetTXTRecord(fqdn string, value string) {
} }
func (xip *Xip) UnsetTXTRecord(fqdn string) { func (xip *Xip) UnsetTXTRecord(fqdn string) {
log.Printf("trying to unset TXT record for fqdn \"%s\"", fqdn) utils.Logger.Debug().Str("fqdn", fqdn).Msg("Trying to set TXT record")
if fqdn != "_acme-challenge.local-ip.sh." { if fqdn != "_acme-challenge.local-ip.sh." {
log.Println("not allowed, abort") utils.Logger.Debug().Msg("Not allowed, abort")
return return
} }
@ -180,7 +180,6 @@ func (xip *Xip) handleA(question dns.Question, message *dns.Msg) {
} }
for _, record := range records { for _, record := range records {
log.Printf("(%s) %s => %s\n", flyRegion, fqdn, record.A)
message.Answer = append(message.Answer, record) message.Answer = append(message.Answer, record)
} }
} }
@ -390,14 +389,21 @@ func (xip *Xip) handleDnsRequest(response dns.ResponseWriter, request *dns.Msg)
message.MsgHdr.Rcode = dns.RcodeRefused message.MsgHdr.Rcode = dns.RcodeRefused
} }
utils.Logger.Debug().Str("FLY_REGION", flyRegion).Any("question", request.Question).Any("answer", message.Answer).Msg("resolved")
error := response.WriteMsg(message) error := response.WriteMsg(message)
if error != nil { if error != nil {
log.Printf("Error writing answer \"%s\": %s\n", message.String(), error.Error()) utils.Logger.Error().Err(error).Str("message", message.String()).Msg("Error responding to query")
} }
}() }()
} }
func (xip *Xip) StartServer() { func (xip *Xip) StartServer() {
if _, exists := os.LookupEnv("FLY_APP_NAME"); exists {
// we're probably running on fly, bind to fly-global-services
xip.server.Addr = "fly-global-services" + xip.server.Addr
}
err := xip.server.ListenAndServe() err := xip.server.ListenAndServe()
defer xip.server.Shutdown() defer xip.server.Shutdown()
if err != nil { if err != nil {
@ -413,9 +419,9 @@ func (xip *Xip) StartServer() {
return return
} }
log.Fatalf("Failed to start server: %s\n ", err.Error()) utils.Logger.Fatal().Err(err).Msg("Failed to start DNS server")
} }
log.Printf("Listening on %s\n", xip.server.Addr) utils.Logger.Info().Str("dns_address", xip.server.Addr).Msg("DNS server listening")
} }
func NewXip(port int) (xip *Xip) { func NewXip(port int) (xip *Xip) {
@ -426,7 +432,7 @@ func NewXip(port int) (xip *Xip) {
} }
xip.server = dns.Server{ xip.server = dns.Server{
Addr: fmt.Sprintf("fly-global-services:%d", port), Addr: fmt.Sprintf(":%d", port),
Net: "udp", Net: "udp",
} }