diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c167f4f --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +go.sum +certgraph +build/ +*.json diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..23cb790 --- /dev/null +++ b/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {description} + Copyright (C) {year} {fullname} + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + {signature of Ty Coon}, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..178312e --- /dev/null +++ b/Makefile @@ -0,0 +1,39 @@ +GIT_DATE := $(shell git log -1 --date=short --pretty='%cd' | tr -d -) +GIT_HASH := $(shell git rev-parse HEAD) + +BUILD_FLAGS := -ldflags "-X main.gitDate=$(GIT_DATE) -X main.gitHash=$(GIT_HASH)" + +PLATFORMS := linux/amd64 linux/386 linux/arm darwin/amd64 windows/amd64 windows/386 openbsd/amd64 +SOURCES := $(shell find . -maxdepth 1 -type f -name "*.go") +ALL_SOURCES = $(shell find . -type f -name '*.go') + +temp = $(subst /, ,$@) +os = $(word 1, $(temp)) +arch = $(word 2, $(temp)) +ext = $(shell if [ "$(os)" = "windows" ]; then echo ".exe"; fi) + +.PHONY: all release fmt clean serv $(PLATFORMS) + +all: certgraph + +release: $(PLATFORMS) + rm -r build/bin/ + +certgraph: $(SOURCES) $(ALL_SOURCES) + go build $(BUILD_FLAGS) -o $@ $(SOURCES) + +$(PLATFORMS): $(SOURCES) + CGO_ENABLED=0 GOOS=$(os) GOARCH=$(arch) go build $(BUILD_FLAGS) -o 'build/bin/$(os)/$(arch)/certgraph$(ext)' $(SOURCES) + mkdir -p build/$(GIT_DATE)/; cd build/bin/$(os)/$(arch)/; zip -r ../../../$(GIT_DATE)/certgraph-$(os)-$(arch)-$(GIT_DATE).zip .; cd ../../../ + +fmt: + gofmt -s -w -l . + +install: $(SOURCES) $(ALL_SOURCES) + go install $(BUILD_FLAGS) + +clean: + rm -r certgraph build/ + +serv: + (cd docs; python -m SimpleHTTPServer) diff --git a/README.md b/README.md new file mode 100644 index 0000000..e83f643 --- /dev/null +++ b/README.md @@ -0,0 +1,113 @@ +# CertGraph +### A tool to crawl the graph of certificate Alternate Names + +CertGraph crawls SSL certificates creating a directed graph where each domain is a node and the certificate alternative names for that domain's certificate are the edges to other domain nodes. New domains are printed as they are found. In Detailed mode upon completion the Graph's adjacency list is printed. + +Crawling defaults to collecting certificate by connecting over TCP, however there are multiple drivers that can search [Certificate Transparency](https://www.certificate-transparency.org/) logs. + +This tool was designed to be used for host name enumeration via SSL certificates, but it can also show you a "chain" of trust between domains and the certificates that re-used between them. + +[Blog post with more information](https://lanrat.com/certgraph/) + +## Usage +``` +Usage of ./certgraph: [OPTION]... HOST... + https://github.com/lanrat/certgraph +OPTIONS: + -cdn + include certificates from CDNs + -ct-expired + include expired certificates in certificate transparency search + -ct-subdomains + include sub-domains in certificate transparency search + -depth uint + maximum BFS depth to go (default 5) + -details + print details about the domains crawled + -driver string + driver to use [crtsh, google, http, smtp] (default "http") + -json + print the graph as json, can be used for graph in web UI + -ns + check for NS records to determine if domain is registered + -parallel uint + number of certificates to retrieve in parallel (default 10) + -sanscap int + maximum number of uniq TLD+1 domains in certificate to include, 0 has no limit (default 80) + -save string + save certs to folder in PEM format + -timeout uint + tcp timeout in seconds (default 10) + -tldplus1 + for every domain found, add tldPlus1 of the domain's parent + -verbose + verbose logging + -version + print version and exit +``` + +## Drivers + +CertGraph has multiple options for querying SSL certificates. The driver is responsible for retrieving the certificates for a given domain. Currently there are the following drivers: + + * **http** this is the default driver which works by connecting to the hosts over HTTPS and retrieving the certificates from the SSL connection + + * **smtp** like the *http* driver, but connects over port 25 and issues the *starttls* command to retrieve the certificates from the SSL connection + + * **crtsh** this driver searches Certificate Transparency logs via [crt.sh](https://crt.sh/). No packets are sent to any of the domains when using this driver + + * **google** this is another Certificate Transparency driver that behaves like *crtsh* but uses the [Google Certificate Transparency Lookup Tool](https://transparencyreport.google.com/https/certificates) + + +## Example +``` +$ ./certgraph -details eff.org +eff.org 0 Good 42E3E4605D8BB4608EB64936E2176A98B97EBF2E0F8F93A64A6640713C7D4325 +maps.eff.org 1 Good 42E3E4605D8BB4608EB64936E2176A98B97EBF2E0F8F93A64A6640713C7D4325 +https-everywhere-atlas.eff.org 1 Good 42E3E4605D8BB4608EB64936E2176A98B97EBF2E0F8F93A64A6640713C7D4325 +httpse-atlas.eff.org 1 Good 42E3E4605D8BB4608EB64936E2176A98B97EBF2E0F8F93A64A6640713C7D4325 +atlas.eff.org 1 Good 42E3E4605D8BB4608EB64936E2176A98B97EBF2E0F8F93A64A6640713C7D4325 +kittens.eff.org 1 Good 42E3E4605D8BB4608EB64936E2176A98B97EBF2E0F8F93A64A6640713C7D4325 +``` +The above output represents the adjacency list for the graph for the root domain `eff.org`. The adjacency list is in the form: +`Node Depth Status Cert-Fingerprint` + +## [Releases](https://github.com/lanrat/certgraph/releases) + +Precompiled releases will occasionally be uploaded to the [releases github page](https://github.com/lanrat/certgraph/releases). https://github.com/lanrat/certgraph/releases + +Also available in [BlackArch](https://blackarch.org). + +## Compiling + +To compile certgraph you must have a working go 1.11 or newer compiler on your system, as certgraph makes use of go's modules for dependencies. +To compile for the running system compilation is as easy as running make +``` +certgraph$ make +go build -o certgraph certgraph.go +``` + +Alternatively you can use `go get` to install with this one-liner: +``` +go get -u github.com/lanrat/certgraph +``` + +## [Web UI](https://lanrat.github.io/certgraph/) + +A web UI is provided in the docs folder and is accessible at the github pages url [https://lanrat.github.io/certgraph/](https://lanrat.github.io/certgraph/). + +The web UI takes the output provided with the `-json` flag. +The JSON graph can be sent to the web interface as an uploaded file, remote URL, or as the query string using the data variable. + +### [Example 1: eff.org](https://lanrat.github.io/certgraph/?data=https://gist.githubusercontent.com/lanrat/8187d01793bf3e578d76495182654206/raw/c49741b5206d81935febdf563452cc4346381e52/eff.json) + +[![eff.org graph](https://cloud.githubusercontent.com/assets/164192/20861413/6ba0fcca-b944-11e6-857f-ddd613130ea3.png)](https://lanrat.github.io/certgraph/?data=https://gist.githubusercontent.com/lanrat/8187d01793bf3e578d76495182654206/raw/c49741b5206d81935febdf563452cc4346381e52/eff.json) + +### [Example 2: google.com](https://lanrat.github.io/certgraph/?data=https://gist.githubusercontent.com/lanrat/1ab1e78aaf5798049650d8d8ad7b58a1/raw/426d3a2498626014cb5ba2856ad0899787e4103f/google.json) + +[![google.com graph](https://cloud.githubusercontent.com/assets/164192/19752837/16cb8302-9bb5-11e6-810d-ea34594a63ef.png)](https://lanrat.github.io/certgraph/?data=https://gist.githubusercontent.com/lanrat/1ab1e78aaf5798049650d8d8ad7b58a1/raw/426d3a2498626014cb5ba2856ad0899787e4103f/google.json) + +### [Example 3: whitehouse.gov](https://lanrat.github.io/certgraph/?data=https://gist.githubusercontent.com/lanrat/96c47dfee0faaaad633cc830b7e3b997/raw/3c79fed837cb3202e220de21d2a8eb128f4bbd9f/whitehouse.json) + +[![whitehouse.gov graph](https://cloud.githubusercontent.com/assets/164192/20861407/4775ff26-b944-11e6-888c-4d93e3333494.png)](https://lanrat.github.io/certgraph/?data=https://gist.githubusercontent.com/lanrat/96c47dfee0faaaad633cc830b7e3b997/raw/3c79fed837cb3202e220de21d2a8eb128f4bbd9f/whitehouse.json) + diff --git a/certgraph.go b/certgraph.go new file mode 100644 index 0000000..f45d0ce --- /dev/null +++ b/certgraph.go @@ -0,0 +1,411 @@ +package main + +import ( + "encoding/json" + "flag" + "fmt" + "net/url" + "os" + "strings" + "sync" + "time" + + "github.com/lanrat/certgraph/dns" + "github.com/lanrat/certgraph/driver" + "github.com/lanrat/certgraph/driver/crtsh" + "github.com/lanrat/certgraph/driver/google" + "github.com/lanrat/certgraph/driver/http" + "github.com/lanrat/certgraph/driver/smtp" + "github.com/lanrat/certgraph/graph" +) + +var ( + gitDate = "none" + gitHash = "master" + certGraph = graph.NewCertGraph() +) + +var certDriver driver.Driver + +// config & flags +var config struct { + timeout time.Duration + verbose bool + maxDepth uint + parallel uint + savePath string + details bool + printJSON bool + driver string + includeCTSubdomains bool + includeCTExpired bool + cdn bool + maxSANsSize int + tldPlus1 bool + updatePSL bool + checkDNS bool + printVersion bool +} + +func init() { + var timeoutSeconds uint + flag.BoolVar(&config.printVersion, "version", false, "print version and exit") + flag.UintVar(&timeoutSeconds, "timeout", 10, "tcp timeout in seconds") + flag.BoolVar(&config.verbose, "verbose", false, "verbose logging") + flag.StringVar(&config.driver, "driver", "http", fmt.Sprintf("driver to use [%s]", strings.Join(driver.Drivers, ", "))) + flag.BoolVar(&config.includeCTSubdomains, "ct-subdomains", false, "include sub-domains in certificate transparency search") + flag.BoolVar(&config.includeCTExpired, "ct-expired", false, "include expired certificates in certificate transparency search") + flag.IntVar(&config.maxSANsSize, "sanscap", 80, "maximum number of uniq TLD+1 domains in certificate to include, 0 has no limit") + flag.BoolVar(&config.cdn, "cdn", false, "include certificates from CDNs") + flag.BoolVar(&config.checkDNS, "dns", false, "check for DNS records to determine if domain is registered") + flag.BoolVar(&config.tldPlus1, "tldplus1", false, "for every domain found, add tldPlus1 of the domain's parent") + flag.BoolVar(&config.updatePSL, "updatepsl", false, "Update the default Public Suffix List") + flag.UintVar(&config.maxDepth, "depth", 5, "maximum BFS depth to go") + flag.UintVar(&config.parallel, "parallel", 10, "number of certificates to retrieve in parallel") + flag.BoolVar(&config.details, "details", false, "print details about the domains crawled") + flag.BoolVar(&config.printJSON, "json", false, "print the graph as json, can be used for graph in web UI") + flag.StringVar(&config.savePath, "save", "", "save certs to folder in PEM format") + flag.Usage = func() { + fmt.Fprintf(os.Stderr, "Usage of %s: [OPTION]... HOST...\n\thttps://github.com/lanrat/certgraph\nOPTIONS:\n", os.Args[0]) + flag.PrintDefaults() + } + flag.Parse() + config.timeout = time.Duration(timeoutSeconds) * time.Second +} + +func main() { + // check for version flag + if config.printVersion { + fmt.Println(version()) + return + } + + // print usage if no domain passed + if flag.NArg() < 1 { + flag.Usage() + return + } + + // cant run on 0 threads + if config.parallel < 1 { + fmt.Fprintln(os.Stderr, "Must enter a positive number of parallel threads") + flag.Usage() + return + } + + // update the public suffix list if required + if config.updatePSL { + err := dns.UpdatePublicSuffixList(config.timeout) + if err != nil { + e(err) + return + } + } + + // add domains passed to startDomains + startDomains := make([]string, 0, 1) + for _, domain := range flag.Args() { + d := strings.ToLower(domain) + if len(d) > 0 { + startDomains = append(startDomains, cleanInput(d)) + if config.tldPlus1 { + tldPlus1, err := dns.TLDPlus1(domain) + if err != nil { + continue + } + startDomains = append(startDomains, tldPlus1) + } + } + } + + // set driver + err := setDriver(config.driver) + if err != nil { + fmt.Fprintln(os.Stderr, err) + return + } + + // create the output directory if it does not exist + if len(config.savePath) > 0 { + err := os.MkdirAll(config.savePath, 0777) + if err != nil { + fmt.Fprintln(os.Stderr, err) + return + } + } + + // perform breath-first-search on the graph + breathFirstSearch(startDomains) + + // print the json output + if config.printJSON { + printJSONGraph() + } + + v("Found", certGraph.NumDomains(), "domains") + v("Graph Depth:", certGraph.DomainDepth()) +} + +// setDriver sets the driver variable for the provided driver string and does any necessary driver prep work +// TODO make config generic and move this to driver module +func setDriver(driver string) error { + var err error + switch driver { + case "google": + certDriver, err = google.Driver(50, config.savePath, config.includeCTSubdomains, config.includeCTExpired) + case "crtsh": + certDriver, err = crtsh.Driver(1000, config.timeout, config.savePath, config.includeCTSubdomains, config.includeCTExpired) + case "http": + certDriver, err = http.Driver(config.timeout, config.savePath) + case "smtp": + certDriver, err = smtp.Driver(config.timeout, config.savePath) + default: + return fmt.Errorf("Unknown driver name: %s", config.driver) + } + return err +} + +// verbose logging +func v(a ...interface{}) { + if config.verbose { + e(a...) + } +} + +func e(a ...interface{}) { + if a != nil { + fmt.Fprintln(os.Stderr, a...) + } +} + +// prints the graph as a json object +func printJSONGraph() { + jsonGraph := certGraph.GenerateMap() + jsonGraph["certgraph"] = generateGraphMetadata() + + j, err := json.MarshalIndent(jsonGraph, "", "\t") + if err != nil { + fmt.Println(err) + return + } + fmt.Println(string(j)) +} + +// breathFirstSearch perform Breadth first search to build the graph +func breathFirstSearch(roots []string) { + var wg sync.WaitGroup + domainNodeInputChan := make(chan *graph.DomainNode, 5) // input queue + domainNodeOutputChan := make(chan *graph.DomainNode, 5) // output queue + + // thread limit code + threadPass := make(chan bool, config.parallel) + for i := uint(0); i < config.parallel; i++ { + threadPass <- true + } + + // thread to put root nodes/domains into queue + wg.Add(1) + go func() { + // the waitGroup Add and Done for this thread ensures that we don't exit before any of the inputs domains are put into the Queue + defer wg.Done() + for _, root := range roots { + wg.Add(1) + n := graph.NewDomainNode(root, 0) + n.Root = true + domainNodeInputChan <- n + } + }() + // thread to start all other threads from DomainChan + go func() { + for { + domainNode := <-domainNodeInputChan + + // depth check + if domainNode.Depth > config.maxDepth { + v("Max depth reached, skipping:", domainNode.Domain) + wg.Done() + continue + } + // use certGraph.domains map as list of + // domains that are queued to be visited, or already have been + + if _, found := certGraph.GetDomain(domainNode.Domain); !found { + certGraph.AddDomain(domainNode) + go func(domainNode *graph.DomainNode) { + defer wg.Done() + // wait for pass + <-threadPass + defer func() { threadPass <- true }() + + // operate on the node + v("Visiting", domainNode.Depth, domainNode.Domain) + visit(domainNode) + domainNodeOutputChan <- domainNode + for _, neighbor := range certGraph.GetDomainNeighbors(domainNode.Domain, config.cdn, config.maxSANsSize) { + wg.Add(1) + domainNodeInputChan <- graph.NewDomainNode(neighbor, domainNode.Depth+1) + if config.tldPlus1 { + tldPlus1, err := dns.TLDPlus1(neighbor) + if err != nil { + continue + } + wg.Add(1) + domainNodeInputChan <- graph.NewDomainNode(tldPlus1, domainNode.Depth+1) + } + } + }(domainNode) + } else { + wg.Done() + } + } + }() + + // save/output thread + done := make(chan bool) + go func() { + for { + domainNode, more := <-domainNodeOutputChan + if more { + if !config.printJSON { + printNode(domainNode) + } else if config.details { + fmt.Fprintln(os.Stderr, domainNode) + } + } else { + done <- true + return + } + } + }() + + wg.Wait() // wait for querying to finish + close(domainNodeOutputChan) + <-done // wait for save to finish +} + +// visit visits each node and get and set its neighbors +func visit(domainNode *graph.DomainNode) { + // check NS if necessary + if config.checkDNS { + _, err := domainNode.CheckForDNS(config.timeout) + if err != nil { + v("CheckForNS", err) + } + } + + // perform cert search + // TODO do pagination in multiple threads to not block on long searches + results, err := certDriver.QueryDomain(domainNode.Domain) + if err != nil { + // this is VERY common to error, usually this is a DNS or tcp connection related issue + // we will skip the domain if we can't query it + v("QueryDomain", domainNode.Domain, err) + return + } + statuses := results.GetStatus() + domainNode.AddStatusMap(statuses) + relatedDomains, err := results.GetRelated() + if err != nil { + v("GetRelated", domainNode.Domain, err) + return + } + domainNode.AddRelatedDomains(relatedDomains) + + // TODO parallelize this + // TODO fix printing domains as they are found with new driver + // add cert nodes to graph + fingerprintMap, err := results.GetFingerprints() + if err != nil { + v("GetFingerprints", err) + return + } + + // fingerprints for the domain queried + fingerprints := fingerprintMap[domainNode.Domain] + for _, fp := range fingerprints { + // add certnode to graph + certNode, exists := certGraph.GetCert(fp) + if !exists { + // get cert details + certResult, err := results.QueryCert(fp) + if err != nil { + v("QueryCert", err) + continue + } + + certNode = certNodeFromCertResult(certResult) + certGraph.AddCert(certNode) + } + + certNode.AddFound(certDriver.GetName()) + domainNode.AddCertFingerprint(certNode.Fingerprint, certDriver.GetName()) + } + + // we dont process any other certificates returned, they will be collected + // when we process the related domains +} + +func printNode(domainNode *graph.DomainNode) { + if config.details { + fmt.Fprintln(os.Stdout, domainNode) + } else { + fmt.Fprintln(os.Stdout, domainNode.Domain) + } + if config.checkDNS && !domainNode.HasDNS { + // TODO print this in a better way + // TODO for debugging + realDomain, _ := dns.TLDPlus1(domainNode.Domain) + fmt.Fprintf(os.Stdout, "* Missing DNS for: %s\n", realDomain) + + } +} + +// certNodeFromCertResult convert certResult to certNode +func certNodeFromCertResult(certResult *driver.CertResult) *graph.CertNode { + certNode := &graph.CertNode{ + Fingerprint: certResult.Fingerprint, + Domains: certResult.Domains, + } + return certNode +} + +// generates metadata for the JSON output +// TODO map all config json +func generateGraphMetadata() map[string]interface{} { + data := make(map[string]interface{}) + data["version"] = version() + data["website"] = "https://lanrat.github.io/certgraph/" + data["scan_date"] = time.Now().UTC() + data["command"] = strings.Join(os.Args, " ") + options := make(map[string]interface{}) + options["parallel"] = config.parallel + options["driver"] = config.driver + options["ct_subdomains"] = config.includeCTSubdomains + options["ct_expired"] = config.includeCTExpired + options["sanscap"] = config.maxSANsSize + options["cdn"] = config.cdn + options["timeout"] = config.timeout + data["options"] = options + return data +} + +// returns the version string +func version() string { + return fmt.Sprintf("Git commit: %s [%s]", gitDate, gitHash) +} + +// cleanInput attempts to parse the input string as a url to extract the hostname +// if it fails, then the input string is returned +// also removes tailing '.' +func cleanInput(host string) string { + host = strings.TrimSuffix(host, ".") + u, err := url.Parse(host) + if err != nil { + return host + } + hostname := u.Hostname() + if hostname == "" { + return host + } + return hostname +} diff --git a/dns/ns.go b/dns/ns.go new file mode 100644 index 0000000..5cd2635 --- /dev/null +++ b/dns/ns.go @@ -0,0 +1,87 @@ +package dns + +import ( + "context" + "net" + "time" +) + +var ( + dnsCache = make(map[string]bool) + dnsResolver = &net.Resolver{} +) + +func init() { + //dnsResolver.PreferGo = true + dnsResolver.StrictErrors = false +} + +func noSuchHostDNSError(err error) bool { + dnsErr, ok := err.(*net.DNSError) + if !ok { + // not a DNSError + return false + } + return dnsErr.Err == "no such host" +} + +// HasRecords does NS, CNAME, A, and AAAA lookups with a timeout +// returns error when no NS found, does not use TLDPlus1 +func HasRecords(domain string, timeout time.Duration) (bool, error) { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + + // first check for NS + ns, err := dnsResolver.LookupNS(ctx, domain) + if err != nil && !noSuchHostDNSError(err) { + //fmt.Println("NS error ", err) + return false, err + } + if len(ns) > 0 { + //fmt.Printf("Found %d NS for %s\n", len(ns), domain) + return true, nil + } + + // next check for CNAME + cname, err := dnsResolver.LookupCNAME(ctx, domain) + if err != nil && !noSuchHostDNSError(err) { + //fmt.Println("cname error ", err) + return false, err + } + if len(cname) > 2 { + //fmt.Printf("found CNAME %s for %s\n", cname, domain) + return true, nil + } + + // next check for IP + addrs, err := dnsResolver.LookupHost(ctx, domain) + if err != nil && !noSuchHostDNSError(err) { + //fmt.Println("ip error ", err) + return false, err + } + if len(addrs) > 0 { + //fmt.Printf("Found %d IPs for %s\n", len(addrs), domain) + return true, nil + } + + //fmt.Printf("Found no DNS records for %s\n", domain) + return false, nil +} + +// HasRecordsCache returns true if the domain has no DNS records (at the tldplus1 level) +// uses a cache to store results to prevent lots of DNS lookups +func HasRecordsCache(domain string, timeout time.Duration) (bool, error) { + domain, err := TLDPlus1(domain) + if err != nil { + return false, err + } + hasDNS, found := dnsCache[domain] + if found { + return hasDNS, nil + } + hasRecords, err := HasRecords(domain, timeout) + if err != nil { + dnsCache[domain] = hasRecords + } + return hasRecords, err +} diff --git a/dns/publicsuffix.go b/dns/publicsuffix.go new file mode 100644 index 0000000..86c9ef3 --- /dev/null +++ b/dns/publicsuffix.go @@ -0,0 +1,42 @@ +package dns + +import ( + "net/http" + "time" + + "github.com/weppos/publicsuffix-go/publicsuffix" +) + +var ( + suffixListFindOptions = &publicsuffix.FindOptions{ + IgnorePrivate: true, + DefaultRule: publicsuffix.DefaultRule, + } + suffixListURL = "https://publicsuffix.org/list/public_suffix_list.dat" + suffixList = publicsuffix.DefaultList + nsCache = make(map[string]bool) +) + +// UpdatePublicSuffixList gets a new copy of the public suffix list from the internat and updates the built in copy with the new rules +func UpdatePublicSuffixList(timeout time.Duration) error { + suffixListParseOptions := &publicsuffix.ParserOption{ + PrivateDomains: !suffixListFindOptions.IgnorePrivate, + } + client := http.Client{ + Timeout: timeout, + } + resp, err := client.Get(suffixListURL) + if err != nil { + return err + } + defer resp.Body.Close() + newSuffixList := publicsuffix.NewList() + newSuffixList.Load(resp.Body, suffixListParseOptions) + suffixList = newSuffixList + return err +} + +// TLDPlus1 returns TLD+1 of domain +func TLDPlus1(domain string) (string, error) { + return publicsuffix.DomainFromListWithOptions(suffixList, domain, suffixListFindOptions) +} diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 0000000..c227b54 --- /dev/null +++ b/docs/index.html @@ -0,0 +1,523 @@ + + + + + + +CertGraph + + + + + +
+ + + +
+
+

Graph

+ +
+
+ +
+ +
+
Info
+
+
+
+ + +
+
+ + + + + + + + + + + + +
#DomainStatusLookup
+ +
+
+ + + + + + + + + + + +
#HashLookup
+ +
+ +
+ + + + + + + + + + + + +
+ + + + + + diff --git a/driver/crtsh/crtsh.go b/driver/crtsh/crtsh.go new file mode 100644 index 0000000..b53c038 --- /dev/null +++ b/driver/crtsh/crtsh.go @@ -0,0 +1,221 @@ +package crtsh + +/* + * This file implements an unofficial API client for Comodo's + * Certificate Transparency search + * https://crt.sh/ + * + * As the API is unofficial and has been reverse engineered it may stop working + * at any time and comes with no guarantees. + */ + +// TODO running in verbose gives error: pq: unnamed prepared statement does not exist + +import ( + "database/sql" + "fmt" + "path" + "time" + + "github.com/lanrat/certgraph/driver" + "github.com/lanrat/certgraph/fingerprint" + "github.com/lanrat/certgraph/status" + _ "github.com/lib/pq" // portgresql +) + +const connStr = "postgresql://guest@crt.sh/certwatch?sslmode=disable" +const driverName = "crtsh" + +func init() { + driver.AddDriver(driverName) +} + +type crtsh struct { + db *sql.DB + queryLimit int + timeout time.Duration + save bool + savePath string + includeSubdomains bool + includeExpired bool +} + +type crtshCertDriver struct { + host string + fingerprints driver.FingerprintMap + driver *crtsh +} + +func (c *crtshCertDriver) GetFingerprints() (driver.FingerprintMap, error) { + return c.fingerprints, nil +} + +func (c *crtshCertDriver) GetStatus() status.Map { + return status.NewMap(c.host, status.New(status.CT)) +} + +func (c *crtshCertDriver) GetRelated() ([]string, error) { + return make([]string, 0), nil +} + +func (c *crtshCertDriver) QueryCert(fp fingerprint.Fingerprint) (*driver.CertResult, error) { + return c.driver.QueryCert(fp) +} + +// Driver creates a new CT driver for crt.sh +func Driver(maxQueryResults int, timeout time.Duration, savePath string, includeSubdomains, includeExpired bool) (driver.Driver, error) { + d := new(crtsh) + d.queryLimit = maxQueryResults + d.includeSubdomains = includeSubdomains + d.includeExpired = includeExpired + var err error + + if len(savePath) > 0 { + d.save = true + d.savePath = savePath + } + + d.db, err = sql.Open("postgres", connStr) + + d.setSQLTimeout(d.timeout.Seconds()) + + return d, err +} + +func (d *crtsh) GetName() string { + return driverName +} + +func (d *crtsh) setSQLTimeout(sec float64) error { + _, err := d.db.Exec(fmt.Sprintf("SET statement_timeout TO %f;", (1000 * sec))) + return err +} + +func (d *crtsh) QueryDomain(domain string) (driver.Result, error) { + results := &crtshCertDriver{ + host: domain, + fingerprints: make(driver.FingerprintMap), + driver: d, + } + + queryStr := "" + + if d.includeSubdomains { + if d.includeExpired { + queryStr = `SELECT digest(certificate.certificate, 'sha256') sha256 + FROM certificate_identity, certificate + WHERE certificate.id = certificate_identity.certificate_id + AND (reverse(lower(certificate_identity.name_value)) LIKE reverse(lower('%%.'||$1)) + OR reverse(lower(certificate_identity.name_value)) LIKE reverse(lower($1))) + LIMIT $2` + } else { + queryStr = `SELECT digest(certificate.certificate, 'sha256') sha256 + FROM certificate_identity, certificate + WHERE certificate.id = certificate_identity.certificate_id + AND x509_notAfter(certificate.certificate) > statement_timestamp() + AND (reverse(lower(certificate_identity.name_value)) LIKE reverse(lower('%%.'||$1)) + OR reverse(lower(certificate_identity.name_value)) LIKE reverse(lower($1))) + LIMIT $2` + } + } else { + if d.includeExpired { + queryStr = `SELECT digest(certificate.certificate, 'sha256') sha256 + FROM certificate_identity, certificate + WHERE certificate.id = certificate_identity.certificate_id + AND reverse(lower(certificate_identity.name_value)) LIKE reverse(lower($1)) + LIMIT $2` + } else { + queryStr = `SELECT digest(certificate.certificate, 'sha256') sha256 + FROM certificate_identity, certificate + WHERE certificate.id = certificate_identity.certificate_id + AND x509_notAfter(certificate.certificate) > statement_timestamp() + AND reverse(lower(certificate_identity.name_value)) LIKE reverse(lower($1)) + LIMIT $2` + } + } + + if d.includeSubdomains { + domain = fmt.Sprintf("%%.%s", domain) + } + + try := 0 + var err error + var rows *sql.Rows + for try < 5 { + // this is a hack while crt.sh gets there stuff togeather + try++ + rows, err = d.db.Query(queryStr, domain, d.queryLimit) + if err == nil { + break + } + } + /*if try > 1 { + fmt.Println("QueryDomain try ", try) + }*/ + if err != nil { + return results, err + } + + for rows.Next() { + var hash []byte + err = rows.Scan(&hash) + if err != nil { + return results, err + } + results.fingerprints.Add(domain, fingerprint.FromHashBytes(hash)) + } + + return results, nil +} + +func (d *crtsh) QueryCert(fp fingerprint.Fingerprint) (*driver.CertResult, error) { + certNode := new(driver.CertResult) + certNode.Fingerprint = fp + certNode.Domains = make([]string, 0, 5) + + queryStr := `SELECT DISTINCT certificate_identity.name_value + FROM certificate, certificate_identity + WHERE certificate.id = certificate_identity.certificate_id + AND certificate_identity.name_type in ('dNSName', 'commonName') + AND digest(certificate.certificate, 'sha256') = $1` + + try := 0 + var err error + var rows *sql.Rows + for try < 5 { + // this is a hack while crt.sh gets there stuff togeather + try++ + rows, err = d.db.Query(queryStr, fp[:]) + if err == nil { + break + } + } + /*if try > 1 { + fmt.Println("QueryCert try ", try) + }*/ + if err != nil { + return certNode, err + } + + for rows.Next() { + var domain string + rows.Scan(&domain) + certNode.Domains = append(certNode.Domains, domain) + } + + if d.save { + var rawCert []byte + queryStr = `SELECT certificate.certificate + FROM certificate + WHERE digest(certificate.certificate, 'sha256') = $1` + row := d.db.QueryRow(queryStr, fp[:]) + err = row.Scan(&rawCert) + if err != nil { + return certNode, err + } + + driver.RawCertToPEMFile(rawCert, path.Join(d.savePath, fp.HexString())+".pem") + } + + return certNode, nil +} diff --git a/driver/driver.go b/driver/driver.go new file mode 100644 index 0000000..5b4c819 --- /dev/null +++ b/driver/driver.go @@ -0,0 +1,91 @@ +package driver + +import ( + "crypto/x509" + "sort" + "strings" + + "github.com/lanrat/certgraph/fingerprint" + "github.com/lanrat/certgraph/status" +) + +// Drivers contains all the drivers that have been registered +var Drivers []string + +// AddDriver should be called in the init() function of every driver to register them here +func AddDriver(name string) { + Drivers = append(Drivers, name) +} + +// Driver is a universal unifying interface to support CT, http and much more! +type Driver interface { + // QueryDomain is the main entrypoint for Driver Searching + // The domain provided will return a CertDriver instance which can be used to query the + // certificates for the provided domain using the driver + QueryDomain(domain string) (Result, error) + + // GetName returns the name of the driver + GetName() string +} + +// Result is a sub-driver that allows querying certificate details from a previously queried domain +type Result interface { + // GetStatus returns the status of the initial domain queried with the Driver.QueryDomain call + GetStatus() status.Map + + // returns a list of additional related domains discovered while looking up the provided domain + GetRelated() ([]string, error) + + // GetFingerprints returns an array of the certificate fingerprints associated with the Domain + // pass return fingerprints to QueryCert to get certificate details + GetFingerprints() (FingerprintMap, error) + + // QueryCert returns the details of the provided certificate or an error if not found + QueryCert(fp fingerprint.Fingerprint) (*CertResult, error) +} + +// FingerprintMap stores a mapping of domains to Fingerprints returned from the driver +// in the case where multiple domains where queries (redirects, related, etc..) the +// matching certificates will be in this map +// the fingerprints returned are guaranteed to be a complete result for the domain's certs, but related domains may or may not be complete +type FingerprintMap map[string][]fingerprint.Fingerprint + +// Add adds a domain and fingerprint to the map +func (f FingerprintMap) Add(domain string, fp fingerprint.Fingerprint) { + f[domain] = append(f[domain], fp) +} + +// CertResult is an object to hold the fingerprint and Domains for a returned certificate +type CertResult struct { + Fingerprint fingerprint.Fingerprint + Domains []string +} + +// NewCertResult creates a new CertResult struct from an x509 cert +func NewCertResult(cert *x509.Certificate) *CertResult { + certResult := new(CertResult) + + // generate Fingerprint + certResult.Fingerprint = fingerprint.FromBytes(cert.Raw) + + // domains + // used to ensure uniq entries in domains array + domainMap := make(map[string]bool) + // add the CommonName just to be safe + cn := strings.ToLower(cert.Subject.CommonName) + if len(cn) > 0 { + domainMap[cn] = true + } + for _, domain := range cert.DNSNames { + if len(domain) > 0 { + domain = strings.ToLower(domain) + domainMap[domain] = true + } + } + for domain := range domainMap { + certResult.Domains = append(certResult.Domains, domain) + } + sort.Strings(certResult.Domains) + + return certResult +} diff --git a/driver/example.go b/driver/example.go new file mode 100644 index 0000000..3440ddc --- /dev/null +++ b/driver/example.go @@ -0,0 +1,41 @@ +package driver + +import "fmt" + +// Example provides a simple entrypoint to test a driver on an individual domain +func Example(domain string, driver Driver) error { + certDriver, err := driver.QueryDomain(domain) + if err != nil { + return err + } + + relatedDomains, err := certDriver.GetRelated() + if err != nil { + return err + } + if len(relatedDomains) > 0 { + fmt.Printf("Related:\n") + } + for _, relatedDomain := range relatedDomains { + fmt.Printf("\t%s\n", relatedDomain) + } + + fingerprintMap, err := certDriver.GetFingerprints() + if err != nil { + return err + } + for domain, fingerprints := range fingerprintMap { + for i := range fingerprints { + fmt.Printf("%s: %s\n", domain, fingerprints[i].HexString()) + cert, err := certDriver.QueryCert(fingerprints[i]) + if err != nil { + return err + } + for j := range cert.Domains { + fmt.Println("\t", cert.Domains[j]) + } + } + } + + return nil +} diff --git a/driver/google/google.go b/driver/google/google.go new file mode 100644 index 0000000..321e421 --- /dev/null +++ b/driver/google/google.go @@ -0,0 +1,224 @@ +package google + +/* + * This file implements an unofficial API client for Google's + * Certificate Transparency search + * https://transparencyreport.google.com/https/certificates + * + * As the API is unofficial and has been reverse engineered it may stop working + * at any time and comes with no guarantees. + */ + +import ( + "encoding/json" + "errors" + "io/ioutil" + "net/http" + "net/url" + "strconv" + "time" + + "github.com/lanrat/certgraph/driver" + "github.com/lanrat/certgraph/fingerprint" + "github.com/lanrat/certgraph/status" +) + +const driverName = "google" + +func init() { + driver.AddDriver(driverName) +} + +// Base URLs for Google's CT API +const searchURL1 = "https://transparencyreport.google.com/transparencyreport/api/v3/httpsreport/ct/certsearch?include_expired=false&include_subdomains=false&domain=example.com" +const searchURL2 = "https://transparencyreport.google.com/transparencyreport/api/v3/httpsreport/ct/certsearch/page?p=DEADBEEF" +const certURL = "https://transparencyreport.google.com/transparencyreport/api/v3/httpsreport/ct/certbyhash?hash=DEADBEEF" + +type googleCT struct { + maxPages float64 // this is a float because that is the type automatically decoded from the JSON response + jsonClient *http.Client + includeExpired bool + includeSubdomains bool +} + +type googleCertDriver struct { + host string + fingerprints driver.FingerprintMap + driver *googleCT +} + +func (c *googleCertDriver) GetFingerprints() (driver.FingerprintMap, error) { + return c.fingerprints, nil +} + +func (c *googleCertDriver) GetStatus() status.Map { + return status.NewMap(c.host, status.New(status.CT)) +} + +func (c *googleCertDriver) GetRelated() ([]string, error) { + return make([]string, 0), nil +} + +func (c *googleCertDriver) QueryCert(fp fingerprint.Fingerprint) (*driver.CertResult, error) { + return c.driver.QueryCert(fp) +} + +// Driver creates a new CT driver for google +func Driver(maxQueryPages int, savePath string, includeSubdomains, includeExpired bool) (driver.Driver, error) { + d := new(googleCT) + d.maxPages = float64(maxQueryPages) + d.jsonClient = &http.Client{Timeout: 10 * time.Second} + d.includeExpired = includeExpired + d.includeSubdomains = includeSubdomains + + if len(savePath) > 0 { + return d, errors.New("google driver does not support saving") + + } + + return d, nil +} + +func (d *googleCT) GetName() string { + return driverName +} + +// getJsonP gets JSON from url and parses it into target object +func (d *googleCT) getJSONP(url string, target interface{}) error { + r, err := d.jsonClient.Get(url) + if err != nil { + return err + } + defer r.Body.Close() + if r.StatusCode != http.StatusOK { + return errors.New("Got non OK HTTP status: '" + r.Status + "' on URL: " + url) + } + + respData, err := ioutil.ReadAll(r.Body) + if err != nil { + return err + } + + respData = respData[5:] // this removes the leading ")]}'" from the response + + return json.Unmarshal(respData, target) +} + +func (d *googleCT) QueryDomain(domain string) (driver.Result, error) { + results := &googleCertDriver{ + fingerprints: make(driver.FingerprintMap), + driver: d, + host: domain, + } + + u, err := url.Parse(searchURL1) + if err != nil { + return results, err + } + + // get page 1 + q := u.Query() + q.Set("include_expired", strconv.FormatBool(d.includeExpired)) + q.Set("include_subdomains", strconv.FormatBool(d.includeSubdomains)) + q.Set("domain", domain) + u.RawQuery = q.Encode() + + var raw [][]interface{} + nextURL := u.String() + currentPage := float64(1) + + // TODO allow for selective pagination + + // iterate over results + for len(nextURL) > 1 && currentPage <= d.maxPages { + err = d.getJSONP(nextURL, &raw) + if err != nil { + return results, err + } + + // simple corectness checks + if raw[0][0] != "https.ct.cdsr" { + return results, errors.New("Got Unexpected Query output: " + raw[0][0].(string)) + } + if len(raw[0]) != 4 { + // result not correct length, likely no results + //fmt.Println(raw[0]) + break + } + if len(raw[0][3].([]interface{})) != 5 { + // pageinfo result not correct length, likely no results + //fmt.Println(raw[0]) + break + } + + // pageInfo: [prevToken, nextToken, ? currentPage, totalPages] + pageInfo := raw[0][3].([]interface{}) + currentPage = pageInfo[3].(float64) + + foundCerts := raw[0][1].([]interface{}) + for _, foundCert := range foundCerts { + certHash := foundCert.([]interface{})[5].(string) + certFP := fingerprint.FromB64(certHash) + results.fingerprints.Add(domain, certFP) + } + //fmt.Println("Page:", pageInfo[3]) + + // create url or next page + nextURL = "" + if pageInfo[1] != nil { + u, err := url.Parse(searchURL2) + if err != nil { + return results, err + } + + // get page n + q := u.Query() + q.Set("p", pageInfo[1].(string)) + u.RawQuery = q.Encode() + nextURL = u.String() + } + } + + return results, nil +} + +func (d *googleCT) QueryCert(fp fingerprint.Fingerprint) (*driver.CertResult, error) { + certNode := new(driver.CertResult) + certNode.Fingerprint = fp + certNode.Domains = make([]string, 0, 5) + + u, err := url.Parse(certURL) + if err != nil { + return certNode, err + } + + q := u.Query() + q.Set("hash", fp.B64Encode()) + u.RawQuery = q.Encode() + + var raw [][]interface{} + + err = d.getJSONP(u.String(), &raw) + if err != nil { + return certNode, err + } + + // simple corectness checks + if raw[0][0] != "https.ct.chr" { + return certNode, errors.New("Got Unexpected Cert output: " + raw[0][0].(string)) + } + if len(raw[0]) != 3 { + // result not correct length, likely no results + //fmt.Println(raw[0]) + return certNode, errors.New("Cert Does not exist! output: " + raw[0][0].(string)) + } + + certInfo := raw[0][1].([]interface{}) + domains := certInfo[7].([]interface{}) + + for _, domain := range domains { + certNode.Domains = append(certNode.Domains, domain.(string)) + } + + return certNode, nil +} diff --git a/driver/http/http.go b/driver/http/http.go new file mode 100644 index 0000000..591f566 --- /dev/null +++ b/driver/http/http.go @@ -0,0 +1,158 @@ +package http + +import ( + "crypto/tls" + "fmt" + "net" + "net/http" + "path" + "time" + + "github.com/lanrat/certgraph/driver" + "github.com/lanrat/certgraph/fingerprint" + "github.com/lanrat/certgraph/status" +) + +const driverName = "http" + +func init() { + driver.AddDriver(driverName) +} + +type httpDriver struct { + port string + save bool + savePath string + tlsConfig *tls.Config + timeout time.Duration +} + +type httpCertDriver struct { + parent *httpDriver + client *http.Client + fingerprints driver.FingerprintMap + status status.Map + related []string + certs map[fingerprint.Fingerprint]*driver.CertResult +} + +func (c *httpCertDriver) GetFingerprints() (driver.FingerprintMap, error) { + return c.fingerprints, nil +} + +func (c *httpCertDriver) GetStatus() status.Map { + return c.status +} + +func (c *httpCertDriver) GetRelated() ([]string, error) { + return c.related, nil +} + +func (c *httpCertDriver) QueryCert(fp fingerprint.Fingerprint) (*driver.CertResult, error) { + cert, found := c.certs[fp] + if found { + return cert, nil + } + return nil, fmt.Errorf("Certificate with Fingerprint %s not found", fp.HexString()) +} + +// Driver creates a new SSL driver for HTTP Connections +func Driver(timeout time.Duration, savePath string) (driver.Driver, error) { + d := new(httpDriver) + d.port = "443" + if len(savePath) > 0 { + d.save = true + d.savePath = savePath + } + d.timeout = timeout + d.tlsConfig = &tls.Config{ + InsecureSkipVerify: true, + } + + return d, nil +} + +func (d *httpDriver) GetName() string { + return driverName +} + +func (d *httpDriver) newHTTPCertDriver() *httpCertDriver { + result := &httpCertDriver{ + parent: d, + status: make(status.Map), + fingerprints: make(driver.FingerprintMap), + certs: make(map[fingerprint.Fingerprint]*driver.CertResult), + } + // set client & client.Transport separately so that dialTLS checkRedirect can be referenced + result.client = &http.Client{ + Timeout: d.timeout, + CheckRedirect: result.checkRedirect, + } + result.client.Transport = &http.Transport{ + TLSClientConfig: d.tlsConfig, + TLSHandshakeTimeout: d.timeout, + ResponseHeaderTimeout: d.timeout, + ExpectContinueTimeout: d.timeout, + DialTLS: result.dialTLS, + } + return result +} + +// GetCert gets the certificates found for a given domain +func (d *httpDriver) QueryDomain(host string) (driver.Result, error) { + results := d.newHTTPCertDriver() + + resp, err := results.client.Get(fmt.Sprintf("https://%s", host)) + fullStatus := status.CheckNetErr(err) + if fullStatus != status.GOOD { + return results, err // in some rare cases this error can be ignored + } + defer resp.Body.Close() + + // set final domain status + results.status.Set(resp.Request.URL.Hostname(), status.New(status.GOOD)) + // no need to add certificate to c.certs and c.fingerprints here, handled in dialTLS method + return results, nil +} + +// only called after a redirect is detected +// req has the next request to send, via has the last requests +// not called for the first HTTP request that replied with the initial redirect +func (c *httpCertDriver) checkRedirect(req *http.Request, via []*http.Request) error { + //fmt.Printf("Redirect %s -> %s\n", via[0].URL, req.URL) + // set both domain's status's + c.status.Set(via[0].URL.Hostname(), status.NewMeta(status.REDIRECT, req.URL.Hostname())) + c.status.Set(req.URL.Hostname(), status.New(status.UNKNOWN)) + c.related = append(c.related, req.URL.Hostname()) + if len(via) >= 10 { // stop after 10 redirects + // this stops the redirect + return http.ErrUseLastResponse + } + return nil +} + +func (c *httpCertDriver) dialTLS(network, addr string) (net.Conn, error) { + dialer := &net.Dialer{Timeout: c.client.Timeout} + conn, err := tls.DialWithDialer(dialer, network, addr, c.parent.tlsConfig) + if conn == nil { + return conn, err + } + // get certs passing by + connState := conn.ConnectionState() + + // only look at leaf certificate which is valid for domain, rest of cert chain is ignored + certResult := driver.NewCertResult(connState.PeerCertificates[0]) + c.certs[certResult.Fingerprint] = certResult + host, _, err := net.SplitHostPort(addr) + if err != nil { + return conn, err + } + c.fingerprints.Add(host, certResult.Fingerprint) + + // save + if c.parent.save && len(connState.PeerCertificates) > 0 { + driver.CertsToPEMFile(connState.PeerCertificates, path.Join(c.parent.savePath, certResult.Fingerprint.HexString())+".pem") + } + + return conn, err +} diff --git a/driver/save.go b/driver/save.go new file mode 100644 index 0000000..e968aca --- /dev/null +++ b/driver/save.go @@ -0,0 +1,45 @@ +package driver + +import ( + "crypto/x509" + "encoding/pem" + "os" +) + +// CertsToPEMFile saves certificates to local pem file +func CertsToPEMFile(certs []*x509.Certificate, file string) error { + if fileExists(file) { + return nil + } + f, err := os.Create(file) + if err != nil { + return err + } + defer f.Close() + for _, cert := range certs { + pem.Encode(f, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}) + } + return nil +} + +// RawCertToPEMFile saves raw certificate to local pem file +func RawCertToPEMFile(cert []byte, file string) error { + if fileExists(file) { + return nil + } + f, err := os.Create(file) + if err != nil { + return err + } + defer f.Close() + pem.Encode(f, &pem.Block{Type: "CERTIFICATE", Bytes: cert}) + return nil +} + +func fileExists(f string) bool { + _, err := os.Stat(f) + if os.IsNotExist(err) { + return false + } + return err == nil +} diff --git a/driver/smtp/smtp.go b/driver/smtp/smtp.go new file mode 100644 index 0000000..3e6ed32 --- /dev/null +++ b/driver/smtp/smtp.go @@ -0,0 +1,156 @@ +package smtp + +import ( + "context" + "crypto/tls" + "crypto/x509" + "fmt" + "net" + "net/smtp" + "path" + "strings" + "time" + + "github.com/lanrat/certgraph/driver" + "github.com/lanrat/certgraph/fingerprint" + "github.com/lanrat/certgraph/status" +) + +const driverName = "smtp" + +func init() { + driver.AddDriver(driverName) +} + +type smtpDriver struct { + port string + save bool + savePath string + tlsConfig *tls.Config + timeout time.Duration +} + +type smtpCertDriver struct { + host string + fingerprints driver.FingerprintMap + status status.Map + mx []string + certs map[fingerprint.Fingerprint]*driver.CertResult +} + +func (c *smtpCertDriver) GetFingerprints() (driver.FingerprintMap, error) { + return c.fingerprints, nil +} + +func (c *smtpCertDriver) GetStatus() status.Map { + return c.status +} + +func (c *smtpCertDriver) GetRelated() ([]string, error) { + return c.mx, nil +} + +func (c *smtpCertDriver) QueryCert(fp fingerprint.Fingerprint) (*driver.CertResult, error) { + cert, found := c.certs[fp] + if found { + return cert, nil + } + return nil, fmt.Errorf("Certificate with Fingerprint %s not found", fp.HexString()) +} + +// Driver creates a new SSL driver for SMTP Connections +func Driver(timeout time.Duration, savePath string) (driver.Driver, error) { + d := new(smtpDriver) + d.port = "25" + if len(savePath) > 0 { + d.save = true + d.savePath = savePath + } + d.tlsConfig = &tls.Config{ + InsecureSkipVerify: true, + } + d.timeout = timeout + + return d, nil +} + +func (d *smtpDriver) GetName() string { + return driverName +} + +func (d *smtpDriver) smtpGetCerts(host string) ([]*x509.Certificate, error) { + var certs []*x509.Certificate + addr := net.JoinHostPort(host, d.port) + dialer := &net.Dialer{Timeout: d.timeout} + + conn, err := dialer.Dial("tcp", addr) + if err != nil { + return certs, err + } + defer conn.Close() + smtp, err := smtp.NewClient(conn, host) + if err != nil { + return certs, err + } + err = smtp.StartTLS(d.tlsConfig) + if err != nil { + return certs, err + } + connState, ok := smtp.TLSConnectionState() + if !ok { + return certs, err + } + return connState.PeerCertificates, err +} + +// QueryDomain gets the certificates found for a given domain +func (d *smtpDriver) QueryDomain(host string) (driver.Result, error) { + results := &smtpCertDriver{ + host: host, + status: make(status.Map), + fingerprints: make(driver.FingerprintMap), + certs: make(map[fingerprint.Fingerprint]*driver.CertResult), + } + + // get related in different query + results.mx, _ = d.getMX(host) + + certs, err := d.smtpGetCerts(host) + smtpStatus := status.CheckNetErr(err) + metaStatus := "" + if len(results.mx) > 0 { + metaStatus = fmt.Sprintf("MX(%s)", strings.Join(results.mx, " ")) + } + results.status.Set(host, status.NewMeta(smtpStatus, metaStatus)) + + if smtpStatus != status.GOOD { + return results, nil + } + + // only look at leaf certificate which is valid for domain, rest of cert chain is ignored + certResult := driver.NewCertResult(certs[0]) + results.certs[certResult.Fingerprint] = certResult + results.fingerprints.Add(host, certResult.Fingerprint) + + // save + if d.save && len(certs) > 0 { + driver.CertsToPEMFile(certs, path.Join(d.savePath, certResult.Fingerprint.HexString())+".pem") + } + + return results, nil +} + +// getMX returns the MX records for the provided domain +func (d *smtpDriver) getMX(domain string) ([]string, error) { + domains := make([]string, 0, 5) + ctx, cancel := context.WithTimeout(context.Background(), d.timeout) + defer cancel() + mx, err := net.DefaultResolver.LookupMX(ctx, domain) + if err != nil { + return domains, err + } + for _, v := range mx { + domains = append(domains, strings.TrimSuffix(v.Host, ".")) + } + return domains, nil +} diff --git a/fingerprint/fingerprint.go b/fingerprint/fingerprint.go new file mode 100644 index 0000000..3bab154 --- /dev/null +++ b/fingerprint/fingerprint.go @@ -0,0 +1,48 @@ +package fingerprint + +import ( + "crypto/sha256" + "encoding/base64" + "fmt" +) + +// Fingerprint sha256 of certificate bytes +type Fingerprint [sha256.Size]byte + +// HexString print Fingerprint as hex +func (fp *Fingerprint) HexString() string { + return fmt.Sprintf("%X", *fp) +} + +// FromHashBytes returns a Fingerprint generated by the first len(Fingerprint) bytes +func FromHashBytes(data []byte) Fingerprint { + var fp Fingerprint + /*if len(data) != sha256.Size { + v("Data is not correct SHA256 size", data) + }*/ + for i := 0; i < len(data) && i < len(fp); i++ { + fp[i] = data[i] + } + return fp +} + +// FromBytes returns a Fingerprint generated by the provided bytes +func FromBytes(data []byte) Fingerprint { + var fp Fingerprint + fp = sha256.Sum256(data) + return fp +} + +// FromB64 returns a Fingerprint from a base64 encoded hash string +func FromB64(hash string) Fingerprint { + data, _ := base64.StdEncoding.DecodeString(hash) + /*if err != nil { + fmt.Println(err) + }*/ + return FromHashBytes(data) +} + +// B64Encode returns the b64 string of a Fingerprint +func (fp *Fingerprint) B64Encode() string { + return base64.StdEncoding.EncodeToString(fp[:]) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..fff6d4e --- /dev/null +++ b/go.mod @@ -0,0 +1,8 @@ +module github.com/lanrat/certgraph + +require ( + github.com/lib/pq v1.0.0 + github.com/weppos/publicsuffix-go v0.4.0 + golang.org/x/net v0.0.0-20180906233101-161cd47e91fd // indirect + golang.org/x/text v0.3.0 // indirect +) diff --git a/graph/cert_node.go b/graph/cert_node.go new file mode 100644 index 0000000..13c145e --- /dev/null +++ b/graph/cert_node.go @@ -0,0 +1,80 @@ +package graph + +import ( + "fmt" + "strings" + + "github.com/lanrat/certgraph/dns" + "github.com/lanrat/certgraph/fingerprint" +) + +// CertNode graph node to store certificate information +type CertNode struct { + Fingerprint fingerprint.Fingerprint + Domains []string + foundMap map[string]bool +} + +func (c *CertNode) String() string { + return fmt.Sprintf("%s\t%s\t%v", c.Fingerprint.HexString(), c.Found(), c.Domains) +} + +// Found returns a list of drivers that found this cert +func (c *CertNode) Found() []string { + found := make([]string, 0, len(c.foundMap)) + for i := range c.foundMap { + found = append(found, i) + } + return found +} + +// AddFound adds a driver name to the source of the certificate +func (c *CertNode) AddFound(driver string) { + if c.foundMap == nil { + c.foundMap = make(map[string]bool) + } + c.foundMap[driver] = true +} + +// CDNCert returns true if we think the certificate belongs to a CDN +// very weak detection, only supports fastly & cloudflare +func (c *CertNode) CDNCert() bool { + for _, domain := range c.Domains { + // cloudflare + if strings.HasSuffix(domain, ".cloudflaressl.com") { + return true + } + // fastly + if strings.HasSuffix(domain, "fastly.net") { + return true + } + // akamai + if strings.HasSuffix(domain, ".akamai.net") { + return true + } + + } + return false +} + +// TLDPlus1Count the number of tld+1 domains in the certificate +func (c *CertNode) TLDPlus1Count() int { + tldPlus1Domains := make(map[string]bool) + for _, domain := range c.Domains { + tldPlus1, err := dns.TLDPlus1(domain) + if err != nil { + continue + } + tldPlus1Domains[tldPlus1] = true + } + return len(tldPlus1Domains) +} + +// ToMap returns a map of the CertNode's fields (weak serialization) +func (c *CertNode) ToMap() map[string]string { + m := make(map[string]string) + m["type"] = "certificate" + m["id"] = c.Fingerprint.HexString() + m["found"] = strings.Join(c.Found(), " ") + return m +} diff --git a/graph/domain_node.go b/graph/domain_node.go new file mode 100644 index 0000000..b18d589 --- /dev/null +++ b/graph/domain_node.go @@ -0,0 +1,111 @@ +package graph + +import ( + "fmt" + "strconv" + "strings" + "time" + + "github.com/lanrat/certgraph/dns" + "github.com/lanrat/certgraph/fingerprint" + "github.com/lanrat/certgraph/status" +) + +// DomainNode structure to store a domain and its edges +type DomainNode struct { + Domain string + Depth uint + Certs map[fingerprint.Fingerprint][]string + RelatedDomains status.Map + Status status.Status + Root bool + HasDNS bool +} + +// NewDomainNode constructor for DomainNode, converts domain to nonWildcard +func NewDomainNode(domain string, depth uint) *DomainNode { + domainNode := new(DomainNode) + domainNode.Domain = nonWildcard(domain) + domainNode.Depth = depth + domainNode.Certs = make(map[fingerprint.Fingerprint][]string) + domainNode.RelatedDomains = make(status.Map) + return domainNode +} + +// AddRelatedDomains adds the domains in the provided array to the domainNode's +// related domains status map with an unknown status if they are not already +// in the map +func (d *DomainNode) AddRelatedDomains(domains []string) { + for _, domain := range domains { + if _, ok := d.RelatedDomains[domain]; ok { + continue + } + d.RelatedDomains[domain] = status.New(status.UNKNOWN) + } +} + +// CheckForDNS checks for the existence of DNS records for the domain's tld+1 +// sets the value to the node and returns the result as well +func (d *DomainNode) CheckForDNS(timeout time.Duration) (bool, error) { + hasDNS, err := dns.HasRecordsCache(d.Domain, timeout) + + d.HasDNS = hasDNS + return hasDNS, err +} + +// AddStatusMap adds the status' in the map to the DomainNode +// also sets the Node's own status if it is in the Map +// side effect: will delete its own status from the provided map +func (d *DomainNode) AddStatusMap(m status.Map) { + if status, ok := m[d.Domain]; ok { + d.Status = status + delete(m, d.Domain) + } + for domain, status := range m { + d.RelatedDomains[domain] = status + } +} + +// GetCertificates returns a list of known certificate fingerprints for the domain +func (d *DomainNode) GetCertificates() []fingerprint.Fingerprint { + fingerprints := make([]fingerprint.Fingerprint, 0, len(d.Certs)) + for fingerprint := range d.Certs { + fingerprints = append(fingerprints, fingerprint) + } + return fingerprints +} + +// get the string representation of a node +func (d *DomainNode) String() string { + certString := "" + // Certs + if len(d.Certs) > 0 { + for fingerprint := range d.Certs { + certString = fmt.Sprintf("%s %s", certString, fingerprint.HexString()) + } + } + return fmt.Sprintf("%s\t%d\t%s\t%s", d.Domain, d.Depth, d.Status.String(), certString) +} + +// AddCertFingerprint appends a Fingerprint to the DomainNode's list of certificates +func (d *DomainNode) AddCertFingerprint(fp fingerprint.Fingerprint, certSource string) { + d.Certs[fp] = append(d.Certs[fp], certSource) +} + +// ToMap returns a map of the DomainNode's fields (weak serialization) +func (d *DomainNode) ToMap() map[string]string { + related := make([]string, 0, len(d.RelatedDomains)) + for domain := range d.RelatedDomains { + related = append(related, domain) + } + relatedString := strings.Join(related, " ") + m := make(map[string]string) + m["type"] = "domain" + m["id"] = d.Domain + m["status"] = d.Status.String() + m["root"] = strconv.FormatBool(d.Root) + m["depth"] = strconv.FormatUint(uint64(d.Depth), 10) + m["related"] = relatedString + m["hasDNS"] = strconv.FormatBool(d.HasDNS) + return m +} diff --git a/graph/graph.go b/graph/graph.go new file mode 100644 index 0000000..c519040 --- /dev/null +++ b/graph/graph.go @@ -0,0 +1,161 @@ +package graph + +import ( + "strings" + "sync" + + "github.com/lanrat/certgraph/fingerprint" +) + +// CertGraph main graph storage engine +type CertGraph struct { + domains sync.Map + certs sync.Map + numDomains int + depth uint +} + +// NewCertGraph instantiates a new empty CertGraph +func NewCertGraph() *CertGraph { + graph := new(CertGraph) + return graph +} + +// LoadOrStoreCert will return the CertNode in the graph with the provided node's fingerprint, or store the node if it did not already exist +// returned bool is true if the CertNode was found, false if stored +func (graph *CertGraph) LoadOrStoreCert(certNode *CertNode) (*CertNode, bool) { + foundCertNode, ok := graph.certs.LoadOrStore(certNode.Fingerprint, certNode) + return foundCertNode.(*CertNode), ok +} + +// AddCert add a CertNode to the graph +func (graph *CertGraph) AddCert(certNode *CertNode) { + // save the cert to the graph + // if it already exists we overwrite, it is simpler than checking first. + graph.certs.Store(certNode.Fingerprint, certNode) +} + +// AddDomain add a DomainNode to the graph +func (graph *CertGraph) AddDomain(domainNode *DomainNode) { + graph.numDomains++ + // save the new maximum depth if greather then current + if domainNode.Depth > graph.depth { + graph.depth = domainNode.Depth + } + // save the domain to the graph + // if it already exists we overwrite, it is simpler than checking first. + // graph.numDomains should still be accurate because we only call this after checking that we have not visited the node before. + graph.domains.Store(domainNode.Domain, domainNode) +} + +//NumDomains returns the number of domains in the graph +func (graph *CertGraph) NumDomains() int { + return graph.numDomains +} + +//DomainDepth returns the maximum depth of the graph from the initial root domains +func (graph *CertGraph) DomainDepth() uint { + return graph.depth +} + +// GetCert returns (CertNode, found) for the certificate with the provided Fingerprint in the graph if found +func (graph *CertGraph) GetCert(fp fingerprint.Fingerprint) (*CertNode, bool) { + node, ok := graph.certs.Load(fp) + if ok { + return node.(*CertNode), true + } + return nil, false +} + +// GetDomain returns (DomainNode, found) for the domain in the graph if found +func (graph *CertGraph) GetDomain(domain string) (*DomainNode, bool) { + node, ok := graph.domains.Load(domain) + if ok { + return node.(*DomainNode), true + } + return nil, false +} + +// GetDomainNeighbors given a domain, return the list of all other domains that share a certificate with the provided domain that are in the graph +// cdn will include CDN certs as well +func (graph *CertGraph) GetDomainNeighbors(domain string, cdn bool, maxSANsSize int) []string { + neighbors := make(map[string]bool) + + domain = nonWildcard(domain) + node, ok := graph.domains.Load(domain) + if ok { + domainNode := node.(*DomainNode) + // related cert neighbors + for relatedDomain := range domainNode.RelatedDomains { + neighbors[relatedDomain] = true + } + + // Cert neighbors + for _, fp := range domainNode.GetCertificates() { + node, ok := graph.certs.Load(fp) + if ok { + certNode := node.(*CertNode) + if !cdn && certNode.CDNCert() { + //v(domain, "-> CDN CERT") + } else if maxSANsSize > 0 && certNode.TLDPlus1Count() > maxSANsSize { + //v(domain, "-> Large CERT") + } else { + for _, neighbor := range certNode.Domains { + neighbors[neighbor] = true + //v(domain, "-- CT -->", neighbor) + } + } + } + } + } + + //exclude domain from own neighbors list + neighbors[domain] = false + + // convert map to array + neighborList := make([]string, 0, len(neighbors)) + for key := range neighbors { + if neighbors[key] { + neighborList = append(neighborList, key) + } + } + return neighborList +} + +// GenerateMap returns a map representation of the certificate graph +// used for JSON serialization +func (graph *CertGraph) GenerateMap() map[string]interface{} { + m := make(map[string]interface{}) + nodes := make([]map[string]string, 0, 2*graph.numDomains) + links := make([]map[string]string, 0, 2*graph.numDomains) + + // add all domain nodes + graph.domains.Range(func(key, value interface{}) bool { + domainNode := value.(*DomainNode) + nodes = append(nodes, domainNode.ToMap()) + for fingerprint, found := range domainNode.Certs { + links = append(links, map[string]string{"source": domainNode.Domain, "target": fingerprint.HexString(), "type": strings.Join(found, " ")}) + } + return true + }) + + // add all cert nodes + graph.certs.Range(func(key, value interface{}) bool { + certNode := value.(*CertNode) + nodes = append(nodes, certNode.ToMap()) + for _, domain := range certNode.Domains { + domain = nonWildcard(domain) + _, ok := graph.GetDomain(domain) + if ok { + links = append(links, map[string]string{"source": certNode.Fingerprint.HexString(), "target": domain, "type": "sans"}) + } + } + return true + }) + + m["nodes"] = nodes + m["links"] = links + m["depth"] = graph.depth + m["numDomains"] = graph.numDomains + return m +} diff --git a/graph/misc.go b/graph/misc.go new file mode 100644 index 0000000..fd25cc6 --- /dev/null +++ b/graph/misc.go @@ -0,0 +1,10 @@ +package graph + +import ( + "strings" +) + +// given a domain returns the non-wildcard version of that domain +func nonWildcard(domain string) string { + return strings.TrimPrefix(domain, "*.") +} diff --git a/status/status.go b/status/status.go new file mode 100644 index 0000000..12ec034 --- /dev/null +++ b/status/status.go @@ -0,0 +1,111 @@ +package status + +import ( + "fmt" + "net" + "syscall" +) + +// DomainStatus domain node connection status +type DomainStatus int + +// Status holds the domain status and optionally more information +// ex: redirects will have the redirected domain in Meta +type Status struct { + Status DomainStatus + Meta string +} + +// New returns a new Status object with the provided DomainStatus +func New(domainStatus DomainStatus) Status { + return Status{ + Status: domainStatus, + } +} + +// NewMeta returns a new Status with the provied meta +func NewMeta(domainStatus DomainStatus, meta string) Status { + s := New(domainStatus) + s.Meta = meta + return s +} + +func (s *Status) String() string { + if s.Meta == "" { + return s.Status.String() + } + return fmt.Sprintf("%s(%s)", s.Status.String(), s.Meta) +} + +// Map is a map of returned domains to their status +type Map map[string]Status + +// Set adds the domain and status to the StatusMap +func (m Map) Set(domain string, status Status) { + m[domain] = status +} + +// NewMap returns a new StatusMap containing the domain and status +func NewMap(domain string, status Status) Map { + m := make(Map) + m.Set(domain, status) + return m +} + +// DomainStatus states +const ( + UNKNOWN = iota + GOOD = iota + TIMEOUT = iota + NOHOST = iota + REFUSED = iota + ERROR = iota + REDIRECT = iota + CT = iota +) + +// return domain status for printing +func (status DomainStatus) String() string { + switch status { + case UNKNOWN: + return "Unknown" + case GOOD: + return "Good" + case TIMEOUT: + return "Timeout" + case NOHOST: + return "No Host" + case REFUSED: + return "Refused" + case ERROR: + return "Error" + case REDIRECT: + return "Redirect" + case CT: + return "CT" + } + return "?" +} + +// CheckNetErr check for errors, print if network related +func CheckNetErr(err error) DomainStatus { + if err == nil { + return GOOD + } else if netError, ok := err.(net.Error); ok && netError.Timeout() { + return TIMEOUT + } else { + switch t := err.(type) { + case *net.OpError: + if t.Op == "dial" { + return NOHOST + } else if t.Op == "read" { + return REFUSED + } + case syscall.Errno: + if t == syscall.ECONNREFUSED { + return REFUSED + } + } + } + return ERROR +}