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

This commit is contained in:
wt committed 2025-07-21 22:11:04 +07:00
1 parent 39c27b0de3
commit e6526fb780
8 files changed
+169 -114

No files matched your search

+6 -4
View File
@@ -6,6 +6,7 @@ import (
"net/http" "net/http"
"os" "os"
"scm/model" "scm/model"
"scm/utils"
) )
func RootCert(w http.ResponseWriter, r *http.Request) { 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) http.Error(w, err.Error(), http.StatusInternalServerError)
return return
} }
fmt.Fprintf(w, `{"status":"ok"}`) fmt.Fprintf(w, `{"status":"ok"}`)
case "POST": case "POST":
var rootCertRequest model.CreateRootCertRequest var rootCertRequest model.CreateRootCertRequest
@@ -25,9 +25,11 @@ func RootCert(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusBadRequest) http.Error(w, err.Error(), http.StatusBadRequest)
return return
} }
err = utils.CreateRootKeyCertificate(rootCertRequest)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, `{"status":"ok"}`) fmt.Fprintf(w, `{"status":"ok"}`)
default: default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) 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/theme.js" defer></script>
<script src="js/certs.js" defer></script> <script src="js/certs.js" defer></script>
<script src="js/create_cert.js" defer></script> <script src="js/create_cert.js" defer></script>
<script src="js/rootcrt.js" defer></script>
<title>Scm</title> <title>Scm</title>
</head> </head>
<style> <style>
@@ -305,81 +306,120 @@
</div> </div>
</div> </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-dialog">
<div class="modal-content"> <div class="modal-content">
<div class="modal-header"> <div class="modal-header">
<h5 class="modal-title">Create SSl Certificate</h5> <h5 class="modal-title">
<button Create rootCA SSl Certificate
type="button" </h5>
data-bs-dismiss="modal"
aria-label="Close"
class="btn-close"
></button>
</div> </div>
<div class="modal-body"> <div class="modal-body">
<div class="form-floating mb-3"> <div class="form-floating mb-3">
<input <input
type="text" type="text"
id="domain" id="rootcommonname"
class="form-control" class="form-control"
placeholder="example.domain" placeholder="example.domain"
/> />
<label for="domain">Domain</label> <label for="rootcommonname">Common Name</label>
</div> </div>
<div class="form-floating mb-3"> <div class="form-floating mb-3">
<input <input
type="text" type="text"
id="commonname" id="rootorganizationname"
class="form-control"
placeholder="commonname"
/>
<label for="commonname">Common Name</label>
</div>
<div class="form-floating mb-3">
<input
type="text"
id="organizationname"
class="form-control" class="form-control"
placeholder="organizationname" placeholder="organizationname"
/> />
<label for="organizationname" <label for="rootorganizationname"
>Organization Name</label >Organization Name</label
> >
</div> </div>
<div class="form-floating mb-3"> <div class="form-floating mb-3">
<input <input
type="text" type="text"
id="organizationunit" id="rootorganizationalunit"
class="form-control" class="form-control"
placeholder="organizationunit" placeholder="organizationalunit"
/> />
<label for="organizationunit" <label for="rootorganizationalunit"
>Organization Unit</label >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>
<div class="form-floating mb-3"> <div class="form-floating mb-3">
<input <input
type="password" type="password"
id="password" id="rootkeypassword"
class="form-control" class="form-control"
placeholder="example.domain" placeholder="Password"
/> />
<label for="password">RootCA password</label> <label for="rootkeypassword">Password</label>
</div> </div>
</div> </div>
<div class="modal-footer"> <div class="modal-footer">
<button <button
type="button" id="createRootCrt"
data-bs-dismiss="modal"
class="btn btn-secondary"
>
Close
</button>
<button
id="createcert"
type="button" type="button"
class="btn btn-primary" class="btn btn-primary"
style="width: 100%"
> >
Create Create
</button> </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 package model
type CreateRootCertRequest struct { type CreateRootCertRequest struct {
CommonName string `json:"CommonName"` CommonName string `json:"CommonName"`
Organization string `json:"Organization"` Organization []string `json:"Organization"`
OrganizationalUnit string `json:"OrganizationalUnit"` OrganizationalUnit []string `json:"OrganizationalUnit"`
Country string `json:"Country"` Country []string `json:"Country"`
Locality string `json:"Locality"` Locality []string `json:"Locality"`
Province string `json:"Province"` Province []string `json:"Province"`
StreetAddress string `json:"StreetAddress"` StreetAddress []string `json:"StreetAddress"`
PostalCode string `json:"PostalCode"` PostalCode []string `json:"PostalCode"`
ValidityYears int `json:"ValidityYears"` ValidityYears int `json:"ValidityYears"`
KeyPassword string `json:"KeyPassword"` KeyPassword string `json:"KeyPassword"`
} }
-2
View File
@@ -3,7 +3,6 @@ package server
import ( import (
"net/http" "net/http"
"scm/api" "scm/api"
"scm/utils"
) )
func Configure() { func Configure() {
@@ -12,5 +11,4 @@ func Configure() {
http.HandleFunc("/api/certs/root", api.RootCert) http.HandleFunc("/api/certs/root", api.RootCert)
http.HandleFunc("/api/certs/create", api.CreateCert) http.HandleFunc("/api/certs/create", api.CreateCert)
http.HandleFunc("/api/certs/delete", api.DeleteCert) 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" "fmt"
"math/big" "math/big"
"os" "os"
"scm/model"
"time" "time"
"github.com/youmark/pkcs8" "github.com/youmark/pkcs8"
) )
func CreateRootKeyCertificate() error { func CreateRootKeyCertificate(data model.CreateRootCertRequest) error {
privkey, err := rsa.GenerateKey(rand.Reader, 4096) privkey, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil { if err != nil {
return err return err
@@ -27,18 +28,18 @@ func CreateRootKeyCertificate() error {
template := x509.Certificate{ template := x509.Certificate{
SerialNumber: serialNumber, SerialNumber: serialNumber,
Subject: pkix.Name{ Subject: pkix.Name{
CommonName: "Root Certificate", CommonName: data.CommonName,
OrganizationalUnit: []string{"Organizational Unit"}, OrganizationalUnit: data.OrganizationalUnit,
Organization: []string{"Organization"}, Organization: data.Organization,
Country: []string{"Country"}, Country: data.Country,
Locality: []string{"Locality"}, Locality: data.Locality,
Province: []string{"Province"}, Province: data.Province,
StreetAddress: []string{"Street Address"}, StreetAddress: data.StreetAddress,
PostalCode: []string{"Postal Code"}, PostalCode: data.PostalCode,
SerialNumber: serialNumber.String(), SerialNumber: serialNumber.String(),
}, },
NotBefore: time.Now(), 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, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{ ExtKeyUsage: []x509.ExtKeyUsage{
x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageServerAuth,
@@ -55,7 +56,7 @@ func CreateRootKeyCertificate() error {
encryptedKey, err := pkcs8.ConvertPrivateKeyToPKCS8( encryptedKey, err := pkcs8.ConvertPrivateKeyToPKCS8(
privkey, privkey,
[]byte("Simba28082020"), []byte(data.KeyPassword),
) )
if err != nil { if err != nil {
return err return err
-1
View File
@@ -39,7 +39,6 @@ func LoadRootCertAndKey(certFile, keyFile, password string) (*x509.Certificate,
if block == nil { if block == nil {
return nil, nil, errors.New("failed to parse CA key PEM") return nil, nil, errors.New("failed to parse CA key PEM")
} }
fmt.Print(block.Type)
// Декодирование ключа с паролем // Декодирование ключа с паролем
decryptedKey, err := pkcs8.ParsePKCS8PrivateKey(block.Bytes, []byte(password)) decryptedKey, err := pkcs8.ParsePKCS8PrivateKey(block.Bytes, []byte(password))
if err != nil { if err != nil {