Last active
May 29, 2019 10:37
-
-
Save paralax/a8d83a286523638feaf2d33efed14c73 to your computer and use it in GitHub Desktop.
search censys from the CLI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"github.com/abadojack/gocensys" | |
"log" | |
"os" | |
"strings" | |
) | |
func contains(s []string, e string) bool { | |
for _, a := range s { | |
if a == e { | |
return true | |
} | |
} | |
return false | |
} | |
func trimSuffix(s, suffix string) string { | |
if strings.HasSuffix(s, suffix) { | |
s = s[:len(s)-len(suffix)] | |
} | |
return s | |
} | |
func usage() { | |
fmt.Println("Usage:", os.Args[0], "action arg [arg ...]") | |
fmt.Println(" action search or view") | |
fmt.Println(" arg search terms or an IPv4 address") | |
os.Exit(1) | |
} | |
func main() { | |
if len(os.Args) < 3 { | |
usage() | |
} | |
action := os.Args[1] | |
UID := os.Getenv("CENSYS_API_ID") | |
SECRET := os.Getenv("CENSYS_API_SECRET") | |
if (UID == "") || (SECRET == "") { | |
log.Fatal("Unable to read Censys env variables CENSYS_API_ID and CENSYS_API_SECRET") | |
} | |
api := gocensys.NewCensysAPI(UID, SECRET, nil) | |
var j []byte | |
if action == "search" { | |
fields := []string{"ip", | |
"updated_at", | |
"protocols", | |
"metadata.description", | |
"autonomous_system.name", | |
"23.telnet.banner", | |
"80.http.get.title", | |
"80.http.get.metadata.description", | |
"8080.http.get.metadata.description", | |
"8888.http.get.metadata.description", | |
"443.https.get.metadata.description", | |
"443.https.get.title", | |
"443.https.tls.certificate.parsed.subject_dn", | |
"443.https.tls.certificate.parsed.names", | |
"443.https.tls.certificate.parsed.subject.common_name", | |
"443.https.tls.certificate.parsed.extensions.subject_alt_name.dns_names"} | |
for _, arg := range os.Args { | |
if strings.Contains(arg, ".") && strings.Contains(arg, ":") { | |
if !contains(fields, arg) { | |
fields = append(fields, trimSuffix(strings.Split(arg, ":")[0], ":")) | |
} | |
} | |
} | |
query := map[string]interface{}{ | |
"query": strings.Join(os.Args[2:], " "), | |
"fields": fields, | |
} | |
res, err := api.Search("ipv4", query) | |
if err != nil { | |
log.Fatal(err) | |
} | |
j, _ = json.Marshal(res) | |
} else if action == "view" { | |
res, err := api.ViewDocument("ipv4", os.Args[2]) | |
if err != nil { | |
log.Fatal(err) | |
} | |
j, _ = json.Marshal(res) | |
} else { | |
log.Fatal("Unknown action. Expected search or view.") | |
} | |
fmt.Println(string(j)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment