storage.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. /*
  2. GNU GENERAL PUBLIC LICENSE
  3. Version 3, 29 June 2007
  4. kyoketsu, a Client-To-Client Network Enumeration System
  5. Copyright (C) 2024 Russell Hrubesky, ChiralWorks Software LLC
  6. Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
  7. Everyone is permitted to copy and distribute verbatim copies
  8. of this license document, but changing it is not allowed.
  9. This program is free software: you can redistribute it and/or modify
  10. it under the terms of the GNU General Public License as published by
  11. the Free Software Foundation, either version 3 of the License,
  12. or (at your option) any later version.
  13. This program is distributed in the hope that it will be useful,
  14. but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  16. See the GNU General Public License for more details.
  17. You should have received a copy of the GNU General Public License
  18. along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. package kyoketsu
  21. import (
  22. "database/sql"
  23. "errors"
  24. "strings"
  25. "github.com/mattn/go-sqlite3"
  26. )
  27. type TopologyDatabaseIO interface {
  28. /*
  29. This interface defines the Input and output methods that will be necessary
  30. for an appropriate implementation of the data storage that the distributed system will use.
  31. When I get around to implementing the client-to-client format of this, it could be anything.
  32. */
  33. Migrate() error
  34. Create(host Host) (*Host, error)
  35. All() ([]Host, error)
  36. GetByNetwork(network string) ([]Host, error)
  37. FilterDnsPattern(network string, patterns []string) ([]Host, error)
  38. GetByIP(ip string) (*Host, error)
  39. Update(id int64, updated Host) (*Host, error)
  40. Delete(id int64) error
  41. }
  42. var (
  43. ErrDuplicate = errors.New("record already exists")
  44. ErrNotExists = errors.New("row not exists")
  45. ErrUpdateFailed = errors.New("update failed")
  46. ErrDeleteFailed = errors.New("delete failed")
  47. )
  48. type SQLiteRepo struct {
  49. db *sql.DB
  50. }
  51. // Instantiate a new SQLiteRepo struct
  52. func NewSQLiteRepo(db *sql.DB) *SQLiteRepo {
  53. return &SQLiteRepo{
  54. db: db,
  55. }
  56. }
  57. // Creates a new SQL table with necessary data
  58. func (r *SQLiteRepo) Migrate() error {
  59. query := `
  60. CREATE TABLE IF NOT EXISTS hosts(
  61. id INTEGER PRIMARY KEY AUTOINCREMENT,
  62. fqdn TEXT NOT NULL,
  63. ipv4_address TEXT NOT NULL UNIQUE,
  64. listening_port TEXT NOT NULL,
  65. network TEXT NOT NULL
  66. );
  67. `
  68. _, err := r.db.Exec(query)
  69. return err
  70. }
  71. /*
  72. Create an entry in the hosts table
  73. :param host: a Host entry from a port scan
  74. */
  75. func (r *SQLiteRepo) Create(host Host) (*Host, error) {
  76. res, err := r.db.Exec("INSERT INTO hosts(fqdn, ipv4_address, listening_port, network) values(?,?,?,?)", host.Fqdn, host.IpAddress, host.PortString, host.Network)
  77. if err != nil {
  78. var sqliteErr sqlite3.Error
  79. if errors.As(err, &sqliteErr) {
  80. if errors.Is(sqliteErr.ExtendedCode, sqlite3.ErrConstraintUnique) {
  81. return nil, ErrDuplicate
  82. }
  83. }
  84. return nil, err
  85. }
  86. id, err := res.LastInsertId()
  87. if err != nil {
  88. return nil, err
  89. }
  90. host.Id = id
  91. return &host, nil
  92. }
  93. // Get all Hosts from the host table
  94. func (r *SQLiteRepo) All() ([]Host, error) {
  95. rows, err := r.db.Query("SELECT * FROM hosts")
  96. if err != nil {
  97. return nil, err
  98. }
  99. defer rows.Close()
  100. var all []Host
  101. for rows.Next() {
  102. var host Host
  103. if err := rows.Scan(&host.Id, &host.Fqdn, &host.IpAddress, &host.PortString, &host.Network); err != nil {
  104. return nil, err
  105. }
  106. all = append(all, host)
  107. }
  108. return all, nil
  109. }
  110. // Get a record by its FQDN
  111. func (r *SQLiteRepo) GetByIP(ip string) (*Host, error) {
  112. row := r.db.QueryRow("SELECT * FROM hosts WHERE ipv4_address = ?", ip)
  113. var host Host
  114. if err := row.Scan(&host.Id, &host.Fqdn, &host.IpAddress, &host.PortString, &host.Network); err != nil {
  115. if errors.Is(err, sql.ErrNoRows) {
  116. return nil, ErrNotExists
  117. }
  118. return nil, err
  119. }
  120. return &host, nil
  121. }
  122. // Update a record by its ID
  123. func (r *SQLiteRepo) Update(id int64, updated Host) (*Host, error) {
  124. if id == 0 {
  125. return nil, errors.New("invalid updated ID")
  126. }
  127. res, err := r.db.Exec("UPDATE hosts SET fqdn = ?, ipv4_address = ?, listening_port = ?, network = ? WHERE id = ?", updated.Fqdn, updated.IpAddress, updated.PortString, updated.Network, id)
  128. if err != nil {
  129. return nil, err
  130. }
  131. rowsAffected, err := res.RowsAffected()
  132. if err != nil {
  133. return nil, err
  134. }
  135. if rowsAffected == 0 {
  136. return nil, ErrUpdateFailed
  137. }
  138. return &updated, nil
  139. }
  140. // Delete a record by its ID
  141. func (r *SQLiteRepo) Delete(id int64) error {
  142. res, err := r.db.Exec("DELETE FROM hosts WHERE id = ?", id)
  143. if err != nil {
  144. return err
  145. }
  146. rowsAffected, err := res.RowsAffected()
  147. if err != nil {
  148. return err
  149. }
  150. if rowsAffected == 0 {
  151. return ErrDeleteFailed
  152. }
  153. return err
  154. }
  155. func (r *SQLiteRepo) GetByNetwork(network string) ([]Host, error) {
  156. rows, err := r.db.Query("SELECT * FROM hosts WHERE network = ?", network)
  157. if err != nil {
  158. return nil, err
  159. }
  160. var hosts []Host
  161. defer rows.Close()
  162. for rows.Next() {
  163. var host Host
  164. if err := rows.Scan(&host.Id, &host.Fqdn, &host.IpAddress, &host.PortString, &host.Network); err != nil {
  165. return nil, err
  166. }
  167. hosts = append(hosts, host)
  168. }
  169. return hosts, nil
  170. }
  171. func (r *SQLiteRepo) FilterDnsPattern(network string, patterns []string) ([]Host, error) {
  172. var queryBuilder strings.Builder
  173. queryBuilder.WriteString("SELECT * FROM hosts WHERE network LIKE ? AND")
  174. args := make([]interface{}, len(patterns)+1)
  175. args[0] = network
  176. for i, pattern := range patterns {
  177. if i > 0 {
  178. queryBuilder.WriteString(" AND ")
  179. }
  180. queryBuilder.WriteString(" fqdn NOT LIKE ?")
  181. args[i+1] = "%" + pattern + "%"
  182. }
  183. rows, err := r.db.Query(queryBuilder.String(), args...)
  184. if err != nil {
  185. return nil, err
  186. }
  187. var hosts []Host
  188. defer rows.Close()
  189. for rows.Next() {
  190. var host Host
  191. if err := rows.Scan(&host.Id, &host.Fqdn, &host.IpAddress, &host.PortString, &host.Network); err != nil {
  192. return nil, err
  193. }
  194. hosts = append(hosts, host)
  195. }
  196. return hosts, nil
  197. }