Skip to content

Commit

Permalink
Code refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
andyone committed Dec 11, 2023
1 parent 2677ff7 commit 8a3514a
Show file tree
Hide file tree
Showing 6 changed files with 105 additions and 86 deletions.
93 changes: 41 additions & 52 deletions cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,8 @@ package cli
import (
"errors"
"fmt"
"io/ioutil"
"os"
"runtime"
"strconv"
"strings"
"time"

Expand All @@ -23,6 +21,7 @@ import (
"github.com/essentialkaos/ek/v12/options"
"github.com/essentialkaos/ek/v12/pager"
"github.com/essentialkaos/ek/v12/strutil"
"github.com/essentialkaos/ek/v12/timeutil"
"github.com/essentialkaos/ek/v12/usage"
"github.com/essentialkaos/ek/v12/usage/completion/bash"
"github.com/essentialkaos/ek/v12/usage/completion/fish"
Expand Down Expand Up @@ -129,7 +128,7 @@ var gradeNumMap = map[string]float64{
}

var api *sslscan.API
var maxLeftToExpiry int64
var maxLeftToExpiry time.Duration
var serverMessageShown bool

var colorTagApp, colorTagVer string
Expand All @@ -148,7 +147,6 @@ func Run(gitRev string, gomod []byte) {
}

configureUI()
prepare()

switch {
case options.Has(OPT_COMPLETION):
Expand All @@ -167,7 +165,22 @@ func Run(gitRev string, gomod []byte) {
os.Exit(0)
}

process(args)
err := prepare()

if err != nil {
printError(err.Error())
os.Exit(1)
}

err, ok := process(args)

if err != nil {
printError(err.Error())
}

if !ok {
os.Exit(1)
}
}

// configureUI configures user interface
Expand All @@ -185,28 +198,29 @@ func configureUI() {
case fmtc.Is256ColorsSupported():
colorTagApp, colorTagVer = "{*}{#99}", "{#99}"
default:
colorTagApp, colorTagVer = "{*}{b}", "{c}"
colorTagApp, colorTagVer = "{*}{b}", "{b}"
}
}

// prepare prepares utility for processing data
func prepare() {
func prepare() error {
if !options.Has(OPT_MAX_LEFT) {
return
return nil
}

var err error

maxLeftToExpiry, err = parseMaxLeft(options.GetS(OPT_MAX_LEFT))
maxLeftToExpiry, err = timeutil.ParseDuration(options.GetS(OPT_MAX_LEFT), 'd')

if err != nil {
printError(err.Error())
os.Exit(1)
return err
}

return nil
}

// process starting request processing
func process(args options.Arguments) {
func process(args options.Arguments) (error, bool) {
var ok bool
var err error
var hosts []string
Expand All @@ -215,20 +229,23 @@ func process(args options.Arguments) {

if err != nil {
if !options.GetB(OPT_FORMAT) {
printError(err.Error())
return err, false
}

os.Exit(1)
return nil, false
}

ok = true // By default everything is fine

if fsutil.CheckPerms("FR", args.Get(0).String()) {
hosts, err = readHostList(args.Get(0).String())

if err != nil && options.GetB(OPT_FORMAT) {
printError(err.Error())
os.Exit(1)
if err != nil {
if !options.GetB(OPT_FORMAT) {
return err, false
}

return nil, false
}
} else {
hosts = args.Strings()
Expand Down Expand Up @@ -268,8 +285,10 @@ func process(args options.Arguments) {
}

if !ok {
os.Exit(1)
return nil, false
}

return nil, true
}

// check check some host
Expand Down Expand Up @@ -528,25 +547,17 @@ func getStatusInProgress(endpoints []*sslscan.EndpointInfo) string {
return ""
}

// readHostList read file with hosts
// readHostList reads file with hosts
func readHostList(file string) ([]string, error) {
var result []string

fd, err := os.OpenFile(file, os.O_RDONLY, 0)

if err != nil {
return result, err
}

defer fd.Close()

listData, err := ioutil.ReadAll(fd)
listData, err := os.ReadFile(file)

if err != nil {
return result, err
return nil, err
}

list := strings.Split(string(listData[:]), "\n")
list := strings.Split(string(listData), "\n")

for _, host := range list {
if host != "" {
Expand Down Expand Up @@ -574,28 +585,6 @@ func appendEndpointsInfo(checkInfo *HostCheckInfo, endpoints []*sslscan.Endpoint
}
}

// parseMaxLeft parses max left option value
func parseMaxLeft(dur string) (int64, error) {
tm := strutil.Tail(dur, 1)
t := strings.Trim(dur, "dwmy")
ti, err := strconv.ParseInt(t, 10, 64)

if err != nil {
return -1, fmt.Errorf("Invalid value for --max-left option: %s", dur)
}

switch strings.ToLower(tm) {
case "w":
return ti * 604800, nil
case "m":
return ti * 2592000, nil
case "y":
return ti * 31536000, nil
default:
return ti * 86400, nil
}
}

// getNormGrade return grade or error
func getNormGrade(grade string) string {
switch grade {
Expand Down
23 changes: 15 additions & 8 deletions cli/details.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,12 @@ func printCertificateInfo(certs []*sslscan.Cert, endpoints []*sslscan.EndpointIn

printCategoryHeader("Server Key and Certificate")

if len(certs) == 0 {
fmtc.Println("\n {r}No valid certificates and keys{!}\n")
fmtutil.Separator(true)
return
}

cert := certs[0]

fmtc.Printf(" %-24s {s}|{!} %s\n", "Subject", extractSubject(cert.Subject))
Expand Down Expand Up @@ -1025,11 +1031,12 @@ func printEndpointHPKPInfo(details *sslscan.EndpointDetails) {
func printEndpointHandshakeInfo(details *sslscan.EndpointDetails) {
fmtc.Printf(" %-40s {s}|{!} ", "Long handshake intolerance")

if details.MiscIntolerance&2 == 2 {
switch {
case details.MiscIntolerance&2 == 2:
fmtc.Println("{y}Yes{!}")
} else if details.MiscIntolerance&4 == 4 {
case details.MiscIntolerance&4 == 4:
fmtc.Println("{y}Yes{!} {s-}(workaround success){!}")
} else {
default:
fmtc.Println("No")
}
}
Expand Down Expand Up @@ -1386,7 +1393,7 @@ func getPinsFromPolicy(policy *sslscan.HPKPPolicy) []string {

for _, pin := range strings.Split(policy.Header, ";") {
pin = strings.TrimSpace(pin)
pin = strings.Replace(pin, "\"", "", -1)
pin = strings.ReplaceAll(pin, "\"", "")
pin = strings.Replace(pin, "=", ": ", 1)

if strings.HasPrefix(pin, "pin-") {
Expand Down Expand Up @@ -1460,8 +1467,8 @@ func isWeakSuite(suite *sslscan.Suite) bool {
// extractSubject extracts subject name from certificate subject
func extractSubject(data string) string {
subject := strutil.ReadField(data, 0, false, ",")
subject = strings.Replace(subject, "CN=", "", -1)
subject = strings.Replace(subject, "OU=", "", -1)
subject = strings.ReplaceAll(subject, "CN=", "")
subject = strings.ReplaceAll(subject, "OU=", "")

return subject
}
Expand Down Expand Up @@ -1502,7 +1509,7 @@ func getTrustInfo(certID string, endpoints []*sslscan.EndpointInfo) (map[string]
}

// getExpiryMessage returns message if cert is expired in given period
func getExpiryMessage(ap *sslscan.AnalyzeProgress, dur int64) string {
func getExpiryMessage(ap *sslscan.AnalyzeProgress, dur time.Duration) string {
if dur <= 0 {
return ""
}
Expand All @@ -1516,7 +1523,7 @@ func getExpiryMessage(ap *sslscan.AnalyzeProgress, dur int64) string {
cert := info.Certs[0]
validUntilDate := time.Unix(cert.NotAfter/1000, 0)

if validUntilDate.Unix()-time.Now().Unix() > dur {
if time.Until(validUntilDate) > dur {
return ""
}

Expand Down
2 changes: 1 addition & 1 deletion cli/encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func encodeAsJSON(checksInfo []*HostCheckInfo) {
os.Exit(1)
}

fmt.Println(string(jsonData[:]))
fmt.Println(string(jsonData))
}

// encodeAsXML print check info in XML format
Expand Down
49 changes: 36 additions & 13 deletions cli/support/support.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@ import (
"fmt"
"os"
"runtime"
"runtime/debug"
"strings"

"github.com/essentialkaos/ek/v12/fmtc"
"github.com/essentialkaos/ek/v12/fmtutil"
"github.com/essentialkaos/ek/v12/fsutil"
"github.com/essentialkaos/ek/v12/hash"
"github.com/essentialkaos/ek/v12/strutil"
"github.com/essentialkaos/ek/v12/system"
"github.com/essentialkaos/ek/v12/system/container"

"github.com/essentialkaos/depsy"
)
Expand Down Expand Up @@ -55,6 +56,10 @@ func showApplicationInfo(app, ver, gitRev string) {
runtime.GOOS, runtime.GOARCH,
))

if gitRev == "" {
gitRev = extractGitRevFromBuildInfo()
}

if gitRev != "" {
if !fmtc.DisableColors && fmtc.IsTrueColorSupported() {
printInfo(7, "Git SHA", gitRev+getHashColorBullet(gitRev))
Expand Down Expand Up @@ -83,37 +88,38 @@ func showOSInfo() {
if err == nil {
fmtutil.Separator(false, "OS INFO")

printInfo(12, "Name", osInfo.Name)
printInfo(12, "Pretty Name", osInfo.PrettyName)
printInfo(12, "Version", osInfo.VersionID)
printInfo(12, "Name", osInfo.ColoredName())
printInfo(12, "Pretty Name", osInfo.ColoredPrettyName())
printInfo(12, "Version", osInfo.Version)
printInfo(12, "ID", osInfo.ID)
printInfo(12, "ID Like", osInfo.IDLike)
printInfo(12, "Version ID", osInfo.VersionID)
printInfo(12, "Version Code", osInfo.VersionCodename)
printInfo(12, "Platform ID", osInfo.PlatformID)
printInfo(12, "CPE", osInfo.CPEName)
}

systemInfo, err := system.GetSystemInfo()

if err != nil {
return
} else {
if osInfo == nil {
fmtutil.Separator(false, "SYSTEM INFO")
printInfo(12, "Name", systemInfo.OS)
}
} else if osInfo == nil {
fmtutil.Separator(false, "SYSTEM INFO")
printInfo(12, "Name", systemInfo.OS)
}

printInfo(12, "Arch", systemInfo.Arch)
printInfo(12, "Kernel", systemInfo.Kernel)

containerEngine := "No"

switch {
case fsutil.IsExist("/.dockerenv"):
switch container.GetEngine() {
case container.DOCKER:
containerEngine = "Yes (Docker)"
case fsutil.IsExist("/run/.containerenv"):
case container.PODMAN:
containerEngine = "Yes (Podman)"
case container.LXC:
containerEngine = "Yes (LXC)"
}

fmtc.NewLine()
Expand All @@ -140,6 +146,23 @@ func showDepsInfo(gomod []byte) {
}
}

// extractGitRevFromBuildInfo extracts git SHA from embedded build info
func extractGitRevFromBuildInfo() string {
info, ok := debug.ReadBuildInfo()

if !ok {
return ""
}

for _, s := range info.Settings {
if s.Key == "vcs.revision" && len(s.Value) > 7 {
return s.Value[:7]
}
}

return ""
}

// getHashColorBullet return bullet with color from hash
func getHashColorBullet(v string) string {
if len(v) > 6 {
Expand All @@ -151,7 +174,7 @@ func getHashColorBullet(v string) string {

// printInfo formats and prints info record
func printInfo(size int, name, value string) {
name = name + ":"
name += ":"
size++

if value == "" {
Expand Down
Loading

0 comments on commit 8a3514a

Please sign in to comment.