Skip to content

Commit

Permalink
Merge pull request #451 from dev4unet/master
Browse files Browse the repository at this point in the history
GCP 키페어 생성 오픈소스 라이센스 이슈 처리 반영
  • Loading branch information
powerkimhub authored Aug 10, 2021
2 parents 03008b5 + af33488 commit 9d17a61
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 183 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,8 @@ func handleSecurity() {
//config := readConfigFile()
//VmID := config.Aws.VmID

securityName := "cb-securitytest-all"
securityId := "cb-securitytest-all"
securityName := "cb-securitytest1"
securityId := "cb-securitytest1"
//securityId := "cb-secu-all"
//vpcId := "cb-vpc"
vpcId := "cb-vpc-load-test"
Expand Down Expand Up @@ -172,20 +172,30 @@ func handleSecurity() {
VpcIID: irs.IID{SystemId: vpcId},
SecurityRules: &[]irs.SecurityRuleInfo{ //보안 정책 설정
//CIDR 테스트
{
FromPort: "30",
ToPort: "",
IPProtocol: "tcp",
Direction: "inbound",
CIDR: "10.13.1.10/32",
},
//{
// FromPort: "30",
// ToPort: "",
// IPProtocol: "tcp",
// Direction: "inbound",
// CIDR: "10.13.1.10/32",
//},
// {
// FromPort: "40",
// ToPort: "",
// IPProtocol: "tcp",
// Direction: "outbound",
// CIDR: "10.13.1.10/32,10.13.1.11/32",
// },

{
//20-22 Prot로 등록
FromPort: "20",
ToPort: "22",
IPProtocol: "tcp",
Direction: "inbound",
CIDR: "0.0.0.0/0",
},

/*
{
// All Port로 등록
Expand Down Expand Up @@ -868,9 +878,9 @@ func handleVM() {
},
//VpcIID: irs.IID{SystemId: "cb-vpc"},
//SubnetIID: irs.IID{SystemId: "cb-sub1"},
VpcIID: irs.IID{SystemId: "cb-vpc-load-test"},
SubnetIID: irs.IID{SystemId: "vpc-loadtest-sub1 "},
SecurityGroupIIDs: []irs.IID{{SystemId: "cb-securitytest1"}},
VpcIID: irs.IID{SystemId: "cb-vpc-load-test"},
SubnetIID: irs.IID{SystemId: "vpc-loadtest-sub1"},
SecurityGroupIIDs: []irs.IID{{SystemId: "securitytest1"}},
VMSpecName: "f1-micro",
KeyPairIID: irs.IID{SystemId: "cb-keypairtest123123"},
VMUserId: "cb-user",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,15 @@
package resources

import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"strings"

call "github.com/cloud-barista/cb-spider/cloud-control-manager/cloud-driver/call-log"
keypair "github.com/cloud-barista/cb-spider/cloud-control-manager/cloud-driver/common"
idrv "github.com/cloud-barista/cb-spider/cloud-control-manager/cloud-driver/interfaces"
irs "github.com/cloud-barista/cb-spider/cloud-control-manager/cloud-driver/interfaces/resources"
"golang.org/x/crypto/ssh"
)

type GCPKeyPairHandler struct {
Expand Down Expand Up @@ -59,32 +53,14 @@ func (keyPairHandler *GCPKeyPairHandler) CreateKey(keyPairReqInfo irs.KeyPairReq
}
}

// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.GCP,
RegionZone: keyPairHandler.Region.Zone,
ResourceType: call.VMKEYPAIR,
ResourceName: keyPairReqInfo.IId.NameId,
CloudOSAPI: "CreateHashString()",
ElapsedTime: "",
ErrorMSG: "",
}
callLogStart := call.Start()

hashString, err := CreateHashString(keyPairHandler.CredentialInfo)
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
if err != nil {
callLogInfo.ErrorMSG = err.Error()
callogger.Info(call.String(callLogInfo))
cblogger.Error(err)
return irs.KeyPairInfo{}, err
}
callogger.Info(call.String(callLogInfo))

savePrivateFileTo := keyPairPath + hashString + "--" + keyPairName
savePublicFileTo := keyPairPath + hashString + "--" + keyPairName + ".pub"
bitSize := 4096

// Check KeyPair Exists
if _, err := os.Stat(savePrivateFileTo); err == nil {
Expand All @@ -94,19 +70,7 @@ func (keyPairHandler *GCPKeyPairHandler) CreateKey(keyPairReqInfo irs.KeyPairReq
return irs.KeyPairInfo{}, createErr
}

// 지정된 바이트크기의 RSA 형식 개인키(비공개키)를 만듬
privateKey, err := generatePrivateKey(bitSize)
if err != nil {
cblogger.Error(err)
return irs.KeyPairInfo{}, err
}

// 개인키를 RSA에서 PEM 형식으로 인코딩
privateKeyBytes := encodePrivateKeyToPEM(privateKey)

// rsa.PublicKey를 가져와서 .pub 파일에 쓰기 적합한 바이트로 변환
// "ssh-rsa ..."형식으로 변환
publicKeyBytes, err := generatePublicKey(&privateKey.PublicKey)
privateKeyBytes, publicKeyBytes, err := keypair.GenKeyPair()
publicKeyString := string(publicKeyBytes)
// projectId 대신에 cb-user 고정
publicKeyString = strings.TrimSpace(publicKeyString) + " " + "cb-user"
Expand All @@ -117,14 +81,14 @@ func (keyPairHandler *GCPKeyPairHandler) CreateKey(keyPairReqInfo irs.KeyPairReq
}

// 파일에 private Key를 쓴다
err = writeKeyToFile(privateKeyBytes, savePrivateFileTo)
err = keypair.SaveKey(privateKeyBytes, savePrivateFileTo)
if err != nil {
cblogger.Error(err)
return irs.KeyPairInfo{}, err
}

// 파일에 public Key를 쓴다
err = writeKeyToFile([]byte(publicKeyString), savePublicFileTo)
err = keypair.SaveKey([]byte(publicKeyString), savePublicFileTo)
if err != nil {
cblogger.Error(err)
return irs.KeyPairInfo{}, err
Expand Down Expand Up @@ -156,32 +120,15 @@ func (keyPairHandler *GCPKeyPairHandler) ListKey() ([]*irs.KeyPairInfo, error) {

var keyPairInfoList []*irs.KeyPairInfo

// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.GCP,
RegionZone: keyPairHandler.Region.Zone,
ResourceType: call.VMKEYPAIR,
ResourceName: "List",
CloudOSAPI: "ioutil.ReadDir()",
ElapsedTime: "",
ErrorMSG: "",
}
callLogStart := call.Start()

files, err := ioutil.ReadDir(keyPairPath)
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
if err != nil {
callLogInfo.ErrorMSG = err.Error()
callogger.Info(call.String(callLogInfo))
//cblogger.Error("Fail ReadDir(keyPairPath)")
//cblogger.Error(err)
//return nil, err

//키페어 폴더가 없는 경우 생성된 키가 없는 것으로 변경
return nil, nil
}
callogger.Info(call.String(callLogInfo))

for _, f := range files {
if strings.Contains(f.Name(), ".pub") {
Expand Down Expand Up @@ -222,29 +169,11 @@ func (keyPairHandler *GCPKeyPairHandler) GetKey(keyIID irs.IID) (irs.KeyPairInfo
privateKeyPath := keyPairPath + hashString + "--" + keyPairName
publicKeyPath := keyPairPath + hashString + "--" + keyPairName + ".pub"

// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.GCP,
RegionZone: keyPairHandler.Region.Zone,
ResourceType: call.VMKEYPAIR,
ResourceName: keyIID.SystemId,
CloudOSAPI: "os.Stat()",
ElapsedTime: "",
ErrorMSG: "",
}
callLogStart := call.Start()

//키 페어 존재 여부 체크
if _, err := os.Stat(privateKeyPath); err != nil {
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
callLogInfo.ErrorMSG = err.Error()
callogger.Info(call.String(callLogInfo))
cblogger.Error(err)
return irs.KeyPairInfo{}, errors.New("Not Found : [" + keyIID.SystemId + "] KeyPair Not Found.")
}
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
callogger.Info(call.String(callLogInfo))

// Private Key, Public Key 파일 정보 가져오기
privateKeyBytes, err := ioutil.ReadFile(privateKeyPath)
Expand Down Expand Up @@ -295,29 +224,12 @@ func (keyPairHandler *GCPKeyPairHandler) DeleteKey(keyIID irs.IID) (bool, error)
return false, errors.New("Not Found : [" + keyIID.SystemId + "] KeyPair Not Found.")
}

// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.GCP,
RegionZone: keyPairHandler.Region.Zone,
ResourceType: call.VMKEYPAIR,
ResourceName: keyPairName,
CloudOSAPI: "Remove()",
ElapsedTime: "",
ErrorMSG: "",
}
callLogStart := call.Start()

// Private Key, Public Key 삭제
err = os.Remove(privateKeyPath)
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
if err != nil {
callLogInfo.ErrorMSG = err.Error()
callogger.Info(call.String(callLogInfo))
cblogger.Error(err)
return false, err
}
callogger.Info(call.String(callLogInfo))
err = os.Remove(publicKeyPath)
if err != nil {
cblogger.Error(err)
Expand All @@ -326,82 +238,3 @@ func (keyPairHandler *GCPKeyPairHandler) DeleteKey(keyIID irs.IID) (bool, error)

return true, nil
}

// 지정된 바이트크기의 RSA 형식 개인키(비공개키)를 만듬
func generatePrivateKey(bitSize int) (*rsa.PrivateKey, error) {
// Private Key 생성
privateKey, err := rsa.GenerateKey(rand.Reader, bitSize)
if err != nil {
cblogger.Error(err)
return nil, err
}

// Private Key 확인
err = privateKey.Validate()
if err != nil {
cblogger.Error(err)
return nil, err
}

log.Println("Private Key generated(생성)")
//fmt.Println(privateKey)
return privateKey, nil
}

// 개인키를 RSA에서 PEM 형식으로 인코딩
func encodePrivateKeyToPEM(privateKey *rsa.PrivateKey) []byte {
// Get ASN.1 DER format
privDER := x509.MarshalPKCS1PrivateKey(privateKey)

// pem.Block
privBlock := pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: privDER,
}

// Private key in PEM format
privatePEM := pem.EncodeToMemory(&privBlock)
fmt.Println("privateKey Rsa -> Pem 형식으로 변환")
//fmt.Println(privatePEM)
return privatePEM
}

// rsa.PublicKey를 가져와서 .pub 파일에 쓰기 적합한 바이트로 변환
// "ssh-rsa ..."형식으로 변환
func generatePublicKey(privatekey *rsa.PublicKey) ([]byte, error) {
publicRsaKey, err := ssh.NewPublicKey(privatekey)
if err != nil {
cblogger.Error(err)
return nil, err
}

pubKeyBytes := ssh.MarshalAuthorizedKey(publicRsaKey)

log.Println("Public key 생성")
//fmt.Println(pubKeyBytes)
return pubKeyBytes, nil
}

// 파일에 Key를 쓴다
func writeKeyToFile(keyBytes []byte, saveFileTo string) error {
err := ioutil.WriteFile(saveFileTo, keyBytes, 0600)
if err != nil {
cblogger.Error(err)
return err
}

log.Printf("Key 저장위치: %s", saveFileTo)
return nil
}

// Credential 기반 hash 생성
/*func createHashString(credentialInfo idrv.CredentialInfo) (string, error) {
keyString := credentialInfo.ClientId + credentialInfo.ClientSecret + credentialInfo.TenantId + credentialInfo.SubscriptionId
hasher := md5.New()
_, err := io.WriteString(hasher, keyString)
if err != nil {
return "", err
}
return fmt.Sprintf("%x", hasher.Sum(nil)), nil
}*/

0 comments on commit 9d17a61

Please sign in to comment.