-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
306 lines (287 loc) · 9.09 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package main
import (
"fmt"
"log"
"github.com/valyala/fasthttp"
"github.com/buaazp/fasthttprouter"
"encoding/json"
"html/template"
"github.com/likexian/whois-go"
"github.com/likexian/whois-parser-go"
"github.com/PuerkitoBio/goquery"
"strings"
"database/sql"
_ "github.com/lib/pq"
)
const Port = ":8080"
func main() {
fmt.Println("created by @samzapata")
// server connection router with fasthttprouter
router := fasthttprouter.New()
// load welcome index
path_index := "/"
router.GET(path_index, Index)
// endpoint I
path_fetch_domain := "/api/servers/v1/d=:domain"
router.GET(path_fetch_domain, GetServerInformation)
// endpoint II
path_domains := "/api/servers/v1/domains"
router.GET(path_domains, GetServers)
log.Fatal(fasthttp.ListenAndServe(Port, router.Handler))
}
// fasthttp request handler
func GetServerInformation(ctx *fasthttp.RequestCtx) {
// fetch data of server with the given domain
j := FetchServerData(ctx.UserValue("domain"))
fmt.Fprintf(ctx, j)
SaveDomain(ctx.UserValue("domain"))
}
// Build server
type Server struct {
Servers []Serverslice `json:"servers"`
Servers_changed bool `json:"servers_changed"`
Ssl_grade string `json:"ssl_grade"`
Previous_ssl_grade string `json:"previous_ssl_grade"`
Logo string `json:"logo"`
Title string `json:"title"`
Is_down bool `json:"is_down"`
}
// data per server
type Serverslice struct {
// Name string `json:"name"`
Address string `json:"address"`
Ssl_grade string `json:"ssl_grade"`
Country string `json:"country"`
Owner string `json:"owner"`
}
// structs to scrape ssl data
type SslServer struct {
Address, Sslgrade string
}
type SslAnalysis struct {
Sslservers []SslServer
}
func FetchServerData(domain interface{}) string {
// scraping
fmt.Println("===Start Scrape Domain===")
server_scraped := ScrapeServer(domain.(string))
fmt.Println("===Finish Scrape Domain===")
fmt.Println("===Start Scrape SSL===")
ssl_scraped := ScrapeSSL(domain.(string))
fmt.Println(ssl_scraped)
fmt.Println("===Finish Scrape SSL===")
res := fasthttp.AcquireResponse()
// variables to build server
var server Server
var serverslice Serverslice
host, _ := whois.Whois(domain.(string))
h, err_dom := whoisparser.Parse(host)
var servers = h.Domain.NameServers
// compare the servers detected with the addresses given from SSL-Labs
if len(ssl_scraped.Sslservers) == len(servers) {
for i, v := range ssl_scraped.Sslservers {
fmt.Printf("==== server %d =====\n", i )
fmt.Println(v)
serverslice.Address = v.Address
serverslice.Ssl_grade = v.Sslgrade
serverslice.Country = h.Registrant.Country
serverslice.Owner = h.Registrant.Organization
fmt.Println("--------------------")
server.Servers = append(server.Servers, Serverslice(serverslice))
}
} else {
for i, v := range servers {
fmt.Printf("==== server %d =====\n", i )
fmt.Println(v)
serverslice.Address = v
serverslice.Ssl_grade = ssl_scraped.Sslservers[0].Sslgrade
serverslice.Country = h.Registrant.Country
serverslice.Owner = h.Registrant.Organization
fmt.Println("--------------------")
server.Servers = append(server.Servers, Serverslice(serverslice))
}
}
// comple data of the server
if err_dom == nil {
var creation, update, changed = h.Domain.CreatedDate, h.Domain.UpdatedDate, true
if creation == update {
changed = false
}
server.Servers_changed = changed
server.Ssl_grade = ssl_scraped.Sslservers[0].Sslgrade
server.Previous_ssl_grade = ssl_scraped.Sslservers[0].Sslgrade
server.Title = server_scraped[0]
server.Logo = server_scraped[1]
if res.StatusCode() == fasthttp.StatusInternalServerError {
server.Is_down = true
} else {
server.Is_down = false
}
}
// prepare JSON
s, _ := json.Marshal(server)
fmt.Println("======")
fmt.Println(string(s))
fmt.Println("======")
// fmt.Println("who is:")
// fmt.Println(host)
return string(s)
}
func ScrapeServer(d string) []string {
// scrape server
var s []string
full_url := "https://www." + d
res_body := DoRequestResponse(full_url)
fmt.Println("==============Using GoQuery===========")
data := res_body.(string)
doc, errr := goquery.NewDocumentFromReader(strings.NewReader(data))
if errr != nil {
log.Fatal(errr)
}
logo_shortcut := doc.Find("link[rel='shortcut icon']")
logo_path, _ := logo_shortcut.Attr("href")
title := doc.Find("title")
fmt.Println(logo_path)
fmt.Println(title.Text())
s = append(s, title.Text())
s = append(s, logo_path)
return s
}
func ScrapeSSL(d string) SslAnalysis {
var grades string
var ips string
var sslanalysis SslAnalysis
var sslserver SslServer
fmt.Println("=============scraping ssllabs=============")
ssllabs_path := "https://www.ssllabs.com/ssltest/analyze.html?d="
full_path := ssllabs_path + d
ssl_scan := DoRequestResponse(string(full_path))
doc, errr := goquery.NewDocumentFromReader(strings.NewReader(ssl_scan.(string)))
if errr != nil {
log.Fatal(errr)
}
// Get address and ssl_grade.
// This depends on the SSLLabs response (single or table)
result := doc.Find("table#multiTable") // 1+ ssl grades report
if result.Size() > 0 {
result.Each(func(i int, td *goquery.Selection) {
td_ip := td.Find("tbody tr td span.ip")
td_grade := td.Find("tbody tr td[align='center']")
// saves ips
ips = ips + " " + td_ip.Text()
// saves ssl grades
grades = grades + " " + td_grade.Text()
})
grades_slice := strings.Fields(grades)
index := 1
for i, v := range grades_slice {
if index == i {
sslserver.Sslgrade = v
index = index + 2
fmt.Println(i, v)
}
}
ips_slice := strings.Fields(ips)
for i, v := range ips_slice {
sslserver.Address = v
fmt.Println(i, v)
sslanalysis.Sslservers = append(sslanalysis.Sslservers, SslServer(sslserver))
}
// j, _ := json.Marshal(sslanalysis)
// fmt.Println(string(j))
return sslanalysis
} else {
// fetch the grade
result_grade := doc.Find("#gradeA")
grade_ssl := strings.TrimSpace(result_grade.Text())
// fetch the ip address
result_ip := doc.Find(".ip")
ip_ssl := strings.TrimSpace(result_ip.Text())
ip_ssl = strings.Trim(ip_ssl, "()")
// prepare json return
sslserver.Sslgrade = grade_ssl
sslserver.Address = ip_ssl
sslanalysis.Sslservers = append(sslanalysis.Sslservers, SslServer(sslserver))
fmt.Println("ip: " + ip_ssl)
fmt.Println("grade ssl: " + grade_ssl)
// j, _ := json.Marshal(sslanalysis)
// fmt.Println(string(j))
return sslanalysis
}
}
// this function receives an url and gives html
func DoRequestResponse(url string) interface{} {
fmt.Println("==============Request - Response===========")
req := fasthttp.AcquireRequest()
req.SetRequestURI(url)
res := fasthttp.AcquireResponse()
err := fasthttp.Do(req, res)
if err != nil {
fmt.Printf("Client get failed: %s\n", err)
}
if res.StatusCode() != fasthttp.StatusOK {
fmt.Printf("Expected status code %d but got %d\n", fasthttp.StatusOK, res.StatusCode())
}
body := res.Body()
fmt.Println("successful response!")
return string(body)
}
// save domains in the 'dataservers' database
func SaveDomain(domain interface{}) {
db, err := ConnectDB()
WriteDB(db, err, domain.(string))
}
// connect to the databse Cockroach
func ConnectDB() (*sql.DB, interface{}) {
db, err := sql.Open("postgres", "postgresql://jsam@localhost:26257/dataservers?ssl=true&sslmode=require&sslrootcert=certs/ca.crt&sslkey=certs/client.jsam.key&sslcert=certs/client.jsam.crt")
if err != nil {
log.Fatal("Error connecting to the database:", err)
}
// defer db.Close()
return db, err
}
func WriteDB(db *sql.DB, err interface{}, d string ) {
// create/verify the table 'domains'
if _, err := db.Exec("CREATE TABLE IF NOT EXISTS domains (id INT PRIMARY KEY DEFAULT unique_rowid(), domain STRING NOT NULL, search_date TIMESTAMP)"); err != nil {
log.Fatal(err)
}
// insert elements into 'domains'
if _, err := db.Exec("INSERT INTO domains (domain, search_date) VALUES ($1, now())", d); err != nil {
log.Fatal(err)
}
}
// Get servers - Endpoint II
func GetServers(ctx *fasthttp.RequestCtx) {
fmt.Println("i'm the endpoint ii")
type Domain struct {
Items []string `json:"items"`
}
db, err := ConnectDB()
rows, err := db.Query("SELECT domain FROM domains")
if err != nil {
log.Fatal(err)
}
var d Domain
dd := ""
for rows.Next() {
var dom string
if err := rows.Scan(&dom); err != nil {
log.Fatal(err)
}
if dd != dom {
d.Items = append(d.Items, dom)
}
dd = dom
}
j, _ := json.Marshal(d)
fmt.Println(d)
fmt.Println(string(j))
fmt.Fprintf(ctx, string(j))
}
func Index(ctx *fasthttp.RequestCtx) {
// render welcome!
ctx.SetContentType("text/html")
// tmpl := template.Must(template.ParseGlob("welcome.html"))
tmpl := template.Must(template.ParseFiles("frontend/welcome.html"))
tmpl.Execute(ctx, nil)
}