### Install and Import Afero Go Package Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/spf13/afero/README.md This snippet shows how to install the Afero library using 'go get' and how to import it into your Go project for use. It's the first step to integrating Afero's filesystem abstractions. ```Go import "github.com/spf13/afero" ``` -------------------------------- ### Complete Mux Server Example in Go Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/gorilla/mux/README.md A minimal, runnable example of a Go HTTP server using Gorilla mux router. Demonstrates the basic setup pattern including package imports, handler function definition, router creation, route registration, and server startup on a specified port. ```go package main import ( "net/http" "log" "github.com/gorilla/mux" ) func YourHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Gorilla!\n")) } func main() { r := mux.NewRouter() r.HandleFunc("/", YourHandler) log.Fatal(http.ListenAndServe(":8000", r)) } ``` -------------------------------- ### Install Pretty Go Package Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/tidwall/pretty/README.md Install the Pretty Go package using the go get command. This retrieves the library from the GitHub repository and makes it available for use in your Go projects. ```shell go get -u github.com/tidwall/pretty ``` -------------------------------- ### Install BuntDB Package Using Go Get Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/tidwall/buntdb/README.md Install the BuntDB library using the Go package manager. This command retrieves the BuntDB package and makes it available for use in your Go projects. ```shell go get -u github.com/tidwall/buntdb ``` -------------------------------- ### Create Basic HTTP/HTTPS Transparent Proxy in Go Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/elazarl/goproxy/README.md Creates a basic HTTP/HTTPS transparent proxy server using GoProxy that listens on port 8080. This is the simplest setup to get started with GoProxy, creating a new proxy instance and starting an HTTP server with verbose logging enabled. ```Go package main import ( "github.com/elazarl/goproxy" "log" "net/http" ) func main() { proxy := goproxy.NewProxyHttpServer() proxy.Verbose = true log.Fatal(http.ListenAndServe(":8080", proxy)) } ``` -------------------------------- ### Go: Setup and Run Evilginx2 Terminal Interface Source: https://context7.com/kgretzky/evilginx2/llms.txt This Go code snippet demonstrates how to set up and start the interactive terminal interface for Evilginx2. It initializes the terminal with necessary components like the HTTP proxy, configuration, certificate database, and main database. The terminal provides commands for managing phishlets, lures, sessions, and configuration settings. ```go package main import ( "github.com/kgretzky/evilginx2/core" "github.com/kgretzky/evilginx2/database" ) // Terminal interface setup func startTerminal(proxy *core.HttpProxy, cfg *core.Config, crtDb *core.CertDb, db *database.Database) error { // Create terminal instance term, err := core.NewTerminal(proxy, cfg, crtDb, db, false) if err != nil { return err } defer term.Close() // Start interactive terminal session // Available commands: // - config: View/modify configuration // - phishlets: List available phishlets // - lures: Create and manage lures // - sessions: View captured sessions // - blacklist: Manage IP blacklist // - help: Show available commands term.DoWork() return nil } ``` -------------------------------- ### Install Match Package Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/tidwall/match/README.md Installs the 'match' package using the Go build tool. This command fetches and installs the latest version of the package, making it available for use in your Go projects. ```bash go get -u github.com/tidwall/match ``` -------------------------------- ### Go: Install Properties Library Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/magiconair/properties/README.md Command to install or upgrade the properties Go library to the latest version. This command fetches the latest code from the repository and updates the local installation. ```shell go get -u github.com/magiconair/properties ``` -------------------------------- ### Get Configuration Values using Viper Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/spf13/viper/README.md This example shows how to retrieve configuration values from Viper using various Get methods. It highlights the use of `IsSet` to check for the existence of a key, preventing the return of zero values for unset keys. The examples demonstrate retrieving boolean, string, and other data types. ```go viper.GetString("logfile") // case-insensitive Setting & Getting if viper.GetBool("verbose") { fmt.Println("verbose enabled") } ``` -------------------------------- ### Basic Pattern Matching Examples Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/tidwall/match/README.md Demonstrates the basic usage of the 'match.Match' function with different wildcard patterns. These examples show how '*' and '?' can be used to match various string patterns. ```go match.Match("hello", "*llo") match.Match("jello", "?ello") match.Match("hello", "h*o") ``` -------------------------------- ### Set Configuration using crypt CLI Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/spf13/viper/README.md Shows how to use the `crypt` command-line tool to set configuration values in a key/value store. It covers both plaintext and potentially encrypted settings, with examples for setting and getting configuration data. ```bash $ go get github.com/bketelsen/crypt/bin/crypt $ crypt set -plaintext /config/hugo.json /Users/hugo/settings/config.json ``` ```bash $ crypt get -plaintext /config/hugo.json ``` -------------------------------- ### Install go-colorable Package (Shell) Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/mattn/go-colorable/README.md This command installs the go-colorable package, which is necessary for enabling color output on Windows. It uses the standard Go package management tool to fetch and install the library. ```bash go get github.com/mattn/go-colorable ``` -------------------------------- ### Install go-toml Command Line Tools Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/pelletier/go-toml/README.md Provides the `go install` commands to install the `tomll` (linter), `tomljson` (TOML to JSON converter), and `jsontoml` (JSON to TOML converter) command-line utilities. These tools are useful for quick conversions and validation outside of Go programs. ```bash go install github.com/pelletier/go-toml/cmd/tomll tomll --help ``` ```bash go install github.com/pelletier/go-toml/cmd/tomljson tomljson --help ``` ```bash go install github.com/pelletier/go-toml/cmd/jsontoml jsontoml --help ``` -------------------------------- ### Install Resty Go Library using Go Modules Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/go-resty/resty/v2/README.md This command installs the Resty Go library and its specified version using Go Modules. Ensure you have Go Modules enabled in your project. ```bash require github.com/go-resty/resty/v2 v2.11.0 ``` -------------------------------- ### Install the Go Color Package Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/fatih/color/README.md This command installs the 'color' package for Go projects. It uses the Go module system to fetch and manage dependencies. ```bash go get github.com/fatih/color ``` -------------------------------- ### Install Viper Go Package Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/spf13/viper/README.md Command to install the Viper configuration library using Go's package management system. Requires Go modules to be enabled in your project. ```shell go get github.com/spf13/viper ``` -------------------------------- ### Install gorilla/mux Router Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/gorilla/mux/README.md Installs the gorilla/mux package using the Go toolchain. Ensure your Go environment is correctly configured for development and testing. ```sh go get -u github.com/gorilla/mux ``` -------------------------------- ### Simple GET Request with Resty Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/go-resty/resty/v2/README.md This Go code snippet shows how to perform a simple GET request using the Resty library. It includes creating a client, making the request with tracing enabled, and printing response details and trace information. Dependencies include the standard Go 'fmt' package and the 'resty' library. ```go // Create a Resty Client client := resty.New() resp, err := client.R(). EnableTrace(). Get("https://httpbin.org/get") // Explore response object fmt.Println("Response Info:") fmt.Println(" Error :", err) fmt.Println(" Status Code:", resp.StatusCode()) fmt.Println(" Status :", resp.Status()) fmt.Println(" Proto :", resp.Proto()) fmt.Println(" Time :", resp.Time()) fmt.Println(" Received At:", resp.ReceivedAt()) fmt.Println(" Body :\n", resp) fmt.Println() // Explore trace info fmt.Println("Request Trace Info:") ti := resp.Request.TraceInfo() fmt.Println(" DNSLookup :", ti.DNSLookup) fmt.Println(" ConnTime :", ti.ConnTime) fmt.Println(" TCPConnTime :", ti.TCPConnTime) fmt.Println(" TLSHandshake :", ti.TLSHandshake) fmt.Println(" ServerTime :", ti.ServerTime) fmt.Println(" ResponseTime :", ti.ResponseTime) fmt.Println(" TotalTime :", ti.TotalTime) fmt.Println(" IsConnReused :", ti.IsConnReused) fmt.Println(" IsConnWasIdle :", ti.IsConnWasIdle) fmt.Println(" ConnIdleTime :", ti.ConnIdleTime) fmt.Println(" RequestAttempt:", ti.RequestAttempt) fmt.Println(" RemoteAddr :", ti.RemoteAddr.String()) ``` -------------------------------- ### Install Go YAML Package Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/gopkg.in/yaml.v2/README.md Command to install the Go YAML package (gopkg.in/yaml.v2) using the Go build tool. ```bash go get gopkg.in/yaml.v2 ``` -------------------------------- ### Install GJSON Go Package Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/tidwall/gjson/README.md Installs the GJSON package using the Go toolchain. This command retrieves the latest version of the library and makes it available for use in Go projects. ```sh go get -u github.com/tidwall/gjson ``` -------------------------------- ### Initializing Native OS File System (OsFs) Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/spf13/afero/README.md Demonstrates how to initialize Afero's OsFs backend, which is a direct wrapper around the native operating system's file system calls. This is useful for production environments. ```go appfs := afero.NewOsFs() appfs.MkdirAll("src/a", 0755) ``` -------------------------------- ### Calling Afero Utilities Directly Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/spf13/afero/README.md Demonstrates how to call Afero utility functions directly, where the file system is passed as the first argument to each function. This approach requires explicitly providing the filesystem instance. ```go fs := new(afero.MemMapFs) f, err := afero.TempFile(fs,"", "ioutil-test") ``` -------------------------------- ### GJSON Built-in Modifiers Examples Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/tidwall/gjson/README.md Provides examples of using GJSON's built-in modifiers like `@pretty` with arguments. This snippet shows how to format JSON output with sorted keys and indentation. ```gjson_path @pretty:{"sortKeys":true} ``` -------------------------------- ### Get a JSON Value Using GJSON Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/tidwall/gjson/README.md Demonstrates how to retrieve a specific value from a JSON string using the gjson.Get function. It takes the JSON string and a dot-notation path as input, returning the found value. The example prints the 'last' name from a nested JSON object. ```go package main import "github.com/tidwall/gjson" const json = `{"name":{"first":"Janet","last":"Prichard"},"age":47}` func main() { value := gjson.Get(json, "name.last") println(value.String()) } ``` -------------------------------- ### HTTP Proxy Initialization (Go) Source: https://context7.com/kgretzky/evilginx2/llms.txt This Go code demonstrates the initialization of the Evilginx HTTP proxy server. It sets up configuration, a database for session storage, a blacklist, and a certificate database before starting the proxy on the specified address and port. ```go package main import ( "fmt" "github.com/kgretzky/evilginx2/core" "github.com/kgretzky/evilginx2/database" "path/filepath" ) // Initialize the HTTP proxy with configuration func setupProxy() error { // Configuration directory for storing settings cfgDir := "/home/user/.evilginx" // Create configuration instance cfg, err := core.NewConfig(cfgDir, "") if err != nil { return fmt.Errorf("config initialization failed: %v", err) } // Initialize database for session storage db, err := database.NewDatabase(filepath.Join(cfgDir, "data.db")) if err != nil { return fmt.Errorf("database initialization failed: %v", err) } // Create blacklist for blocking unwanted IPs bl, err := core.NewBlacklist(filepath.Join(cfgDir, "blacklist.txt")) if err != nil { return fmt.Errorf("blacklist initialization failed: %v", err) } // Initialize certificate database for TLS crtDb, err := core.NewCertDb(filepath.Join(cfgDir, "crt"), cfg, ns) if err != nil { return fmt.Errorf("certificate db initialization failed: %v", err) } // Create HTTP proxy instance // Binds to 0.0.0.0:443, developer mode disabled proxy, err := core.NewHttpProxy("0.0.0.0", 443, cfg, crtDb, db, bl, false) if err != nil { return fmt.Errorf("proxy initialization failed: %v", err) } // Start the proxy server proxy.Start() return nil } ``` -------------------------------- ### Import go-toml Library Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/pelletier/go-toml/README.md This snippet shows the standard Go import statement required to use the go-toml library in your project. Ensure you have the library installed via `go get`. ```go import "github.com/pelletier/go-toml" ``` -------------------------------- ### GJSON Custom Modifier Implementation Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/tidwall/gjson/README.md Shows how to define and use custom modifiers in GJSON. This example implements a `@case` modifier to convert JSON string values to upper or lower case. ```go gjson.AddModifier("case", func(json, arg string) string { if arg == "upper" { return strings.ToUpper(json) } if arg == "lower" { return strings.ToLower(json) } return json }) ``` -------------------------------- ### Start TLS Listener (Go) Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/caddyserver/certmagic/README.md Initiates a TLS listener for the given hostnames. This function is useful when you need to directly manage the TLS connection lifecycle or integrate with existing network setups. ```go ln, err := certmagic.Listen([]string{"example.com"}) if err != nil { return err } ``` -------------------------------- ### Initializing Memory-Backed File System (MemMapFs) Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/spf13/afero/README.md Shows how to initialize Afero's MemMapFs, an in-memory file system suitable for testing and scenarios where disk persistence is not required. It is fully concurrent and safe for use in goroutines. ```go mm := afero.NewMemMapFs() mm.MkdirAll("src/a", 0755) ``` -------------------------------- ### Sample Form Submission with Resty Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/go-resty/resty/v2/README.md Provides examples of submitting form data using Resty. This includes standard form submissions for login and profile updates, as well as handling multi-value form data using `SetFormDataFromValues`. ```go client := resty.New() // User Login resp, err := client.R(). SetFormData(map[string]string{ "username": "jeeva", "password": "mypass", }). Post("http://myapp.com/login") // Profile update resp, err := client.R(). SetFormData(map[string]string{ "first_name": "Jeevanandam", "last_name": "M", "zip_code": "00001", "city": "new city update", }). Post("http://myapp.com/profile") // Multi value form data criteria := url.Values{ "search_criteria": []string{"book", "glass", "pencil"}, } resp, err := client.R(). SetFormDataFromValues(criteria). Post("http://myapp.com/search") ``` -------------------------------- ### Process JSON Lines with GJSON Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/tidwall/gjson/README.md Demonstrates how to process multi-line JSON documents treated as an array using the '..' prefix. Shows examples of accessing specific lines, counting lines, and filtering by field values. ```Shell {"name": "Gilbert", "age": 61} {"name": "Alexa", "age": 34} {"name": "May", "age": 57} {"name": "Deloise", "age": 44} ``` ```Shell ..# >> 4 ..1 >> {"name": "Alexa", "age": 34} ..3 >> {"name": "Deloise", "age": 44} ..#.name >> ["Gilbert","Alexa","May","Deloise"] ..#(name="May").age >> 57 ``` -------------------------------- ### Testing with MemMapFs for File Existence Check Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/spf13/afero/README.md Shows a unit test using Afero's MemMapFs to simulate a filesystem. This example creates directories and files within the mock filesystem and then checks for the existence of a file using `Stat`. ```go func TestExist(t *testing.T) { appFS := afero.NewMemMapFs() // create test files and directories appFS.MkdirAll("src/a", 0755) afero.WriteFile(appFS, "src/a/b", []byte("file b"), 0644) afero.WriteFile(appFS, "src/c", []byte("file c"), 0644) name := "src/c" _, err := appFS.Stat(name) if os.IsNotExist(err) { t.Errorf("file \"%s\" does not exist.\n", name) } } ``` -------------------------------- ### Bash: Example cURL Request for CORS Handling Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/gorilla/mux/README.md This bash command demonstrates how to make a cURL request to a local server endpoint that is configured to handle CORS requests. It shows the client-side initiation of a GET request to `/foo` on port 8080. ```bash curl localhost:8080/foo -v ``` -------------------------------- ### Define Dynamic Authentication URLs (YAML) Source: https://github.com/kgretzky/evilginx2/wiki/Phishlet-File-Format-(2.3.0) This example shows how to define multiple authentication URLs, including wildcard patterns, to trigger session capture. This is useful when session cookies are dynamically generated and cannot be reliably identified by name alone. ```yaml auth_urls: - '/admin' - '/admin/.*' ``` -------------------------------- ### Initialize CopyOnWriteFs Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/spf13/afero/README.md Creates a CopyOnWriteFs, which uses a read-only base filesystem and a writable overlay. Reads check the overlay first, then the base. Writes are made to the overlay. Files initially only in the base are copied to the overlay upon modification. ```go base := afero.NewOsFs() roBase := afero.NewReadOnlyFs(base) ufs := afero.NewCopyOnWriteFs(roBase, afero.NewMemMapFs()) fh, _ = ufs.Create("/home/test/file2.txt") fh.WriteString("This is a test") fh.Close() ``` -------------------------------- ### Build URL with Host and Query Variables (Go) Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/gorilla/mux/README.md Shows how to build a complete URL including host and query parameters from a named route. This example includes subdomain, path variables, and query filters. ```go r := mux.NewRouter() r.Host("{subdomain}.example.com"). Path("/articles/{category}/{id:[0-9]+}"). Queries("filter", "{filter}"). HandlerFunc(ArticleHandler). Name("article") url, err := r.Get("article").URL("subdomain", "news", "category", "technology", "id", "42", "filter", "gorilla") // url.String() will be "http://news.example.com/articles/technology/42?filter=gorilla" ``` -------------------------------- ### Configure JSON Credentials Capture (YAML) Source: https://github.com/kgretzky/evilginx2/wiki/Phishlet-File-Format-(2.3.0) This example demonstrates how to configure Evilginx2 to capture credentials from JSON payloads. It specifies the 'json' type and uses regular expressions to extract values for 'email' and 'password' directly from the JSON string. ```yaml credentials: username: key: '' search: '"email":"([^"]*)"' type: 'json' password: key: '' search: '"password":"([^"]*)"' type: 'json' ``` -------------------------------- ### GJSON Result Utility Functions Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/tidwall/gjson/README.md Provides examples of common utility functions available on the `gjson.Result` type in Go. These functions allow for checking existence, retrieving values as various types (interface{}, int64, uint64, float64, string, bool, time.Time), and converting results to arrays or maps. ```go result.Exists() bool result.Value() interface{} result.Int() int64 result.Uint() uint64 result.Float() float64 result.String() string result.Bool() bool result.Time() time.Time result.Array() []gjson.Result result.Map() map[string]gjson.Result result.Get(path string) Result result.ForEach(iterator func(key, value Result) bool) result.Less(token Result, caseSensitive bool) bool ``` -------------------------------- ### Simple JSON Parsing and Getting Values with Go Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/tidwall/gjson/README.md Explains the basic `Parse` and `Get` functions in GJSON for parsing JSON strings and retrieving values using dot notation or chained `Get` calls. Shows equivalent ways to access nested properties. ```Go gjson.Parse(json).Get("name").Get("last") gjson.Get(json, "name").Get("last") gjson.Get(json, "name.last") ``` -------------------------------- ### Manage Global Evilginx2 Configuration Settings (Go) Source: https://context7.com/kgretzky/evilginx2/llms.txt This Go function demonstrates how to configure global settings for Evilginx2. It covers creating a configuration instance, setting the base domain, server IP addresses (external and bind), ports (HTTPS and DNS), enabling/disabling autocert, setting the unauthorized URL, and configuring an optional proxy. The 'core' package is required. ```go package main import ( "github.com/kgretzky/evilginx2/core" ) // Configuration management func configureEvilginx() error { cfgDir := "/home/user/.evilginx" // Create configuration cfg, err := core.NewConfig(cfgDir, "") if err != nil { return err } // Set base domain for phishing cfg.SetBaseDomain("phishing-domain.com") // Set server IP addresses cfg.SetServerExternalIP("203.0.113.10") // Public IP cfg.SetServerBindIP("0.0.0.0") // Bind address // Set ports cfg.SetHttpsPort(443) cfg.SetDnsPort(53) // Enable automatic certificate generation cfg.SetAutocert(true) // Set default unauthorized URL (where non-targeted visitors go) cfg.SetUnauthUrl("https://www.youtube.com/watch?v=dQw4w9WgXcQ") // Configure proxy (optional) err = cfg.SetProxyConfig( "socks5", // type: socks5, http, https "proxy.example.com", // address 1080, // port "username", // username "password", // password true, // enabled ) // Save configuration err = cfg.Save() if err != nil { return err } return nil } ``` -------------------------------- ### Allow GET Requests with Payload in Resty (Go) Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/go-resty/resty/v2/README.md Shows how to enable the 'Allow GET Method Payload' option for a Resty HTTP client. This is disabled by default and allows sending a request body with GET requests. ```go // Create a Resty Client client := resty.New() // Allow GET request with Payload. This is disabled by default. client.SetAllowGetMethodPayload(true) ``` -------------------------------- ### Get Nested Array Values with Go Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/tidwall/gjson/README.md Illustrates how to retrieve values from nested arrays within a JSON structure using GJSON paths. It covers getting all elements of a specific field in an array and querying objects within an array based on their properties. ```Go { "programmers": [ { "firstName": "Janet", "lastName": "McLaughlin", }, { "firstName": "Elliotte", "lastName": "Hunter", }, { "firstName": "Jason", "lastName": "Harold", } ] } ``` ```Go result := gjson.Get(json, "programmers.#.lastName") for _, name := range result.Array() { println(name.String()) } ``` ```Go name := gjson.Get(json, `programmers.#(lastName="Hunter").firstName`) println(name.String()) // prints "Elliotte" ``` -------------------------------- ### Create jWalterWeatherman Notebook instance in Go Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/spf13/jwalterweatherman/README.md Demonstrates creating a non-global Notebook instance with custom log levels and output destinations. Allows independent configuration of logging separate from global settings by specifying output writers, log formats, and severity thresholds. ```go notepad = jww.NewNotepad(jww.LevelInfo, jww.LevelTrace, os.Stdout, ioutil.Discard, "", log.Ldate|log.Ltime) notepad.WARN.Println("Some warning") ``` -------------------------------- ### Walk All Registered Routes (Go) Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/gorilla/mux/README.md Provides an example of using the `Walk` function on a `mux.Router` to iterate through all registered routes. For each route, it prints details like path template, regex, methods, and query parameters. ```go package main import ( "fmt" "net/http" "strings" "github.com/gorilla/mux" ) func handler(w http.ResponseWriter, r *http.Request) { return } func main() { r := mux.NewRouter() r.HandleFunc("/", handler) r.HandleFunc("/products", handler).Methods("POST") r.HandleFunc("/articles", handler).Methods("GET") r.HandleFunc("/articles/{id}", handler).Methods("GET", "PUT") r.HandleFunc("/authors", handler).Queries("surname", "{surname}") err := r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error { pathTemplate, err := route.GetPathTemplate() if err == nil { fmt.Println("ROUTE:", pathTemplate) } pathRegexp, err := route.GetPathRegexp() if err == nil { fmt.Println("Path regexp:", pathRegexp) } queriesTemplates, err := route.GetQueriesTemplates() if err == nil { fmt.Println("Queries templates:", strings.Join(queriesTemplates, ",")) } queriesRegexps, err := route.GetQueriesRegexp() if err == nil { fmt.Println("Queries regexps:", strings.Join(queriesRegexps, ",")) } methods, err := route.GetMethods() if err == nil { fmt.Println("Methods:", strings.Join(methods, ",")) } fmt.Println() return nil }) if err != nil { fmt.Println(err) } http.Handle("/", r) } ``` -------------------------------- ### Serve Static Files using PathPrefix and FileServer Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/gorilla/mux/README.md Provides an example of how to configure Gorilla Mux to serve static files from a directory. It uses `PathPrefix` to define the URL path and `http.FileServer` to handle file serving, along with `http.StripPrefix`. ```go func main() { var dir string flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir") flag.Parse() r := mux.NewRouter() // This will serve files under http://localhost:8000/static/ r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir)))) srv := &http.Server{ Handler: r, Addr: "127.0.0.1:8000", // Good practice: enforce timeouts for servers you create! WriteTimeout: 15 * time.Second, ReadTimeout: 15 * time.Second, } log.Fatal(srv.ListenAndServe()) } ``` -------------------------------- ### Build URL with Subrouters (Go) Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/gorilla/mux/README.md Demonstrates how to build a URL when using subrouters, where host and path definitions might be applied at different levels. This example shows building a URL from a router with a subrouter defining the host. ```go r := mux.NewRouter() s := r.Host("{subdomain}.example.com").Subrouter() s.Path("/articles/{category}/{id:[0-9]+}"). HandlerFunc(ArticleHandler). Name("article") url, err := r.Get("article").URL("subdomain", "news", "category", "technology", "id", "42") // url.String() will be "http://news.example.com/articles/technology/42" ``` -------------------------------- ### Declare Afero Filesystem Backend in Go Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/spf13/afero/README.md Demonstrates declaring a package variable to hold an Afero filesystem instance. It provides examples for using an in-memory filesystem ('MemMapFs') for testing or the OS filesystem ('OsFs') for real-world operations. Choosing the correct backend is crucial for application behavior and testability. ```Go var AppFs = afero.NewMemMapFs() or var AppFs = afero.NewOsFs() ``` -------------------------------- ### Basic Route Registration in mux Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/gorilla/mux/README.md Demonstrates the basic usage of gorilla/mux for registering URL paths with corresponding handler functions. This is analogous to Go's standard http.HandleFunc. ```go package main import ( "net/http" "github.com/gorilla/mux" ) func main() { r := mux.NewRouter() r.HandleFunc("/", HomeHandler) r.HandleFunc("/products", ProductsHandler) r.HandleFunc("/articles", ArticlesHandler) http.Handle("/", r) } ``` -------------------------------- ### Calling Afero Utilities via Afero Type Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/spf13/afero/README.md Illustrates using Afero utility functions by binding them as methods to an Afero custom type. This approach involves creating an Afero instance that holds the underlying filesystem. ```go fs := afero.NewMemMapFs() afs := &afero.Afero{Fs: fs} f, err := afs.TempFile("", "ioutil-test") ``` -------------------------------- ### Install go-isatty Package Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/mattn/go-isatty/README.md This command installs the `go-isatty` package, which provides functionality for detecting terminal file descriptors in Go programs. It uses the standard Go command-line tool for package management. ```bash go get github.com/mattn/go-isatty ``` -------------------------------- ### Start a TLS Listener with CertMagic Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/caddyserver/certmagic/README.md Demonstrates how to start a TLS listener using CertMagic, which manages TLS certificates automatically. This is useful for directly listening for HTTPS connections on a specific port with custom configurations. ```go // Start a TLS listener cer, err := certmagic.GetCertificate(nil, "example.com") if err != nil { // handle error } listener, err := certmagic.NewListener(nil, "example.com", ":443") if err != nil { // handle error } defer listener.Close() for { conn, err := listener.Accept() if err != nil { // handle error continue } go http.Serve(conn, mux) } ``` -------------------------------- ### Afero File System Methods in Go Source: https://github.com/kgretzky/evilginx2/blob/master/vendor/github.com/spf13/afero/README.md Lists the available methods on an Afero filesystem object, mirroring many operations found in the standard Go 'os' package. These methods allow for file manipulation, directory creation, and status checking through the Afero abstraction layer. ```Go Chmod(name string, mode os.FileMode) : error Chown(name string, uid, gid int) : error Chtimes(name string, atime time.Time, mtime time.Time) : error Create(name string) : File, error Mkdir(name string, perm os.FileMode) : error MkdirAll(path string, perm os.FileMode) : error Name() : string Open(name string) : File, error OpenFile(name string, flag int, perm os.FileMode) : File, error Remove(name string) : error RemoveAll(path string) : error Rename(oldname, newname string) : error Stat(name string) : os.FileInfo, error ``` -------------------------------- ### HTML Structure and CSS Styling for Evilginx2 Source: https://github.com/kgretzky/evilginx2/blob/master/redirectors/download_example/index.html This snippet details the basic HTML structure and CSS styles used for the Evilginx2 interface. It includes styling for the page background, a central box, messages, and download elements. Dependencies include standard HTML and CSS. ```html body { background-color: #28a745; } #box { position: absolute; top: 50%; left: 50%; text-align: center; background-color: #fff; padding: 40px 40px; transform: translate(-50%, -50%); border-radius: 16px; -webkit-box-shadow: 10px 10px 22px 0px rgba(0,0,0,0.75); -moz-box-shadow: 10px 10px 22px 0px rgba(0,0,0,0.75); box-shadow: 10px 10px 22px 0px rgba(0,0,0,0.75); } .message { text-align: center; font-size: 24px; font-family: Arial, Helvetica, sans-serif; } .download { text-align: center; } ```