place go files in project dirs and updates to checkCertificate

merge-requests/1/merge
Matthew 2019-12-27 13:59:58 -05:00
parent a1176bfa36
commit 6a9d31f1a9
No known key found for this signature in database
GPG Key ID: 766BE43AE75F7559
3 changed files with 230 additions and 0 deletions

View File

@ -0,0 +1,105 @@
// ignore this error
package main
import (
"crypto/sha1"
"crypto/x509"
"encoding/hex"
"encoding/json"
"encoding/pem"
"encoding/xml"
"fmt"
"io/ioutil"
"os"
)
// HandleError handles an error by panicing.
func HandleError(e error) {
if e != nil {
panic(e)
}
}
func main() {
type CertificateAbstract struct {
EmailAddress string
SignatureAlgorithm string
PublicKeyAlgorithm string
ExtendedKeyUsage []string
PolicyIdentifiers []string
SerialNumber string
FingerPrint string
}
type CompleteCertificate struct {
XMLName xml.Name `xml:"CertificateParse"`
RawParse *x509.Certificate
AbstractParse CertificateAbstract
}
certificateFile, err := ioutil.ReadFile(os.Args[1])
HandleError(err)
certificatePemDecode, _ := pem.Decode(certificateFile)
if certificatePemDecode == nil {
panic("Certificate PEM Encode == nil")
}
certificateParse, err := x509.ParseCertificate(certificatePemDecode.Bytes)
HandleError(err)
policyIdentifiers := []string{}
extendedKeyUsages := []string{}
var emailAddress interface{}
for _, value := range certificateParse.Subject.Names {
if value.Type.String() == "1.2.840.113549.1.9.1" {
emailAddress = value.Value
}
}
for _, value := range certificateParse.PolicyIdentifiers {
policyIdentifiers = append(policyIdentifiers, value.String())
}
for _, value := range certificateParse.ExtKeyUsage {
switch value {
case 0:
extendedKeyUsages = append(extendedKeyUsages, "All/Any Usages")
break
case 1:
extendedKeyUsages = append(extendedKeyUsages, "TLS Web Server Authentication")
break
case 2:
extendedKeyUsages = append(extendedKeyUsages, "TLS Web Client Authentication")
break
case 3:
extendedKeyUsages = append(extendedKeyUsages, "Code Signing")
break
case 4:
extendedKeyUsages = append(extendedKeyUsages, "E-mail Protection (S/MIME)")
default:
break
}
}
sum := sha1.Sum(certificateParse.Raw)
certificateStruct := CompleteCertificate{
RawParse: certificateParse,
AbstractParse: CertificateAbstract{
EmailAddress: fmt.Sprintf("%s", emailAddress),
SignatureAlgorithm: certificateParse.SignatureAlgorithm.String(),
PublicKeyAlgorithm: certificateParse.PublicKeyAlgorithm.String(),
PolicyIdentifiers: policyIdentifiers,
ExtendedKeyUsage: extendedKeyUsages,
SerialNumber: certificateParse.SerialNumber.String(),
FingerPrint: hex.EncodeToString(sum[:]),
},
}
if len(os.Args) >= 3 {
if os.Args[2] == "json" {
data, err := json.MarshalIndent(certificateStruct, "", " ")
HandleError(err)
fmt.Printf("%v\n", string(data))
} else if os.Args[2] == "xml" {
data, err := xml.MarshalIndent(certificateStruct, "", " ")
HandleError(err)
fmt.Printf("%v\n", string(data))
}
} else {
data, err := json.MarshalIndent(certificateStruct, "", " ")
HandleError(err)
fmt.Printf("%v\n", string(data))
}
}

26
src/go/storage/dirsize.go Normal file
View File

@ -0,0 +1,26 @@
package main
import (
"os"
"path/filepath"
)
// DirSize This function returns the total size of a directory in bytes.
func DirSize(path* string) float64 {
var dirSize int64 = 0
readSize := func(path string, file os.FileInfo, err error) error {
if !file.IsDir() {
dirSize += file.Size()
}
return nil
}
err := filepath.Walk(*path, readSize)
HandleError(err, 0)
size := float64(dirSize)
return size
}

99
src/go/storage/storage.go Normal file
View File

@ -0,0 +1,99 @@
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/go-redis/redis/v7"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"io/ioutil"
"time"
"strings"
)
// Collection the MongoDB Account collection
var Collection *mongo.Collection
// RedisClient the Redis client
var RedisClient *redis.Client
// Account represents an user's account.
type Account struct {
Username string `json:"username"`
UserID string `json:"userID"`
EmailAddress string `json:"emailAddress"`
CreatedBy string `json:"createdBy"`
CreatedAt time.Time `json:"createdAt"`
Locked bool `json:"locked"`
}
// HandleError This function panics if an error exists.
func HandleError(e error, serv int) {
if e != nil && serv == 1 {
panic(e)
} else if e != nil && serv == 0 {
fmt.Println(e)
}
}
func main() {
type Config struct {
MongoDB string `json:"mongoURL"`
}
config := &Config{}
file, err := ioutil.ReadFile("../config.json")
HandleError(err, 1)
err = json.Unmarshal(file, &config)
client, err := mongo.NewClient(options.Client().ApplyURI(config.MongoDB))
HandleError(err, 1)
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
HandleError(err, 1)
err = client.Ping(context.TODO(), nil)
fmt.Printf("Connected to MongoDB [GO]\n")
HandleError(err, 1)
Collection = client.Database("cloudservices").Collection("accounts")
RedisClient = redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
_, err = RedisClient.Ping().Result()
fmt.Printf("Connected to Redis [GO]\n")
HandleError(err, 1)
for {
fmt.Printf("Calling handler func [GO]\n")
handler()
time.Sleep(1000000 * time.Millisecond)
}
}
func handler() {
cur, err := Collection.Find(context.TODO(), bson.D{})
HandleError(err, 0)
for cur.Next(context.TODO()) {
go checkAccountSizeAndUpdate(cur.Current.Lookup("username").String(), cur.Current.Lookup("id").String())
fmt.Printf("Checking account information for %s\n", cur.Current.Lookup("username").String())
time.Sleep(600000 * time.Millisecond)
}
}
func checkAccountSizeAndUpdate(username string, id string) {
var size float64 = 0
var userHomeDirectory string = strings.Replace(strings.Join([]string{"/home/", string(username)}, ""), "\"", "", -1)
fmt.Println(userHomeDirectory)
sizeHome := DirSize(&userHomeDirectory)
size += sizeHome
sizeMail := DirSize(&userHomeDirectory)
size += sizeMail
RedisClient.Set("storage"+"-"+string(id), size, 0)
fmt.Printf("Set Call | Username: %v, ID: %v | Bytes: %f\n", string(username), string(id), size)
}