Best Gauge code snippet using main.signExecutable
sign-executable.go
Source:sign-executable.go  
...141		return errors.Wrap(err, "unzipping client")142	}143	return os.Chmod(opts.destination, 0755)144}145func signExecutable(ctx context.Context, opts signOpts) error {146	tempDir, err := ioutil.TempDir("", "evergreen")147	if err != nil {148		return errors.Wrap(err, "creating temp dir")149	}150	defer os.RemoveAll(tempDir)151	toSignPath := path.Join(tempDir, "evergreen.zip")152	if err := zipFile(opts.executablePath, toSignPath); err != nil {153		return errors.Wrapf(err, "compressing '%s'", opts.executablePath)154	}155	signedZipPath := path.Join(tempDir, "evergreen_signed.zip")156	if err = signWithNotaryClient(ctx, toSignPath, signedZipPath, opts); err != nil {157		fmt.Fprintf(os.Stderr, "code signing failed: %s", err.Error())158		return nil159	}160	signedZip, err := os.ReadFile(signedZipPath)161	if err != nil {162		return errors.Wrap(err, "reading signed zip")163	}164	return extractFileFromZip(signedZip, path.Base(opts.executablePath), opts.outputPath)165}166type signOpts struct {167	notaryClientPath string168	notaryServerURL  string169	bundleID         string170	executablePath   string171	outputPath       string172	notaryKey        string173	notarySecret     string174}175type fetchClientOpts struct {176	notaryClientDownloadURL string177	destination             string178}179func main() {180	var fetchOpts fetchClientOpts181	var signOpts signOpts182	ctx := context.Background()183	app := &cli.App{184		Commands: []cli.Command{185			{186				Name:  getClientSubcommand,187				Usage: "fetch the notary client",188				Flags: []cli.Flag{189					&cli.StringFlag{190						Name:        "destination",191						Usage:       "`PATH` to save the client",192						Destination: &fetchOpts.destination,193						Value:       path.Join(".", notaryClientFilename),194					},195					&cli.StringFlag{196						Name:        "download-url",197						Usage:       "`URL` to GET the client from",198						Destination: &fetchOpts.notaryClientDownloadURL,199						Required:    true,200					},201				},202				Action: func(c *cli.Context) error {203					return downloadClient(ctx, fetchOpts)204				},205			},206			{207				Name:  signSubcommand,208				Usage: "sign an executable",209				Flags: []cli.Flag{210					&cli.StringFlag{211						Name:        "client",212						Usage:       "`PATH` to the notary client",213						Destination: &signOpts.notaryClientPath,214						Required:    true,215					},216					&cli.StringFlag{217						Name:        "server-url",218						Usage:       "`PATH` to the notary server",219						Destination: &signOpts.notaryServerURL,220						Required:    true,221					},222					&cli.StringFlag{223						Name:        "bundle-id",224						Usage:       "`BUNDLE-ID` to sign with",225						Destination: &signOpts.bundleID,226						Required:    true,227					},228					&cli.StringFlag{229						Name:        "executable",230						Usage:       "`PATH` to the executable to sign",231						Destination: &signOpts.executablePath,232						Required:    true,233					},234					&cli.StringFlag{235						Name:        "output",236						Usage:       "`PATH` to output the signed executable. If omitted the input executable will be overwritten",237						Destination: &signOpts.outputPath,238					},239					&cli.StringFlag{240						Name:        "notary-key",241						Usage:       "`KEY` to authenticate with the notary server. If omitted the notary client will check the value of MACOS_NOTARY_KEY in the environment",242						Destination: &signOpts.notaryKey,243					},244					&cli.StringFlag{245						Name:        "notary-secret",246						Usage:       "`SECRET` to authenticate with the notary server. If omitted the notary client will check the value of MACOS_NOTARY_SECRET in the environment",247						Destination: &signOpts.notarySecret,248					},249				},250				Action: func(c *cli.Context) error {251					if signOpts.outputPath == "" {252						signOpts.outputPath = signOpts.executablePath253					}254					return signExecutable(ctx, signOpts)255				},256			},257		},258	}259	err := app.Run(os.Args)260	if err != nil {261		log.Fatal(err)262	}263}...Limelighter.go
Source:Limelighter.go  
1package main2import (3	"bytes"4	"crypto/rand"5	"crypto/rsa"6	"crypto/tls"7	"crypto/x509"8	"crypto/x509/pkix"9	"encoding/pem"10	"flag"11	"fmt"12	"io"13	"log"14	crand "math/rand"15	"os"16	"os/exec"17	"strings"18	"time"19	"github.com/fatih/color"20)21type FlagOptions struct {22	outFile   string23	inputFile string24	domain    string25	password  string26	real      string27	verify    string28}29var (30	debugging   bool31	debugWriter io.Writer32)33func printDebug(format string, v ...interface{}) {34	if debugging {35		output := fmt.Sprintf("[DEBUG] ")36		output += format37		fmt.Fprintf(debugWriter, output, v...)38	}39}40const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"41func VarNumberLength(min, max int) string {42	var r string43	crand.Seed(time.Now().UnixNano())44	num := crand.Intn(max-min) + min45	n := num46	r = RandStringBytes(n)47	return r48}49func RandStringBytes(n int) string {50	b := make([]byte, n)51	for i := range b {52		b[i] = letters[crand.Intn(len(letters))]53	}54	return string(b)55}56func GenerateCert(domain string, inputFile string) {57	var err error58	rootKey, err := rsa.GenerateKey(rand.Reader, 4096)59	if err != nil {60		panic(err)61	}62	certs, err := GetCertificatesPEM(domain + ":443")63	if err != nil {64		os.Chdir("..")65		foldername := strings.Split(inputFile, ".")66		os.RemoveAll(foldername[0])67		log.Fatal("Error: The domain: " + domain + " does not exist or is not accessible from the host you are compiling on")68	}69	block, _ := pem.Decode([]byte(certs))70	cert, _ := x509.ParseCertificate(block.Bytes)71	keyToFile(domain+".key", rootKey)72	SubjectTemplate := x509.Certificate{73		SerialNumber: cert.SerialNumber,74		Subject: pkix.Name{75			CommonName: cert.Subject.CommonName,76		},77		NotBefore:             cert.NotBefore,78		NotAfter:              cert.NotAfter,79		BasicConstraintsValid: true,80		IsCA:                  true,81		KeyUsage:              x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,82		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},83	}84	IssuerTemplate := x509.Certificate{85		SerialNumber: cert.SerialNumber,86		Subject: pkix.Name{87			CommonName: cert.Issuer.CommonName,88		},89		NotBefore: cert.NotBefore,90		NotAfter:  cert.NotAfter,91	}92	derBytes, err := x509.CreateCertificate(rand.Reader, &SubjectTemplate, &IssuerTemplate, &rootKey.PublicKey, rootKey)93	if err != nil {94		panic(err)95	}96	certToFile(domain+".pem", derBytes)97}98func keyToFile(filename string, key *rsa.PrivateKey) {99	file, err := os.Create(filename)100	if err != nil {101		panic(err)102	}103	defer file.Close()104	b, err := x509.MarshalPKCS8PrivateKey(key)105	if err != nil {106		fmt.Fprintf(os.Stderr, "Unable to marshal RSA private key: %v", err)107		os.Exit(2)108	}109	if err := pem.Encode(file, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: b}); err != nil {110		panic(err)111	}112}113func certToFile(filename string, derBytes []byte) {114	certOut, err := os.Create(filename)115	if err != nil {116		log.Fatalf("[-] Failed to Open cert.pem for Writing: %s", err)117	}118	if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {119		log.Fatalf("[-] Failed to Write Data to cert.pem: %s", err)120	}121	if err := certOut.Close(); err != nil {122		log.Fatalf("[-] Error Closing cert.pem: %s", err)123	}124}125func GetCertificatesPEM(address string) (string, error) {126	conn, err := tls.Dial("tcp", address, &tls.Config{127		InsecureSkipVerify: true,128	})129	if err != nil {130		return "", err131	}132	defer conn.Close()133	var b bytes.Buffer134	for _, cert := range conn.ConnectionState().PeerCertificates {135		err := pem.Encode(&b, &pem.Block{136			Type:  "CERTIFICATE",137			Bytes: cert.Raw,138		})139		if err != nil {140			return "", err141		}142	}143	return b.String(), nil144}145func GeneratePFK(password string, domain string) {146	cmd := exec.Command("openssl", "pkcs12", "-export", "-out", domain+".pfx", "-inkey", domain+".key", "-in", domain+".pem", "-passin", "pass:"+password+"", "-passout", "pass:"+password+"")147	err := cmd.Run()148	if err != nil {149		log.Fatalf("cmd.Run() failed with %s\n", err)150	}151}152func SignExecutable(password string, pfx string, filein string, fileout string) {153	cmd := exec.Command("osslsigncode", "sign", "-pkcs12", pfx, "-in", ""+filein+"", "-out", ""+fileout+"", "-pass", ""+password+"")154	err := cmd.Run()155	if err != nil {156		log.Fatalf("cmd.Run() failed with %s\n", err)157	}158}159func Check(check string) {160	cmd := exec.Command("osslsigncode", "verify", ""+check+"")161	cmd.Stdout = os.Stdout162	cmd.Stderr = os.Stderr163	err := cmd.Run()164	if err != nil {165		log.Fatalf("cmd.Run() failed with %s\n", err)166	}167}168func options() *FlagOptions {169	outFile := flag.String("O", "", "Signed file name")170	inputFile := flag.String("I", "", "Unsiged file name to be signed")171	domain := flag.String("Domain", "", "Domain you want to create a fake code sign for")172	password := flag.String("Password", "", "Password for real certificate")173	real := flag.String("Real", "", "Path to a valid .pfx certificate file")174	verify := flag.String("Verify", "", "Verifies a file's code sign certificate")175	debug := flag.Bool("debug", false, "Print debug statements")176	flag.Parse()177	debugging = *debug178	debugWriter = os.Stdout179	return &FlagOptions{outFile: *outFile, inputFile: *inputFile, domain: *domain, password: *password, real: *real, verify: *verify}180}181func main() {182	fmt.Println(`183	.____    .__               .____    .__       .__     __                184	|    |   |__| _____   ____ |    |   |__| ____ |  |___/  |_  ___________ 185	|    |   |  |/     \_/ __ \|    |   |  |/ ___\|  |  \   __\/ __ \_  __ \186	|    |___|  |  Y Y  \  ___/|    |___|  / /_/  >   Y  \  | \  ___/|  | \/187	|_______ \__|__|_|  /\___  >_______ \__\___  /|___|  /__|  \___  >__|   188		\/        \/     \/        \/ /_____/      \/          \/         			189							@Tyl0us190	191	192[*] A Tool for Code Signing... Real and fake`)193	opt := options()194	if opt.verify == "" && opt.inputFile == "" && opt.outFile == "" {195		log.Fatal("Error: Please provide a file to sign or a file check")196	}197	if opt.verify == "" && opt.inputFile == "" {198		log.Fatal("Error: Please provide a file to sign")199	}200	if opt.verify == "" && opt.outFile == "" {201		log.Fatal("Error: Please provide a name for the signed file")202	}203	if opt.real == "" && opt.domain == "" && opt.verify == "" {204		log.Fatal("Error: Please specify a valid path to a .pfx file or specify the domain to spoof")205	}206	if opt.verify != "" {207		fmt.Println("[*] Checking code signed on file: " + opt.verify)208		Check(opt.verify)209		os.Exit(3)210	}211	if opt.real != "" {212		fmt.Println("[*] Signing " + opt.inputFile + " with a valid cert " + opt.real)213		SignExecutable(opt.password, opt.real, opt.inputFile, opt.outFile)214	} else {215		password := VarNumberLength(8, 12)216		pfx := opt.domain + ".pfx"217		fmt.Println("[*] Signing " + opt.inputFile + " with a fake cert")218		GenerateCert(opt.domain, opt.inputFile)219		GeneratePFK(password, opt.domain)220		SignExecutable(password, pfx, opt.inputFile, opt.outFile)221	}222	fmt.Println("[*] Cleaning up....")223	printDebug("[!] Deleting " + opt.domain + ".pem\n")224	os.Remove(opt.domain + ".pem")225	printDebug("[!] Deleting " + opt.domain + ".key\n")226	os.Remove(opt.domain + ".key")227	printDebug("[!] Deleting " + opt.domain + ".pfx\n")228	os.Remove(opt.domain + ".pfx")229	fmt.Println(color.GreenString("[+] ") + "Signed File Created.")230}...signExecutable
Using AI Code Generation
1import (2func main() {3    usr, err := user.Current()4    if err != nil {5        fmt.Println(err)6        os.Exit(1)7    }8    desktop := filepath.Join(home, "Desktop")9    downloads := filepath.Join(home, "Downloads")10    documents := filepath.Join(home, "Documents")11    pictures := filepath.Join(home, "Pictures")12    music := filepath.Join(home, "Music")13    videos := filepath.Join(home, "Videos")14    public := filepath.Join(home, "Public")15    templates := filepath.Join(home, "Templates")16    applications := filepath.Join(home, "Applications")17    library := filepath.Join(home, "Library")18    goPath := filepath.Join(home, "go")19    goSrc := filepath.Join(home, "go/src")20    goBin := filepath.Join(home, "go/bin")21    goPkg := filepath.Join(home, "go/pkg")22    goSrcGithub := filepath.Join(home, "go/src/github.com")23    goSrcGithubProtonMail := filepath.Join(home, "go/src/github.com/ProtonMail")signExecutable
Using AI Code Generation
1import (2func main() {3	file, err := os.Open("C:/Users/HP/Desktop/1.exe")4	if err != nil {5		log.Fatal(err)6	}7	defer file.Close()8	info, _ := file.Stat()9	size := info.Size()10	data := make([]byte, size)11	file.Read(data)12	signedData, err := main.SignExecutable(data)13	if err != nil {14		log.Fatal(err)15	}16	out, err := os.Create("C:/Users/HP/Desktop/2.exe")17	if err != nil {18		log.Fatal(err)19	}20	defer out.Close()21	out.Write(signedData)22	fmt.Println("Done!")23}24import (25func main() {26	file, err := os.Open("C:/Users/HP/Desktop/1.exe")27	if err != nil {28		log.Fatal(err)29	}30	defer file.Close()31	info, _ := file.Stat()32	size := info.Size()33	data := make([]byte, size)34	file.Read(data)35	signedData, err := main.SignExecutable(data)36	if err != nil {37		log.Fatal(err)38	}39	out, err := os.Create("C:/Users/HP/Desktop/2.exe")40	if err != nil {41		log.Fatal(err)42	}43	defer out.Close()44	out.Write(signedData)45	fmt.Println("Done!")46}47import (48func main() {49	file, err := os.Open("C:/Users/HP/Desktop/1.exe")50	if err != nil {51		log.Fatal(err)52	}53	defer file.Close()54	info, _ := file.Stat()55	size := info.Size()56	data := make([]byte, size)57	file.Read(data)58	signedData, err := main.SignExecutable(data)59	if err != nil {60		log.Fatal(err)61	}signExecutable
Using AI Code Generation
1import (2func main() {3	fmt.Println("Hello, playground")4	s=main.Signer{}5	s.SignExecutable()6}7import (8func main() {9	fmt.Println("Hello, playground")10	s=main.Signer{}11	s.SignExecutable()12}13import (14func main() {15	fmt.Println("Hello, playground")16	s=main.Signer{}17	s.SignExecutable()18}19import (20func main() {21	fmt.Println("Hello, playground")22	s=main.Signer{}23	s.SignExecutable()24}25import (26func main() {27	fmt.Println("Hello, playground")28	s=main.Signer{}29	s.SignExecutable()30}31import (32func main() {33	fmt.Println("Hello, playground")34	s=main.Signer{}35	s.SignExecutable()36}37import (38func main() {39	fmt.Println("Hello, playground")40	s=main.Signer{}41	s.SignExecutable()42}43import (44func main() {45	fmt.Println("Hello, playground")46	s=main.Signer{}47	s.SignExecutable()48}49import (50func main() {51	fmt.Println("Hello, playground")Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
