Skip to content

Commit

Permalink
Saving pfx/cer/csr in folder
Browse files Browse the repository at this point in the history
  • Loading branch information
Demetrous-fd committed Oct 17, 2024
1 parent b945a68 commit 168cb45
Show file tree
Hide file tree
Showing 8 changed files with 123 additions and 19 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ t/
bin/
README.pdf
csr.json
logger.log
logger.log
test_certs/
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,14 @@ Flags:
Включить отладочную информацию
-file string
JSON файл с csr запросами (default "csr.json")
-flat
Не сохранять контейнер/сертификат/csr запрос в отдельной папке
-folder string
Директория сохранения контейнеров/сертификатов/csr запросов (default "test_certs")
-skip-root
Пропустить установку корневого сертификата тестового УЦ
-version
Отобразить версию программы
```

### Поддержка проекта
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ go 1.20
require golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56

require (
github.com/Demetrous-fd/CryptoPro-Adapter v0.0.0-20241009063443-a965bb04c1af // indirect
github.com/Demetrous-fd/CryptoPro-Adapter v0.0.0-20241016081432-3a5ddc206b41 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/otiai10/copy v1.14.0 // indirect
golang.org/x/sync v0.7.0 // indirect
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
github.com/Demetrous-fd/CryptoPro-Adapter v0.0.0-20241009063443-a965bb04c1af h1:gl4IIMPGJWovLcgfDY9Q5pNbLX3T3qgUpd4yaVZwzXo=
github.com/Demetrous-fd/CryptoPro-Adapter v0.0.0-20241009063443-a965bb04c1af/go.mod h1:u3GJFQjJZ7lfZv/guG3cnAISW6Ua9B7dOhBYCErEXXA=
github.com/Demetrous-fd/CryptoPro-Adapter v0.0.0-20241015080818-62cd7126ae4a h1:B+tzqXgkuZjR5VeJmP6FXy28p2kiSlwPUj9qvk2/tS8=
github.com/Demetrous-fd/CryptoPro-Adapter v0.0.0-20241015080818-62cd7126ae4a/go.mod h1:u3GJFQjJZ7lfZv/guG3cnAISW6Ua9B7dOhBYCErEXXA=
github.com/Demetrous-fd/CryptoPro-Adapter v0.0.0-20241016081432-3a5ddc206b41 h1:6U2KVQupgIJOjqFrbHXJcyVI7GZsi8Qf0cr5ywUY9VY=
github.com/Demetrous-fd/CryptoPro-Adapter v0.0.0-20241016081432-3a5ddc206b41/go.mod h1:u3GJFQjJZ7lfZv/guG3cnAISW6Ua9B7dOhBYCErEXXA=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/otiai10/copy v1.14.0 h1:dCI/t1iTdYGtkvCuBG2BgR6KZa83PTclw4U5n2wAllU=
Expand Down
6 changes: 3 additions & 3 deletions src/csr.go
Original file line number Diff line number Diff line change
Expand Up @@ -360,9 +360,6 @@ func requestCertificate(csr string) string {
}

certData := string(cert)

certData = strings.ReplaceAll(certData, "-----BEGIN CERTIFICATE-----\r\n", "")
certData = strings.ReplaceAll(certData, "-----END CERTIFICATE-----\r\n", "")
return certData
}

Expand All @@ -377,6 +374,9 @@ func installCertificate(x509 *cades.X509EnrollmentRoot, certificateData string)
return err
}

certificateData = strings.ReplaceAll(certificateData, "-----BEGIN CERTIFICATE-----\r\n", "")
certificateData = strings.ReplaceAll(certificateData, "-----END CERTIFICATE-----\r\n", "")

err = enrollCert.InstallResponse(ALLOW_UNTRUSTED_ROOT, certificateData, XCN_CRYPT_STRING_BASE64, "")
if err != nil {
return err
Expand Down
77 changes: 71 additions & 6 deletions src/installer.go
Original file line number Diff line number Diff line change
@@ -1,32 +1,97 @@
package main

import (
"errors"
"fmt"
"os"
"path/filepath"

cades "github.com/Demetrous-fd/CryptoPro-Adapter"
"golang.org/x/exp/slog"
)

func ExecuteCsrInstall(x509 *cades.X509EnrollmentRoot, csr *CsrParams) {
type ContainerInfo struct {
Name string `json:"name"`
Thumbprint string `json:"thumbprint"`
ContainerName string `json:"containerName"`
ContainerPin string `json:"containerPin,omitempty"`
}

func ExecuteCsrInstall(x509 *cades.X509EnrollmentRoot, csr *CsrParams) *ContainerInfo {
result := &ContainerInfo{}
csrData, err := generateCsr(x509, csr)
if err != nil {
slog.Error(fmt.Sprintf("Cant generate csr request, container[%s], error: %s", csr.Container.Name, err.Error()))
return
return result
}

certificate := requestCertificate(csrData)
outputFolder := *outputFolderFlag
if !*flatFlag {
outputFolder = filepath.Join(outputFolder, csr.Container.Name)

if _, err := os.Stat(outputFolder); errors.Is(err, os.ErrNotExist) {
os.Mkdir(outputFolder, os.ModePerm)
}
}

csrFilename := fmt.Sprintf("%s.csr", csr.Container.Name)
csrFilePath := filepath.Join(outputFolder, csrFilename)
csrFile, err := os.Create(csrFilePath)
if err != nil {
slog.Error(fmt.Sprintf("Cant create file: %s, error: %s", csrFilePath, err.Error()))
}
csrFile.WriteString(csrData)

certificate := requestCertificate(csrData)
if certificate == "" {
slog.Error(fmt.Sprintf("Cant request certificate, container[%s]", csr.Container.Name))
return
return result
}

certFilename := fmt.Sprintf("%s.cer", csr.Container.Name)
certFilePath := filepath.Join(outputFolder, certFilename)
certFile, err := os.Create(certFilePath)
if err != nil {
slog.Error(fmt.Sprintf("Cant create file: %s, error: %s", certFilePath, err.Error()))
}
certFile.WriteString(certificate)

err = installCertificate(x509, certificate)
if err != nil {
slog.Error(fmt.Sprintf("Cant install certificate, container[%s], error: %s", csr.Container.Name, err.Error()))
return
return result
}

cm := cades.CadesManager{}
container, err := cm.GetContainer(csr.Container.Name)
if err != nil {
slog.Error(fmt.Sprintf("Cant get container with name: %s, error: %s", csr.Container.Name, err.Error()))
}

if csr.Container.Exportable {
pfxFilename := fmt.Sprintf("%s.pfx", csr.Container.Name)
pfxFilePath := filepath.Join(outputFolder, pfxFilename)
pfxFilePath, _ = filepath.Abs(pfxFilePath)

if (container != &cades.Container{}) {
_, err = cm.ExportContainerToPfx(pfxFilePath, container.UniqueContainerName, csr.Container.Pin)
if err != nil {
slog.Error(fmt.Sprintf("Cant create file: %s, error: %s", pfxFilePath, err.Error()))
}
}
}

slog.Info(fmt.Sprintf("Container[%s] and certificate installed", csr.Container.Name))

result.Name = csr.Container.Name
certThumbprint, err := getThumbprintFromBS64Certificate(certificate)
if err != nil {
slog.Error(err.Error())
}
result.Thumbprint = certThumbprint
result.ContainerName = container.ContainerName
result.ContainerPin = csr.Container.Pin
return result
}

func InstallRoot(cadesObj *cades.Cades) {
Expand All @@ -36,7 +101,7 @@ func InstallRoot(cadesObj *cades.Cades) {
return
}

thumbprint, err := getRootCertificateThumbprint(rootCertificate)
thumbprint, err := getThumbprintFromBS64Certificate(rootCertificate)

if err == nil {
cm := cades.CadesManager{}
Expand Down
42 changes: 35 additions & 7 deletions src/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,29 @@ import (
"fmt"
"io"
"os"
"path/filepath"

cades "github.com/Demetrous-fd/CryptoPro-Adapter"
"golang.org/x/exp/slog"
)

var (
debugFlag *bool
skipRootFlag *bool
versionFlag *bool
csrFileFlag *string
debugFlag *bool
flatFlag *bool
skipRootFlag *bool
versionFlag *bool
csrFileFlag *string
outputFolderFlag *string
)

func init() {
debugFlag = flag.Bool("debug", false, "Включить отладочную информацию")
versionFlag = flag.Bool("version", false, "Отобразить версию программы")
skipRootFlag = flag.Bool("skip-root", false, "Пропустить установку корневого сертификата тестового УЦ")
flatFlag = flag.Bool("flat", false, "Не сохранять контейнер/сертификат/csr запрос в отдельной папке")

csrFileFlag = flag.String("file", "csr.json", "JSON файл с csr запросами")
versionFlag = flag.Bool("version", false, "Отобразить версию программы")
outputFolderFlag = flag.String("folder", "test_certs", "Директория сохранения контейнеров/сертификатов/csr запросов")
}

type CSRsBlock struct {
Expand All @@ -35,7 +41,7 @@ func main() {
flag.Parse()

if *versionFlag {
fmt.Println("Masscsr version 0.0.0")
fmt.Println("Masscsr version 0.1.0")
fmt.Println("Repository: https://github.com/Demetrous-fd/CryptoPro-Mass-CSR")
fmt.Println("Maintainer: Lazydeus (Demetrous-fd)")
return
Expand All @@ -62,6 +68,10 @@ func main() {
logger := slog.New(handler)
slog.SetDefault(logger)

if _, err := os.Stat(*outputFolderFlag); errors.Is(err, os.ErrNotExist) {
os.Mkdir(*outputFolderFlag, os.ModePerm)
}

if _, err := os.Stat(*csrFileFlag); errors.Is(err, os.ErrNotExist) {
slog.Error(fmt.Sprintf("File: '%s' not exists", *csrFileFlag))
return
Expand Down Expand Up @@ -100,7 +110,25 @@ func main() {

x509 := cades.CreateX509EnrollmentRoot(cadesLocal)

var containersInfo []ContainerInfo
for _, csr := range csrsBlock.Requests {
ExecuteCsrInstall(x509, &csr)
info := ExecuteCsrInstall(x509, &csr)

if (info != &ContainerInfo{}) {
containersInfo = append(containersInfo, *info)
}
}

infoData, err := json.MarshalIndent(containersInfo, "", "\t")
if err == nil {
infoPath := filepath.Join(*outputFolderFlag, "info.json")
infoFile, err := os.Create(infoPath)
if err != nil {
slog.Error(err.Error())
return
}
defer infoFile.Close()

infoFile.Write(infoData)
}
}
2 changes: 1 addition & 1 deletion src/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func requestRootCertificate() string {
return certData
}

func getRootCertificateThumbprint(data string) (string, error) {
func getThumbprintFromBS64Certificate(data string) (string, error) {
rootCertificateDer := strings.ReplaceAll(data, "-----BEGIN CERTIFICATE-----\r\n", "")
rootCertificateDer = strings.ReplaceAll(rootCertificateDer, "-----END CERTIFICATE-----\r\n", "")

Expand Down

0 comments on commit 168cb45

Please sign in to comment.