added createrootcertificateifnotexists
Build / Build (push) Successful in 19s

This commit is contained in:
wt
2025-07-21 22:11:04 +07:00
parent 39c27b0de3
commit e6526fb780
8 changed files with 169 additions and 114 deletions
+6 -4
View File
@@ -6,6 +6,7 @@ import (
"net/http"
"os"
"scm/model"
"scm/utils"
)
func RootCert(w http.ResponseWriter, r *http.Request) {
@@ -16,7 +17,6 @@ func RootCert(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, `{"status":"ok"}`)
case "POST":
var rootCertRequest model.CreateRootCertRequest
@@ -25,9 +25,11 @@ func RootCert(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
err = utils.CreateRootKeyCertificate(rootCertRequest)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, `{"status":"ok"}`)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+76 -36
View File
@@ -8,6 +8,7 @@
<script src="js/theme.js" defer></script>
<script src="js/certs.js" defer></script>
<script src="js/create_cert.js" defer></script>
<script src="js/rootcrt.js" defer></script>
<title>Scm</title>
</head>
<style>
@@ -305,81 +306,120 @@
</div>
</div>
</div>
<div class="modal fade" tabindex="-1" id="create_certificate">
<div class="modal fade" tabindex="-1" id="createRootCertificate">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Create SSl Certificate</h5>
<button
type="button"
data-bs-dismiss="modal"
aria-label="Close"
class="btn-close"
></button>
<h5 class="modal-title">
Create rootCA SSl Certificate
</h5>
</div>
<div class="modal-body">
<div class="form-floating mb-3">
<input
type="text"
id="domain"
id="rootcommonname"
class="form-control"
placeholder="example.domain"
/>
<label for="domain">Domain</label>
<label for="rootcommonname">Common Name</label>
</div>
<div class="form-floating mb-3">
<input
type="text"
id="commonname"
class="form-control"
placeholder="commonname"
/>
<label for="commonname">Common Name</label>
</div>
<div class="form-floating mb-3">
<input
type="text"
id="organizationname"
id="rootorganizationname"
class="form-control"
placeholder="organizationname"
/>
<label for="organizationname"
<label for="rootorganizationname"
>Organization Name</label
>
</div>
<div class="form-floating mb-3">
<input
type="text"
id="organizationunit"
id="rootorganizationalunit"
class="form-control"
placeholder="organizationunit"
placeholder="organizationalunit"
/>
<label for="organizationunit"
>Organization Unit</label
<label for="rootorganizationalunit"
>Organizational Unit</label
>
</div>
<div class="form-floating mb-3">
<input
type="text"
id="rootCountry"
class="form-control"
placeholder="Country"
/>
<label for="rootCountry">Country</label>
</div>
<div class="form-floating mb-3">
<input
type="text"
id="rootLocality"
class="form-control"
placeholder="Asia/Novosibirsk"
/>
<label for="rootLocality">Locality</label>
</div>
<div class="form-floating mb-3">
<input
type="text"
id="rootProvince"
class="form-control"
placeholder="Tomsk Oblast"
/>
<label for="rootProvince">Province</label>
</div>
<div class="form-floating mb-3">
<input
type="text"
id="rootStreetAddress"
class="form-control"
placeholder="Tomsk Oblast, Russia"
/>
<label for="rootStreetAddress"
>Street address</label
>
</div>
<div class="form-floating mb-3">
<input
type="text"
id="rootPostalCode"
class="form-control"
placeholder="646037"
/>
<label for="rootPostalCode">Postal code</label>
</div>
<div class="form-floating mb-3">
<input
type="number"
id="rootValidityYears"
class="form-control"
placeholder="10"
/>
<label for="rootValidityYears"
>Validity years</label
>
</div>
<div class="form-floating mb-3">
<input
type="password"
id="password"
id="rootkeypassword"
class="form-control"
placeholder="example.domain"
placeholder="Password"
/>
<label for="password">RootCA password</label>
<label for="rootkeypassword">Password</label>
</div>
</div>
<div class="modal-footer">
<button
type="button"
data-bs-dismiss="modal"
class="btn btn-secondary"
>
Close
</button>
<button
id="createcert"
id="createRootCrt"
type="button"
class="btn btn-primary"
style="width: 100%"
>
Create
</button>
+65
View File
@@ -0,0 +1,65 @@
const createRootCertificateModal = bootstrap.Modal.getOrCreateInstance(
document.querySelector("#createRootCertificate"),
);
const createRootCrtButton = document.querySelector("#createRootCrt");
const rootcommonnameinput = document.querySelector("#rootcommonname");
const rootorganizationinput = document.querySelector("#rootorganizationname");
const rootorganizationalunitinput = document.querySelector(
"#rootorganizationalunit",
);
const rootcountryinput = document.querySelector("#rootCountry");
const rootlocalityinput = document.querySelector("#rootLocality");
const rootprovinceinput = document.querySelector("#rootProvince");
const rootstreetaddressinput = document.querySelector("#rootStreetAddress");
const rootpostalcodeinput = document.querySelector("#rootPostalCode");
const rootvalidityyearsinput = document.querySelector("#rootValidityYears");
const rootkeypasswordinput = document.querySelector("#rootkeypassword");
const getRootCrt = () => {
fetch(window.location.origin + "/api/certs/root")
.then((data) => data.json())
.then((jsondata) => {
console.log(jsondata);
})
.catch((error) => {
createRootCertificateModal.show();
});
};
getRootCrt();
createRootCrtButton.addEventListener("click", () => {
const newRootCertificate = {
CommonName: rootcommonnameinput.value,
Organization: [rootorganizationinput.value],
OrganizationalUnit: [rootorganizationalunitinput.value],
Country: [rootcountryinput.value],
Locality: [rootlocalityinput.value],
Province: [rootprovinceinput.value],
StreetAddress: [rootstreetaddressinput.value],
PostalCode: [rootpostalcodeinput.value],
ValidityYears: parseInt(rootvalidityyearsinput.value),
KeyPassword: rootkeypasswordinput.value,
};
fetch(window.location.origin + "/api/certs/root", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newRootCertificate),
}).then((data) =>
data
.json()
.then((jsondata) => {
console.log(jsondata);
if (jsondata.status === "ok") {
alert("Root certificate created successfully");
createRootCertificateModal.hide();
}
})
.catch((error) => {
alert(error);
}),
);
});
+10 -10
View File
@@ -1,14 +1,14 @@
package model
type CreateRootCertRequest struct {
CommonName string `json:"CommonName"`
Organization string `json:"Organization"`
OrganizationalUnit string `json:"OrganizationalUnit"`
Country string `json:"Country"`
Locality string `json:"Locality"`
Province string `json:"Province"`
StreetAddress string `json:"StreetAddress"`
PostalCode string `json:"PostalCode"`
ValidityYears int `json:"ValidityYears"`
KeyPassword string `json:"KeyPassword"`
CommonName string `json:"CommonName"`
Organization []string `json:"Organization"`
OrganizationalUnit []string `json:"OrganizationalUnit"`
Country []string `json:"Country"`
Locality []string `json:"Locality"`
Province []string `json:"Province"`
StreetAddress []string `json:"StreetAddress"`
PostalCode []string `json:"PostalCode"`
ValidityYears int `json:"ValidityYears"`
KeyPassword string `json:"KeyPassword"`
}
-2
View File
@@ -3,7 +3,6 @@ package server
import (
"net/http"
"scm/api"
"scm/utils"
)
func Configure() {
@@ -12,5 +11,4 @@ func Configure() {
http.HandleFunc("/api/certs/root", api.RootCert)
http.HandleFunc("/api/certs/create", api.CreateCert)
http.HandleFunc("/api/certs/delete", api.DeleteCert)
utils.CheckOrCreateRootKeyCertificate()
}
-50
View File
@@ -1,50 +0,0 @@
package utils
import (
"fmt"
"os"
)
func CheckOrCreateRootKeyCertificate() error {
_, err := os.Stat(fmt.Sprintf("%s/%s", os.Getenv("CERTS_PATH"), "root"))
if err == nil {
_, err := os.Stat(fmt.Sprintf("%s/%s", os.Getenv("CERTS_PATH"), "root/root.key"))
if err == nil {
_, err := os.Stat(fmt.Sprintf("%s/%s", os.Getenv("CERTS_PATH"), "root/root.crt"))
if err == nil {
return fmt.Errorf("%s", "key already exists")
} else if os.IsNotExist(err) {
os.RemoveAll(fmt.Sprintf("%s/%s", os.Getenv("CERTS_PATH"), "root"))
err = CreateRootKeyCertificate()
if err != nil {
fmt.Println("error creating root key certificate:", err)
return fmt.Errorf("%s", "error creating root key certificate")
}
} else {
fmt.Println("error checking certificate directory:", err)
return fmt.Errorf("%s", "error checking certificate directory")
}
} else if os.IsNotExist(err) {
os.RemoveAll(fmt.Sprintf("%s/%s", os.Getenv("CERTS_PATH"), "root"))
err = CreateRootKeyCertificate()
if err != nil {
fmt.Println("error creating root key certificate:", err)
return fmt.Errorf("%s", "error creating root key certificate")
}
} else {
fmt.Println("error checking certificate directory:", err)
return fmt.Errorf("%s", "error checking certificate directory")
}
} else if os.IsNotExist(err) {
os.RemoveAll(fmt.Sprintf("%s/%s", os.Getenv("CERTS_PATH"), "root"))
err = CreateRootKeyCertificate()
if err != nil {
fmt.Println("error creating root key certificate:", err)
return fmt.Errorf("%s", "error creating root key certificate")
}
} else {
fmt.Println("error checking certificate directory:", err)
return fmt.Errorf("%s", "error checking certificate directory")
}
return nil
}
+12 -11
View File
@@ -8,12 +8,13 @@ import (
"fmt"
"math/big"
"os"
"scm/model"
"time"
"github.com/youmark/pkcs8"
)
func CreateRootKeyCertificate() error {
func CreateRootKeyCertificate(data model.CreateRootCertRequest) error {
privkey, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
return err
@@ -27,18 +28,18 @@ func CreateRootKeyCertificate() error {
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
CommonName: "Root Certificate",
OrganizationalUnit: []string{"Organizational Unit"},
Organization: []string{"Organization"},
Country: []string{"Country"},
Locality: []string{"Locality"},
Province: []string{"Province"},
StreetAddress: []string{"Street Address"},
PostalCode: []string{"Postal Code"},
CommonName: data.CommonName,
OrganizationalUnit: data.OrganizationalUnit,
Organization: data.Organization,
Country: data.Country,
Locality: data.Locality,
Province: data.Province,
StreetAddress: data.StreetAddress,
PostalCode: data.PostalCode,
SerialNumber: serialNumber.String(),
},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(10, 0, 0),
NotAfter: time.Now().AddDate(data.ValidityYears, 0, 0),
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{
x509.ExtKeyUsageServerAuth,
@@ -55,7 +56,7 @@ func CreateRootKeyCertificate() error {
encryptedKey, err := pkcs8.ConvertPrivateKeyToPKCS8(
privkey,
[]byte("Simba28082020"),
[]byte(data.KeyPassword),
)
if err != nil {
return err
-1
View File
@@ -39,7 +39,6 @@ func LoadRootCertAndKey(certFile, keyFile, password string) (*x509.Certificate,
if block == nil {
return nil, nil, errors.New("failed to parse CA key PEM")
}
fmt.Print(block.Type)
// Декодирование ключа с паролем
decryptedKey, err := pkcs8.ParsePKCS8PrivateKey(block.Bytes, []byte(password))
if err != nil {