fix: server_name split issue in SAN cert

This commit is contained in:
0xJacky 2023-02-15 10:44:30 +08:00
parent bf3edfaa44
commit 175d19a206
No known key found for this signature in database
GPG key ID: B6E4A6E4A561BAF0
17 changed files with 534 additions and 534 deletions

View file

@ -525,7 +525,7 @@ function initSortable() {
:okText="$gettext('OK')"
:title="$gettext('Are you sure you want to delete?')"
@confirm="destroy(record[rowKey])">
<a-button type="link" size="small" v-translate>Delete</a-button>
<a-button type="link" size="small">{{ $gettext('Delete') }}</a-button>
</a-popconfirm>
</template>
</template>

View file

@ -164,7 +164,7 @@ function wsOnMessage(m: { data: any }) {
</p>
<p v-if="cpu_info">
{{ $gettext('CPU:') + ' ' }}
<span class="cpu-model">{{ cpu_info[0]?.modelName }}</span>
<span class="cpu-model">{{ cpu_info[0]?.modelName || 'core' }}</span>
<span class="cpu-mhz">{{ (cpu_info[0]?.mhz / 1000).toFixed(2) + 'GHz' }}</span>
* {{ cpu_info.length }}
</p>
@ -303,10 +303,6 @@ function wsOnMessage(m: { data: any }) {
}
}
.os-platform {
text-transform: capitalize;
}
.load-avg-describe {
@media (max-width: 1600px) and (min-width: 1200px) {
display: none;

View file

@ -25,7 +25,7 @@ watch(route, () => {
const update = ref(0)
const ngx_config = reactive({
filename: '',
name: '',
upstreams: [],
servers: []
})

View file

@ -7,7 +7,7 @@ import ChangeCert from '@/views/domain/cert/ChangeCert.vue'
const {$gettext} = useGettext()
const props = defineProps(['directivesMap', 'current_server_directives', 'enabled', 'cert_info'])
const props = defineProps(['config_name', 'directivesMap', 'current_server_directives', 'enabled', 'cert_info'])
const emit = defineEmits(['callback', 'update:enabled'])
@ -38,6 +38,7 @@ const enabled = computed({
<change-cert :directives-map="props.directivesMap"/>
<issue-cert
:config_name="config_name"
:current_server_directives="props.current_server_directives"
:directives-map="props.directivesMap"
v-model:enabled="enabled"

View file

@ -1,6 +1,6 @@
<script setup lang="ts">
import {useGettext} from 'vue3-gettext'
import {computed, h, nextTick, onMounted, ref, VNode, watch} from 'vue'
import {computed, nextTick, ref, watch} from 'vue'
import {message} from 'ant-design-vue'
import domain from '@/api/domain'
import websocket from '@/lib/websocket'
@ -8,7 +8,7 @@ import Template from '@/views/template/Template.vue'
const {$gettext, interpolate} = useGettext()
const props = defineProps(['directivesMap', 'current_server_directives', 'enabled'])
const props = defineProps(['config_name', 'directivesMap', 'current_server_directives', 'enabled'])
const emit = defineEmits(['changeEnabled', 'callback', 'update:enabled'])
@ -50,7 +50,7 @@ function job() {
})
}
}).then(() => {
issue_cert(name.value, callback)
issue_cert(props.config_name, name.value, callback)
})
}
@ -61,13 +61,13 @@ function callback(ssl_certificate: string, ssl_certificate_key: string) {
function change_auto_cert(r: boolean) {
if (r) {
domain.add_auto_cert(name.value).then(() => {
domain.add_auto_cert(props.config_name).then(() => {
message.success(interpolate($gettext('Auto-renewal enabled for %{name}'), {name: name.value}))
}).catch(e => {
message.error(e.message ?? interpolate($gettext('Enable auto-renewal failed for %{name}'), {name: name.value}))
})
} else {
domain.remove_auto_cert(name.value).then(() => {
domain.remove_auto_cert(props.config_name).then(() => {
message.success(interpolate($gettext('Auto-renewal disabled for %{name}'), {name: name.value}))
}).catch(e => {
message.error(e.message ?? interpolate($gettext('Disable auto-renewal failed for %{name}'), {name: name.value}))
@ -86,7 +86,7 @@ function log(msg: string) {
(logContainer.value as any as Element).scroll({top: 320, left: 0, behavior: 'smooth'})
}
const issue_cert = async (server_name: string, callback: Function) => {
const issue_cert = async (config_name: string, server_name: string, callback: Function) => {
progressStatus.value = 'active'
modalClosable.value = false
modalVisible.value = true
@ -95,7 +95,7 @@ const issue_cert = async (server_name: string, callback: Function) => {
log($gettext('Getting the certificate, please wait...'))
const ws = websocket('/api/cert/issue', false)
const ws = websocket(`/api/domain/${config_name}/cert`, false)
ws.onopen = () => {
ws.send(JSON.stringify({

View file

@ -168,6 +168,7 @@ watch(current_server_index, () => {
<template v-if="current_support_ssl&&enabled">
<cert
v-if="current_support_ssl"
:config_name="ngx_config.name"
:cert_info="props.cert_info?.[k]"
:current_server_directives="current_server_directives"
:directives-map="directivesMap"

View file

@ -66,7 +66,7 @@ export default defineConfig({
server: {
proxy: {
'/api': {
target: 'https://nginx.jackyu.cn/',
target: 'http://127.0.0.1:9001/',
changeOrigin: true,
secure: false,
ws: true

1
go.mod
View file

@ -39,6 +39,7 @@ require (
github.com/jpillora/s3 v1.1.4 // indirect
github.com/json-iterator/go v1.1.9 // indirect
github.com/leodido/go-urn v1.2.0 // indirect
github.com/lib/pq v1.10.7 // indirect
github.com/mattn/go-isatty v0.0.12 // indirect
github.com/mattn/go-sqlite3 v1.14.5 // indirect
github.com/miekg/dns v1.1.40 // indirect

2
go.sum
View file

@ -280,6 +280,8 @@ github.com/labstack/echo/v4 v4.1.11/go.mod h1:i541M3Fj6f76NZtHSj7TXnyM8n2gaodfvf
github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k=
github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y=
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
github.com/lib/pq v1.10.7 h1:p7ZhMD+KsSRozJr34udlUrhboJwWAgCg34+/ZZNvZZw=
github.com/lib/pq v1.10.7/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/linode/linodego v0.25.3/go.mod h1:GSBKPpjoQfxEfryoCRcgkuUOCuVtGHWhzI8OMdycNTE=
github.com/liquidweb/go-lwApi v0.0.0-20190605172801-52a4864d2738/go.mod h1:0sYF9rMXb0vlG+4SzdiGMXHheCZxjguMq+Zb4S2BfBs=
github.com/liquidweb/go-lwApi v0.0.5/go.mod h1:0sYF9rMXb0vlG+4SzdiGMXHheCZxjguMq+Zb4S2BfBs=

View file

@ -54,7 +54,7 @@ func prog(state overseer.State) {
}
s := gocron.NewScheduler(time.UTC)
job, err := s.Every(1).Hour().SingletonMode().Do(cert.AutoCert)
job, err := s.Every(1).Minute().SingletonMode().Do(cert.AutoObtain)
if err != nil {
log.Fatalf("AutoCert Job: %v, Err: %v\n", job, err)

View file

@ -87,8 +87,6 @@ func IssueCert(c *gin.Context) {
go cert.IssueCert(buffer.ServerName, logChan, errChan)
domain := strings.Join(buffer.ServerName, "_")
go handleIssueCertLogChan(ws, logChan)
// block, unless errChan closed
@ -110,22 +108,29 @@ func IssueCert(c *gin.Context) {
close(logChan)
sslCertificatePath := nginx.GetConfPath("ssl", domain, "fullchain.cer")
sslCertificateKeyPath := nginx.GetConfPath("ssl", domain, "private.key")
certDirName := strings.Join(buffer.ServerName, "_")
sslCertificatePath := nginx.GetConfPath("ssl", certDirName, "fullchain.cer")
sslCertificateKeyPath := nginx.GetConfPath("ssl", certDirName, "private.key")
certModel, err := model.FirstOrCreateCert(domain)
certModel, err := model.FirstOrCreateCert(c.Param("name"))
if err != nil {
log.Println(err)
}
err = certModel.Updates(&model.Cert{
Domains: buffer.ServerName,
SSLCertificatePath: sslCertificatePath,
SSLCertificateKeyPath: sslCertificateKeyPath,
})
if err != nil {
log.Println(err)
err = ws.WriteJSON(IssueCertResponse{
Status: Error,
Message: err.Error(),
})
return
}
err = ws.WriteJSON(IssueCertResponse{
@ -150,9 +155,9 @@ func GetCertList(c *gin.Context) {
})
}
func getCert(c *gin.Context, certModel model.Cert) {
func getCert(c *gin.Context, certModel *model.Cert) {
type resp struct {
model.Cert
*model.Cert
SSLCertification string `json:"ssl_certification"`
SSLCertificationKey string `json:"ssl_certification_key"`
CertificateInfo *CertificateInfo `json:"certificate_info,omitempty"`
@ -202,13 +207,12 @@ func GetCert(c *gin.Context) {
return
}
getCert(c, certModel)
getCert(c, &certModel)
}
func AddCert(c *gin.Context) {
var json struct {
Name string `json:"name"`
Domain string `json:"domain" binding:"required"`
SSLCertificatePath string `json:"ssl_certificate_path" binding:"required"`
SSLCertificateKeyPath string `json:"ssl_certificate_key_path" binding:"required"`
SSLCertification string `json:"ssl_certification"`
@ -217,19 +221,13 @@ func AddCert(c *gin.Context) {
if !BindAndValid(c, &json) {
return
}
certModel, err := model.FirstOrCreateCert(json.Domain)
if err != nil {
ErrHandler(c, err)
return
}
err = certModel.Updates(&model.Cert{
certModel := &model.Cert{
Name: json.Name,
Domain: json.Domain,
SSLCertificatePath: json.SSLCertificatePath,
SSLCertificateKeyPath: json.SSLCertificateKeyPath,
})
}
err := certModel.Insert()
if err != nil {
ErrHandler(c, err)
@ -291,7 +289,6 @@ func ModifyCert(c *gin.Context) {
err = certModel.Updates(&model.Cert{
Name: json.Name,
Domain: json.Domain,
SSLCertificatePath: json.SSLCertificatePath,
SSLCertificateKeyPath: json.SSLCertificateKeyPath,
})

View file

@ -104,15 +104,8 @@ func GetDomain(c *gin.Context) {
c.Set("maybe_error", "")
certInfoMap := make(map[int]CertificateInfo)
var serverName string
for serverIdx, server := range config.Servers {
for _, directive := range server.Directives {
if directive.Directive == "server_name" {
serverName = strings.ReplaceAll(directive.Params, " ", "_")
continue
}
if directive.Directive == "ssl_certificate" {
pubKey, err := cert.GetCertInfo(directive.Params)
@ -134,7 +127,7 @@ func GetDomain(c *gin.Context) {
}
}
certModel, _ := model.FirstCert(serverName)
certModel, _ := model.FirstCert(name)
c.Set("maybe_error", "nginx_config_syntax_error")
@ -304,7 +297,7 @@ func DisableDomain(c *gin.Context) {
}
// delete auto cert record
certModel := model.Cert{Domain: c.Param("name")}
certModel := model.Cert{Filename: c.Param("name")}
err = certModel.Remove()
if err != nil {
ErrHandler(c, err)
@ -345,7 +338,7 @@ func DeleteDomain(c *gin.Context) {
return
}
certModel := model.Cert{Domain: name}
certModel := model.Cert{Filename: name}
_ = certModel.Remove()
err = os.Remove(availablePath)
@ -362,9 +355,8 @@ func DeleteDomain(c *gin.Context) {
}
func AddDomainToAutoCert(c *gin.Context) {
domain := c.Param("domain")
domain = strings.ReplaceAll(domain, " ", "_")
certModel, err := model.FirstOrCreateCert(domain)
name := c.Param("name")
certModel, err := model.FirstOrCreateCert(name)
if err != nil {
ErrHandler(c, err)
@ -384,10 +376,9 @@ func AddDomainToAutoCert(c *gin.Context) {
}
func RemoveDomainFromAutoCert(c *gin.Context) {
domain := c.Param("domain")
domain = strings.ReplaceAll(domain, " ", "_")
name := c.Param("name")
certModel := model.Cert{
Domain: domain,
Filename: name,
}
err := certModel.Updates(&model.Cert{

View file

@ -2,6 +2,7 @@ package model
import (
"github.com/0xJacky/Nginx-UI/server/pkg/nginx"
"github.com/lib/pq"
"os"
)
@ -10,28 +11,35 @@ const (
AutoCertDisabled = -1
)
type CertDomains []string
type Cert struct {
Model
Name string `json:"name"`
Domain string `json:"domain"`
Domains pq.StringArray `json:"domains" gorm:"type:text[]"`
Filename string `json:"filename"`
SSLCertificatePath string `json:"ssl_certificate_path"`
SSLCertificateKeyPath string `json:"ssl_certificate_key_path"`
AutoCert int `json:"auto_cert"`
}
func FirstCert(domain string) (c Cert, err error) {
func FirstCert(confName string) (c Cert, err error) {
err = db.First(&c, &Cert{
Domain: domain,
Filename: confName,
}).Error
return
}
func FirstOrCreateCert(domain string) (c Cert, err error) {
err = db.FirstOrCreate(&c, &Cert{Domain: domain}).Error
func FirstOrCreateCert(confName string) (c Cert, err error) {
err = db.FirstOrCreate(&c, &Cert{Filename: confName}).Error
return
}
func (c *Cert) Insert() error {
return db.Create(c).Error
}
func GetAutoCertList() (c []Cert) {
var t []Cert
db.Where("auto_cert", AutoCertEnabled).Find(&t)
@ -49,7 +57,7 @@ func GetAutoCertList() (c []Cert) {
}
for _, v := range t {
if enabledConfigMap[v.Domain] == true {
if enabledConfigMap[v.Filename] == true {
c = append(c, v)
}
}
@ -76,9 +84,9 @@ func FirstCertByID(id int) (c Cert, err error) {
}
func (c *Cert) Updates(n *Cert) error {
return db.Model(c).Updates(n).Error
return db.Model(&Cert{}).Where("filename", c.Filename).Updates(n).Error
}
func (c *Cert) Remove() error {
return db.Where("domain", c.Domain).Delete(c).Error
return db.Where("filename", c.Filename).Delete(c).Error
}

View file

@ -3,7 +3,6 @@ package cert
import (
"github.com/0xJacky/Nginx-UI/server/model"
"log"
"strings"
"time"
)
@ -19,7 +18,7 @@ func handleIssueCertLogChan(logChan chan string) {
}
}
func AutoCert() {
func AutoObtain() {
defer func() {
if err := recover(); err != nil {
log.Println("[AutoCert] Recover", err)
@ -27,19 +26,12 @@ func AutoCert() {
}()
log.Println("[AutoCert] Start")
autoCertList := model.GetAutoCertList()
for i := range autoCertList {
domain := autoCertList[i].Domain
certModel, err := model.FirstCert(domain)
if err != nil {
log.Println("[AutoCert] Error get certificate from database", err)
continue
}
for _, certModel := range autoCertList {
confName := certModel.Filename
if certModel.SSLCertificatePath == "" {
log.Println("[AutoCert] Error ssl_certificate_path is empty, " +
"try to reopen auto-cert for this domain:" + domain)
"try to reopen auto-cert for this config:" + confName)
continue
}
@ -49,16 +41,17 @@ func AutoCert() {
// Get certificate info error, ignore this domain
continue
}
// before 1 mo
if time.Now().Before(cert.NotBefore.AddDate(0, 1, 0)) {
// every week
if time.Now().Sub(cert.NotBefore).Hours()/24 < 7 {
continue
}
//
// after 1 mo, reissue certificate
logChan := make(chan string, 1)
errChan := make(chan error, 1)
// support SAN certification
go IssueCert(strings.Split(domain, "_"), logChan, errChan)
go IssueCert(certModel.Domains, logChan, errChan)
go handleIssueCertLogChan(logChan)
@ -69,4 +62,5 @@ func AutoCert() {
close(logChan)
}
log.Println("[AutoCert] End")
}

View file

@ -5,6 +5,7 @@ import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"github.com/0xJacky/Nginx-UI/server/pkg/nginx"
"github.com/0xJacky/Nginx-UI/server/settings"
"github.com/go-acme/lego/v4/certcrypto"
@ -14,6 +15,7 @@ import (
"github.com/go-acme/lego/v4/registration"
"github.com/pkg/errors"
"log"
"net/http"
"os"
"path/filepath"
"strings"
@ -65,6 +67,11 @@ func IssueCert(domain []string, logChan chan string, errChan chan error) {
if settings.ServerSettings.CADir != "" {
config.CADirURL = settings.ServerSettings.CADir
if config.HTTPClient != nil {
config.HTTPClient.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
}
config.Certificate.KeyType = certcrypto.RSA2048

View file

@ -2,11 +2,13 @@ package nginx
import (
"github.com/tufanbarisyildirim/gonginx"
"path"
"strings"
)
type NgxConfig struct {
FileName string `json:"file_name"`
Name string `json:"name"`
Upstreams []*NgxUpstream `json:"upstreams"`
Servers []*NgxServer `json:"servers"`
Custom string `json:"custom"`
@ -57,5 +59,6 @@ func NewNgxConfig(filename string) *NgxConfig {
return &NgxConfig{
FileName: filename,
Upstreams: make([]*NgxUpstream, 0),
Name: path.Base(filename),
}
}

View file

@ -76,6 +76,7 @@ func InitRouter() *gin.Engine {
g.DELETE("domain/:name", api.DeleteDomain)
// duplicate site
g.POST("domain/:name/duplicate", api.DuplicateSite)
g.GET("domain/:name/cert", api.IssueCert)
g.GET("configs", api.GetConfigs)
g.GET("config/*name", api.GetConfig)
@ -90,17 +91,15 @@ func InitRouter() *gin.Engine {
g.GET("template/blocks", api.GetTemplateBlockList)
g.GET("template/block/:name", api.GetTemplateBlock)
g.GET("cert/issue", api.IssueCert)
g.GET("certs", api.GetCertList)
g.GET("cert/:id", api.GetCert)
g.POST("cert", api.AddCert)
g.POST("cert/:id", api.ModifyCert)
g.DELETE("cert/:id", api.RemoveCert)
// Add domain to auto-renew cert list
g.POST("auto_cert/:domain", api.AddDomainToAutoCert)
g.POST("auto_cert/:name", api.AddDomainToAutoCert)
// Delete domain from auto-renew cert list
g.DELETE("auto_cert/:domain", api.RemoveDomainFromAutoCert)
g.DELETE("auto_cert/:name", api.RemoveDomainFromAutoCert)
// pty
g.GET("pty", api.Pty)