Skip to content

Commit

Permalink
Added Custom Name Server Option
Browse files Browse the repository at this point in the history
  • Loading branch information
Sickjuicy committed Nov 26, 2024
1 parent 4a4483e commit e6b2d45
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 49 deletions.
50 changes: 27 additions & 23 deletions src/mod/acme/acme.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (

"github.com/go-acme/lego/v4/certcrypto"
"github.com/go-acme/lego/v4/certificate"
"github.com/go-acme/lego/v4/challenge/dns01"
"github.com/go-acme/lego/v4/challenge/http01"
"github.com/go-acme/lego/v4/lego"
"github.com/go-acme/lego/v4/registration"
Expand All @@ -30,11 +31,12 @@ import (
)

type CertificateInfoJSON struct {
AcmeName string `json:"acme_name"` //ACME provider name
AcmeUrl string `json:"acme_url"` //Custom ACME URL (if any)
SkipTLS bool `json:"skip_tls"` //Skip TLS verification of upstream
UseDNS bool `json:"dns"` //Use DNS challenge
PropTimeout int `json:"prop_time"` //Propagation timeout
AcmeName string `json:"acme_name"` //ACME provider name
AcmeUrl string `json:"acme_url"` //Custom ACME URL (if any)
SkipTLS bool `json:"skip_tls"` //Skip TLS verification of upstream
UseDNS bool `json:"dns"` //Use DNS challenge
PropTimeout int `json:"prop_time"` //Propagation timeout
DNSServers []string `json:"dnsServers"` // DNS servers
}

// ACMEUser represents a user in the ACME system.
Expand Down Expand Up @@ -94,7 +96,7 @@ func (a *ACMEHandler) Close() error {
}

// ObtainCert obtains a certificate for the specified domains.
func (a *ACMEHandler) ObtainCert(domains []string, certificateName string, email string, caName string, caUrl string, skipTLS bool, useDNS bool, propagationTimeout int) (bool, error) {
func (a *ACMEHandler) ObtainCert(domains []string, certificateName string, email string, caName string, caUrl string, skipTLS bool, useDNS bool, propagationTimeout int, dnsServers []string) (bool, error) {
a.Logf("Obtaining certificate for: "+strings.Join(domains, ", "), nil)

// generate private key
Expand All @@ -114,7 +116,6 @@ func (a *ACMEHandler) ObtainCert(domains []string, certificateName string, email
config := lego.NewConfig(&adminUser)

// skip TLS verify if need
// Ref: https://github.com/go-acme/lego/blob/6af2c756ac73a9cb401621afca722d0f4112b1b8/lego/client_config.go#L74
if skipTLS {
a.Logf("Ignoring TLS/SSL Verification Error for ACME Server", nil)
config.HTTPClient.Transport = &http.Transport{
Expand Down Expand Up @@ -150,7 +151,6 @@ func (a *ACMEHandler) ObtainCert(domains []string, certificateName string, email
config.CADirURL = caLinkOverwrite
a.Logf("Using "+caLinkOverwrite+" for CA Directory URL", nil)
} else {
// (caName == "" || caUrl == "") will use default acme
config.CADirURL = a.DefaultAcmeServer
a.Logf("Using Default ACME "+a.DefaultAcmeServer+" for CA Directory URL", nil)
}
Expand All @@ -168,11 +168,11 @@ func (a *ACMEHandler) ObtainCert(domains []string, certificateName string, email
if useDNS {
if !a.Database.TableExists("acme") {
a.Database.NewTable("acme")
return false, errors.New("DNS Provider and DNS Credenital configuration required for ACME Provider (Error -1)")
return false, errors.New("DNS Provider and DNS Credential configuration required for ACME Provider (Error -1)")
}

if !a.Database.KeyExists("acme", certificateName+"_dns_provider") || !a.Database.KeyExists("acme", certificateName+"_dns_credentials") {
return false, errors.New("DNS Provider and DNS Credenital configuration required for ACME Provider (Error -2)")
return false, errors.New("DNS Provider and DNS Credential configuration required for ACME Provider (Error -2)")
}

var dnsCredentials string
Expand All @@ -195,7 +195,11 @@ func (a *ACMEHandler) ObtainCert(domains []string, certificateName string, email
return false, err
}

err = client.Challenge.SetDNS01Provider(provider)
if len(dnsServers) > 0 {
err = client.Challenge.SetDNS01Provider(provider, dns01.AddRecursiveNameservers(dnsServers))
} else {
err = client.Challenge.SetDNS01Provider(provider)
}
if err != nil {
a.Logf("Failed to resolve DNS01 Provider", err)
return false, err
Expand All @@ -209,19 +213,9 @@ func (a *ACMEHandler) ObtainCert(domains []string, certificateName string, email
}

// New users will need to register
/*
reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
if err != nil {
log.Println(err)
return false, err
}
*/
var reg *registration.Resource
// New users will need to register
if client.GetExternalAccountRequired() {
a.Logf("External Account Required for this ACME Provider", nil)
// IF KID and HmacEncoded is overidden

if !a.Database.TableExists("acme") {
a.Database.NewTable("acme")
return false, errors.New("kid and HmacEncoded configuration required for ACME Provider (Error -1)")
Expand Down Expand Up @@ -257,7 +251,6 @@ func (a *ACMEHandler) ObtainCert(domains []string, certificateName string, email
a.Logf("Register with external account binder failed", err)
return false, err
}
//return false, errors.New("External Account Required for this ACME Provider.")
} else {
reg, err = client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
if err != nil {
Expand Down Expand Up @@ -298,6 +291,7 @@ func (a *ACMEHandler) ObtainCert(domains []string, certificateName string, email
SkipTLS: skipTLS,
UseDNS: useDNS,
PropTimeout: propagationTimeout,
DNSServers: dnsServers,
}

certInfoBytes, err := json.Marshal(certInfo)
Expand Down Expand Up @@ -479,12 +473,22 @@ func (a *ACMEHandler) HandleRenewCertificate(w http.ResponseWriter, r *http.Requ
}
}

// Extract DNS servers from the request
var dnsServers []string
dnsServersPara, err := utils.PostPara(r, "dnsServers")
if err == nil && dnsServersPara != "" {
dnsServers = strings.Split(dnsServersPara, ",")
for i := range dnsServers {
dnsServers[i] = strings.TrimSpace(dnsServers[i])
}
}

//Clean spaces in front or behind each domain
cleanedDomains := []string{}
for _, domain := range domains {
cleanedDomains = append(cleanedDomains, strings.TrimSpace(domain))
}
result, err := a.ObtainCert(cleanedDomains, filename, email, ca, caUrl, skipTLS, dns, propagationTimeout)
result, err := a.ObtainCert(cleanedDomains, filename, email, ca, caUrl, skipTLS, dns, propagationTimeout, dnsServers)
if err != nil {
utils.SendErrorResponse(w, jsonEscape(err.Error()))
return
Expand Down
13 changes: 9 additions & 4 deletions src/mod/acme/autorenew.go
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,6 @@ func (a *AutoRenewer) CheckAndRenewCertificates() ([]string, error) {
return a.renewExpiredDomains(expiredCertList)
}

// Close the auto renewer
func (a *AutoRenewer) Close() {
if a.TickerstopChan != nil {
a.TickerstopChan <- true
Expand Down Expand Up @@ -384,13 +383,19 @@ func (a *AutoRenewer) renewExpiredDomains(certs []*ExpiredCerts) ([]string, erro
}
}

//For upgrading config from older version of Zoraxy which don't have timeout
// For upgrading config from older version of Zoraxy which don't have timeout
if certInfo.PropTimeout == 0 {
//Set default timeout
// Set default timeout
certInfo.PropTimeout = 300
}

_, err = a.AcmeHandler.ObtainCert(expiredCert.Domains, certName, a.RenewerConfig.Email, certInfo.AcmeName, certInfo.AcmeUrl, certInfo.SkipTLS, certInfo.UseDNS, certInfo.PropTimeout)
// Extract DNS servers from the certificate info if available
var dnsServers []string
if certInfo.DNSServers != nil {
dnsServers = certInfo.DNSServers
}

_, err = a.AcmeHandler.ObtainCert(expiredCert.Domains, certName, a.RenewerConfig.Email, certInfo.AcmeName, certInfo.AcmeUrl, certInfo.SkipTLS, certInfo.UseDNS, certInfo.PropTimeout, dnsServers)
if err != nil {
a.Logf("Renew "+fileName+"("+strings.Join(expiredCert.Domains, ",")+") failed", err)
} else {
Expand Down
36 changes: 14 additions & 22 deletions src/web/snippet/acme.html
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@
</style>
</head>
<body>
<link rel="stylesheet" href="../darktheme.css">
<script src="../script/darktheme.js"></script>
<br>
<div class="ui container">
<div class="ui header">
Expand All @@ -52,7 +50,7 @@ <h3>ACME Email</h3>
</div>
<small>If you don't want to share your private email address, you can also fill in an email address that point to a mailbox not exists on your domain.</small>
</div>
<div class="ui basic segment advanceoptions">
<div class="ui basic segment" style="background-color: #f7f7f7; border-radius: 1em;">
<div class="ui accordion advanceSettings">
<div class="title">
<i class="dropdown icon"></i>
Expand Down Expand Up @@ -137,6 +135,13 @@ <h3>Generate New Certificate</h3>
<!-- Auto populate moved to acmedns module and initDNSProviderList() -->
</div>
</div>
<div class="ui form">
<div class="field">
<label>Domain Name Server (optional)</label>
<input id="dnsInput" type="text" placeholder="ns.example.com" onkeyup="handlePostInputAutomation();">
<small>If you have more than one DNS server, enter them separated by commas (e.g. ns1.example.com,ns2.example.com)
</small>
</div>
</div>
<div class="field dnsChallengeOnly" style="display:none;">
<div class="ui divider"></div>
Expand Down Expand Up @@ -439,15 +444,11 @@ <h4><i class="yellow exclamation triangle icon"></i> Notes & FAQ</h4>
let optionalFieldsHTML = "";
for (const [key, datatype] of Object.entries(data)) {
if (datatype == "int"){
let defaultValue = 10;
if (key == "HTTPTimeout"){
defaultValue = 300;
}
$("#dnsProviderAPIFields").append(`<div class="ui fluid labeled dnsConfigField input typeint" key="${key}" style="margin-top: 0.2em;">
$("#dnsProviderAPIFields").append(`<div class="ui fluid labeled dnsConfigField input" key="${key}" style="margin-top: 0.2em;">
<div class="ui basic blue label" style="font-weight: 300;">
${key}
</div>
<input type="number" value="${defaultValue}">
<input type="number" value="300">
</div>`);
}else if (datatype == "bool"){
booleanFieldsHTML += (`<div class="ui checkbox dnsConfigField" key="${key}" style="margin-top: 1em !important; padding-left: 0.4em;">
Expand Down Expand Up @@ -606,12 +607,8 @@ <h4><i class="yellow exclamation triangle icon"></i> Notes & FAQ</h4>
//Boolean option
let checked = $(this).find("input")[0].checked;
dnsCredentials[thisKey] = checked;
}else if ($(this).hasClass("typeint")){
//Int options
let value = $(this).find("input").val();
dnsCredentials[thisKey] = parseInt(value);
}else{
//String options
//String or int options
let value = $(this).find("input").val().trim();
dnsCredentials[thisKey] = value;
}
Expand Down Expand Up @@ -725,18 +722,17 @@ <h4><i class="yellow exclamation triangle icon"></i> Notes & FAQ</h4>
if (callback != undefined){callback(false);}
return;
}



var ca = $("#ca").dropdown("get value");
var caURL = "";
if (ca == "Custom ACME Server") {
ca = "custom";
caURL = $("#caURL").val();
}


var dns = $("#useDnsChallenge")[0].checked;
var skipTLSValue = $("#skipTLSCheckbox")[0].checked;
var dnsServers = $("#dnsInput").val(); // New line: Read DNS servers from input field

$.ajax({
url: "/api/acme/obtainCert",
Expand All @@ -749,22 +745,18 @@ <h4><i class="yellow exclamation triangle icon"></i> Notes & FAQ</h4>
caURL: caURL,
skipTLS: skipTLSValue,
dns: dns,
dnsServers: dnsServers // New line: Include DNS servers in the request
},
success: function(response) {
$("#obtainButton").removeClass("loading").removeClass("disabled");
if (response.error) {
console.log("Error:", response.error);
// Show error message
parent.msgbox(response.error, false, 12000);
if (callback != undefined){callback(false);}
} else {
console.log("Certificate renewed successfully");
// Show success message
parent.msgbox("Certificate renewed successfully");

// Renew the parent certificate list
parent.initManagedDomainCertificateList();

if (callback != undefined){callback(true);}
}
},
Expand Down

0 comments on commit e6b2d45

Please sign in to comment.