webserver.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. package kyoketsu
  2. import (
  3. "embed"
  4. "encoding/json"
  5. "fmt"
  6. "html/template"
  7. "io"
  8. "log"
  9. "net/http"
  10. "path"
  11. "strings"
  12. "sync"
  13. )
  14. type ScanRequest struct {
  15. IpAddress string `json:"ip_address"`
  16. FqdnPattern string `json:"fqdn_pattern"`
  17. }
  18. // Holding all static web server resources
  19. //
  20. //go:embed html/bootstrap-5.0.2-dist/js/* html/bootstrap-5.0.2-dist/css/* html/* html/templates/*
  21. var content embed.FS
  22. /*
  23. Run a new webserver
  24. :param port: port number to run the webserver on
  25. */
  26. func RunHttpServer(port int, dbhook TopologyDatabaseIO, portmap []int, logStream io.Writer) {
  27. assets := &AssetHandler{Root: content, RelPath: "static", EmbedRoot: "html"}
  28. tmpl, err := template.ParseFS(content, "html/templates/*.html")
  29. if err != nil {
  30. log.Fatal(err)
  31. }
  32. iptable, err := template.ParseFS(content, "html/templates/ip_table.html")
  33. if err != nil {
  34. log.Fatal(err)
  35. }
  36. htmlHndl := &HtmlHandler{Home: tmpl, TableEntry: iptable, DbHook: dbhook}
  37. execHndl := &ExecutionHandler{DbHook: dbhook, PortMap: portmap, TableEntry: iptable, stream: logStream}
  38. http.Handle("/static/", assets)
  39. http.Handle("/home", htmlHndl)
  40. http.Handle("/subnets", htmlHndl)
  41. http.Handle("/excludefqdn", htmlHndl)
  42. http.Handle("/refresh", execHndl)
  43. log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", port), nil))
  44. }
  45. type ExecutionHandler struct {
  46. DbHook TopologyDatabaseIO
  47. TableEntry *template.Template
  48. PortMap []int
  49. stream io.Writer
  50. }
  51. func (e *ExecutionHandler) Log(vals ...string) {
  52. e.stream.Write([]byte("KYOKETSU-WEB LOG ||| " + strings.Join(vals, " ||| ")))
  53. }
  54. /*
  55. Top level function to be routed to, this will spawn a suite of goroutines that will perform a concurrent scan on hosts and write back HTML data
  56. :param w: an http.ResponseWriter that we will write data back to
  57. :param r: a pointer to the request coming in from the client
  58. */
  59. func (e *ExecutionHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  60. input, err := e.parseRequest(r)
  61. if err != nil {
  62. http.Error(w, err.Error(), http.StatusInternalServerError)
  63. return
  64. }
  65. subnetMap, err := GetNetworkAddresses(input.IpAddress)
  66. if err != nil {
  67. http.Error(w, "Failed to get network addresses", http.StatusInternalServerError)
  68. return
  69. }
  70. scanned := make(chan Host)
  71. var wg sync.WaitGroup
  72. var mu sync.Mutex
  73. var errorRaised bool
  74. wg.Add(1)
  75. go e.processScannedData(w, e.TableEntry, scanned, &wg, &mu, &errorRaised)
  76. NetSweep(subnetMap.Ipv4s, subnetMap.Mask, RetrieveScanDirectives(), scanned)
  77. close(scanned)
  78. wg.Wait()
  79. if errorRaised {
  80. http.Error(w, "Error during scan processing. Check logs for details.", http.StatusInternalServerError)
  81. }
  82. }
  83. /*
  84. Parse the request sent in from the client
  85. :param r: pointer to the http.Request coming in from the client
  86. */
  87. func (e *ExecutionHandler) parseRequest(r *http.Request) (ScanRequest, error) {
  88. var input ScanRequest
  89. b, err := io.ReadAll(r.Body)
  90. defer r.Body.Close()
  91. if err != nil {
  92. return input, fmt.Errorf("error reading request body: %w", err)
  93. }
  94. err = json.Unmarshal(b, &input)
  95. if err != nil {
  96. return input, fmt.Errorf("error unmarshalling request body: %w", err)
  97. }
  98. return input, nil
  99. }
  100. /*
  101. Process the data that is created from the kyoketsu Web Scanner, and parse the data into an HTML template
  102. :param w: an http.ResponseWriter to write the template back into
  103. :param templ: a pointer to the html template that will house the data
  104. :param scanned: a channel with 'Host' structs coming through
  105. :param wg: a pointer to a waitgroup that will get decremented when the function exits
  106. :param mu: a pointer to a mutex that will control when the errorRaised singleton is modified
  107. :param errorRaised: a pointer to a boolean that will signify if an error raised whilst processing data
  108. */
  109. func (e *ExecutionHandler) processScannedData(w http.ResponseWriter, templ *template.Template, scanned chan Host, wg *sync.WaitGroup, mu *sync.Mutex, errorRaised *bool) {
  110. defer wg.Done()
  111. for x := range scanned {
  112. if len(x.ListeningPorts) > 0 {
  113. if err := templ.Execute(w, x); err != nil {
  114. mu.Lock()
  115. *errorRaised = true
  116. mu.Unlock()
  117. e.Log(err.Error())
  118. }
  119. host, err := e.DbHook.GetByIP(x.IpAddress)
  120. if err != nil {
  121. if err != ErrNotExists {
  122. mu.Lock()
  123. *errorRaised = true
  124. mu.Unlock()
  125. e.Log(err.Error())
  126. }
  127. if _, err := e.DbHook.Create(x); err != nil {
  128. mu.Lock()
  129. *errorRaised = true
  130. mu.Unlock()
  131. e.Log(err.Error())
  132. }
  133. continue
  134. }
  135. if _, err := e.DbHook.Update(host.Id, x); err != nil {
  136. mu.Lock()
  137. *errorRaised = true
  138. mu.Unlock()
  139. e.Log(err.Error())
  140. }
  141. }
  142. }
  143. }
  144. // handlers //
  145. type HtmlHandler struct {
  146. Home *template.Template // pointer to the HTML homepage
  147. TableEntry *template.Template // pointer to the table entry html template
  148. DbHook TopologyDatabaseIO
  149. }
  150. func (h *HtmlHandler) handleHome(w http.ResponseWriter, r *http.Request) {
  151. if r.RequestURI == "/home" {
  152. data, err := h.DbHook.All()
  153. if err != nil {
  154. http.Error(w, "There was an error reading from the database: "+err.Error(), http.StatusInternalServerError)
  155. }
  156. h.Home.Execute(w, data)
  157. return
  158. }
  159. }
  160. func (h *HtmlHandler) subnetQueryHandler(w http.ResponseWriter, r *http.Request) {
  161. var req ScanRequest
  162. b, err := io.ReadAll(r.Body)
  163. defer r.Body.Close()
  164. if err != nil {
  165. http.Error(w, "There was an error reading the request: "+err.Error(), http.StatusBadRequest)
  166. return
  167. }
  168. err = json.Unmarshal(b, &req)
  169. if err != nil {
  170. http.Error(w, "There was an error reading the request: "+err.Error(), http.StatusBadRequest)
  171. return
  172. }
  173. data, err := h.DbHook.GetByNetwork(req.IpAddress)
  174. if err != nil {
  175. http.Error(w, "There was an error reading the request: "+err.Error(), http.StatusBadRequest)
  176. return
  177. }
  178. for _, host := range data {
  179. h.TableEntry.Execute(w, host)
  180. }
  181. }
  182. func (h *HtmlHandler) fqdnQueryHandler(w http.ResponseWriter, r *http.Request) {
  183. var req ScanRequest
  184. b, err := io.ReadAll(r.Body)
  185. defer r.Body.Close()
  186. if err != nil {
  187. http.Error(w, "There was an error reading the request: "+err.Error(), http.StatusBadRequest)
  188. return
  189. }
  190. err = json.Unmarshal(b, &req)
  191. if err != nil {
  192. http.Error(w, "There was an error reading the request: "+err.Error(), http.StatusBadRequest)
  193. return
  194. }
  195. dnsList := strings.Split(req.FqdnPattern, ",")
  196. data, err := h.DbHook.FilterDnsPattern(dnsList)
  197. if err != nil {
  198. http.Error(w, "There was an error reading the request: "+err.Error(), http.StatusBadRequest)
  199. return
  200. }
  201. for _, host := range data {
  202. h.TableEntry.Execute(w, host)
  203. }
  204. }
  205. /*
  206. Handler function for HTML serving
  207. :param w: http.ResponseWriter interface for sending data back
  208. :param r: pointer to the http.Request coming in
  209. */
  210. func (h *HtmlHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  211. switch r.RequestURI {
  212. case "/home":
  213. h.handleHome(w, r)
  214. case "/subnets":
  215. h.subnetQueryHandler(w, r)
  216. case "/excludefqdn":
  217. h.fqdnQueryHandler(w, r)
  218. }
  219. }
  220. type AssetHandler struct {
  221. Root embed.FS // Should be able to use anything that implements the fs.FS interface for serving asset files
  222. EmbedRoot string // This is the root of the embeded file system
  223. RelPath string // The path that will be used for the handler, relative to the root of the webserver (/static, /assets, etc)
  224. }
  225. /*
  226. Handler function to serve out asset files (HTMX, bootstrap, pngs etc)
  227. :param w: http.ResponseWriter interface for sending data back to the caller
  228. :param r: pointer to an http.Request
  229. */
  230. func (a *AssetHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  231. var uripath string // the path from the request
  232. var pathSp []string // the path from the request split, so that we can point the request path to the embedded fs
  233. var assetPath []string // the cleaned path for the requested asset
  234. var fname string // filename of the requested asset
  235. var ctype string
  236. var b []byte
  237. var err error
  238. uripath = strings.TrimPrefix(r.URL.Path, a.RelPath)
  239. uripath = strings.Trim(uripath, "/")
  240. pathSp = strings.Split(uripath, "/")
  241. fname = pathSp[len(pathSp)-1]
  242. assetPath = append(assetPath, a.EmbedRoot)
  243. for i := 1; i < len(pathSp); i++ {
  244. assetPath = append(assetPath, pathSp[i])
  245. }
  246. b, err = a.Root.ReadFile(path.Join(assetPath...))
  247. if err != nil {
  248. http.Error(w, "Error occured when getting Asset: "+err.Error(), http.StatusBadRequest)
  249. }
  250. switch {
  251. case strings.Contains(fname, "css"):
  252. ctype = "text/css"
  253. case strings.Contains(fname, "js"):
  254. ctype = "text/javascript"
  255. case strings.Contains(fname, "html"):
  256. ctype = "text/html"
  257. case strings.Contains(fname, "json"):
  258. ctype = "application/json"
  259. case strings.Contains(fname, "png"):
  260. ctype = "image/png"
  261. default:
  262. ctype = "text"
  263. }
  264. w.Header().Add("Content-Type", ctype)
  265. fmt.Fprint(w, string(b))
  266. }