sql.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. /*
  2. * swsyd - swsy daemon, make nsswitch easy
  3. * Copyright (C) 2024 Marcus Pedersén marcus@marcux.org
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. package sql
  19. import (
  20. "fmt"
  21. "errors"
  22. "log/slog"
  23. "slices"
  24. "strings"
  25. "time"
  26. "notabug.org/marcux/swsy/swsyd/common"
  27. "gorm.io/driver/sqlite"
  28. "gorm.io/gorm"
  29. )
  30. // Represents the passwd
  31. // file.
  32. type Password struct {
  33. ID uint32
  34. Username string `gorm:"unique" form:"username"`
  35. Password string `gorm:"default:'x'" form:"-"`
  36. UID int32 `gorm:"unique" form:"uid"`
  37. GID int32 `form:"gid"`
  38. Gecos string `form:"gecos"`
  39. Home string `form:"home"`
  40. Shell string `form:"shell"`
  41. }
  42. // Represent group file
  43. type Group struct {
  44. ID uint32
  45. Groupname string `gorm:"unique" form:"groupname"`
  46. GroupPassword string `gorm:"default:'x'" form:"password"`
  47. GID int32 `gorm:"unique" form:"gid"`
  48. Users string `form:"-"`
  49. }
  50. // Represent shadow file
  51. type Shadow struct {
  52. ID uint32
  53. Username string `gorm:"unique" form:"username"`
  54. Password string `form:"password"`
  55. LastChange uint32 `form:"last_change"`
  56. MinPasswordAge uint32 `gorm:"default:0" form:"min_password_age"`
  57. MaxPasswordAge uint32 `gorm:"default:99999" form:"max_password_age"`
  58. WarningPeriod uint32 `gorm:"default:7" form:"warning_period"`
  59. InactivePeriod uint32 `form:"inactive_period"`
  60. ExpireDate string `form:"expire_date"`
  61. }
  62. // Represent host file
  63. type Host struct {
  64. ID uint32
  65. IPv4 string `form:"ipv4"`
  66. IPv6 string `form:"ipv6"`
  67. Hostnames string `gorm:"not null" form:"hostnames"`
  68. }
  69. // Returns users with specified
  70. // name. If user is empty string
  71. // and uid is a negative value
  72. // all users are returned.
  73. // If uid is a positive value
  74. // specified user is returned.
  75. // If name and search is soecified
  76. // all users starting with name is
  77. // returned. If only name is specified
  78. // user with exactly that name is returned.
  79. func GetUser(db *gorm.DB, name string, uid int32, search bool) []Password {
  80. users := []Password{}
  81. if len(name) == 0 && uid < 0 {
  82. rows, err := db.Find(&[]Password{}).Rows()
  83. if err != nil {
  84. slog.Error(fmt.Sprintf("Failed to get all password: %s", err))
  85. return users
  86. }
  87. defer rows.Close()
  88. for rows.Next() {
  89. var u Password
  90. db.ScanRows(rows, &u)
  91. users = append(users, u)
  92. }
  93. } else if uid >= 0 {
  94. rows, err := db.Where("UID = ?", uid).Find(&Password{}).Rows()
  95. if err != nil {
  96. slog.Error(fmt.Sprintf("Failed to get password with UID: %d, %s", uid, err))
  97. return users
  98. }
  99. defer rows.Close()
  100. for rows.Next() {
  101. var u Password
  102. db.ScanRows(rows, &u)
  103. users = append(users, u)
  104. }
  105. } else if search {
  106. rows,err := db.Where("username LIKE ?",
  107. fmt.Sprintf("%s%%", name)).Find(&[]Password{}).Rows()
  108. if err != nil {
  109. slog.Error(fmt.Sprintf("Failed to get all users starting with: %s from database", name))
  110. return users
  111. }
  112. defer rows.Close()
  113. for rows.Next() {
  114. var u Password
  115. db.ScanRows(rows, &u)
  116. users = append(users, u)
  117. }
  118. } else {
  119. rows,err := db.Where("username = ?", name).Find(&Password{}).Rows()
  120. if err != nil {
  121. slog.Error(fmt.Sprintf("Failed to get users with username: %s from database", name))
  122. return users
  123. }
  124. defer rows.Close()
  125. for rows.Next() {
  126. var u Password
  127. db.ScanRows(rows, &u)
  128. users = append(users, u)
  129. }
  130. }
  131. return users
  132. }
  133. // Gets group, group
  134. // specified with either
  135. // groupname or uid.
  136. // If both are provided gid
  137. // will be used, gid must be
  138. // a negative value to not be used.
  139. // Search will return groups starting
  140. // with searched string.
  141. // If search is provided with gid
  142. // it will be ignored.
  143. // If name is empty string, gid is
  144. // negative and search is true
  145. // then all groups are returned.
  146. func GetGroup(db *gorm.DB, name string, gid int32, search bool) []Group {
  147. groups := []Group{}
  148. if gid >= 0 {
  149. // Get group with gid
  150. g := Group{}
  151. res := db.Where("g_id = ?", gid).First(&g)
  152. if res.Error != nil {
  153. slog.Error(fmt.Sprintf("Failed to get group with gid: %d from database: %s", gid, res.Error))
  154. } else {
  155. groups = append(groups, g)
  156. }
  157. } else if len(name) > 0 && search {
  158. // Get groups starting with groupnasme.
  159. rows, err := db.Table("groups").Where("groupname LIKE ?",
  160. fmt.Sprintf("%s%%", name)).Rows()
  161. if err != nil {
  162. slog.Error(fmt.Sprintf("Failed to get group with groupname starting with: %s from database: %s", name, err))
  163. } else {
  164. defer rows.Close()
  165. for rows.Next() {
  166. g := Group{}
  167. db.ScanRows(rows, &g)
  168. groups = append(groups, g)
  169. }
  170. }
  171. } else if len(name) > 0 {
  172. // Get group with groupname
  173. g := Group{}
  174. res := db.Where("groupname = ?", name).First(&g)
  175. if res.Error != nil {
  176. slog.Error(fmt.Sprintf("Failed to get group with groupname: %s from database: %s", name, res.Error))
  177. } else {
  178. groups = append(groups, g)
  179. }
  180. } else if len(name) == 0 && gid < 0 && search {
  181. rows, err := db.Find(&[]Group{}).Rows()
  182. if err != nil {
  183. slog.Error(fmt.Sprintf("Failed to get all groups from database: %s", err))
  184. } else {
  185. defer rows.Close()
  186. for rows.Next() {
  187. g := Group{}
  188. db.ScanRows(rows, &g)
  189. groups = append(groups, g)
  190. }
  191. }
  192. }
  193. return groups
  194. }
  195. // Gets users group, users
  196. // specified with either
  197. // username or uid.
  198. // If both are provided uid
  199. // will be used, uid must be
  200. // a negative value to not be used.
  201. // First value in returned
  202. // slice is the primary group.
  203. func GetUserGroups(db *gorm.DB, name string, uid int32) []Group {
  204. groups := []Group{}
  205. u := Password{}
  206. if uid >= 0 {
  207. res := db.Where("uid = ?", uid).First(&u)
  208. if res.Error != nil {
  209. slog.Error("GetUserGroups: Failed to get user with uid: %s from database: %s", uid, res.Error)
  210. return groups
  211. }
  212. } else if len(name) > 0 {
  213. res := db.Where("username = ?", name).First(&u)
  214. if res.Error != nil {
  215. slog.Error("GetUserGroups: Failed to get user with username: %s from database: %s", name, res.Error)
  216. return groups
  217. }
  218. } else {
  219. return groups
  220. }
  221. rows, err := db.Table("groups").Where("users LIKE ?",
  222. fmt.Sprintf("%%%s%%", u.Username)).Rows()
  223. if err != nil {
  224. slog.Error(fmt.Sprintf("GetUserGroups: Failed to get all groups for user with uid: %s, %s", uid, err))
  225. return groups
  226. }
  227. defer rows.Close()
  228. var primGroup Group
  229. for rows.Next() {
  230. var g Group
  231. db.ScanRows(rows, &g)
  232. if g.GID == u.GID {
  233. primGroup = g
  234. } else {
  235. usrs := strings.Split(g.Users, ",")
  236. for _, usr := range usrs {
  237. if strings.TrimSpace(usr) == u.Username {
  238. groups = append(groups, g)
  239. break
  240. }
  241. }
  242. }
  243. }
  244. if len(primGroup.Groupname) > 0 {
  245. groups = append([]Group{primGroup}, groups...)
  246. }
  247. return groups
  248. }
  249. // Gets shadow fields,
  250. // specified with either
  251. // username or uid.
  252. // If both are provided uid
  253. // will be used, uid must be
  254. // a negative value to not be used.
  255. // Search will return shadow fields
  256. // starting with searched username.
  257. // If search is provided with uid
  258. // it will be ignored.
  259. // If user is empty string, uid is
  260. // negative and search is true
  261. // then all shadow records are returned.
  262. func GetShadow(db *gorm.DB, user string, uid int32, search bool) []Shadow {
  263. shadows := []Shadow{}
  264. if uid >= 0 {
  265. // Get shadow for uid
  266. u := Password{}
  267. res := db.Table("passwords").Where("uid = ?", uid).First(&u)
  268. if res.Error != nil {
  269. slog.Error("GetShadow: Failed to get user with UID: %d from database: %s", uid, res.Error)
  270. return shadows
  271. }
  272. s := Shadow{}
  273. res = db.Table("shadows").Where("username = ?", u.Username).First(&s)
  274. if res.Error != nil {
  275. slog.Error("GetShadow: Failed to get shadow with username: %s, %s",
  276. u.Username, res.Error)
  277. } else {
  278. shadows = append(shadows, s)
  279. }
  280. } else if len(user) > 0 && search {
  281. // Get shadows starting with user
  282. rows, err := db.Table("shadows").Where("username LIKE ?",
  283. fmt.Sprintf("%%%s%%", user)).Rows()
  284. if err != nil {
  285. slog.Error(fmt.Sprintf("GetShadow: Failed to get all shadow fields for user with name: %s, %s", user, err))
  286. return shadows
  287. }
  288. defer rows.Close()
  289. for rows.Next() {
  290. s := Shadow{}
  291. db.ScanRows(rows, &s)
  292. shadows = append(shadows, s)
  293. }
  294. } else if len(user) > 0 {
  295. // Get shadow for username
  296. s := Shadow{}
  297. res := db.Table("shadows").Where("username = ?", user).First(&s)
  298. if res.Error != nil {
  299. slog.Error("GetShadow: Failed to get shadow with username: %s, %s",
  300. user, res.Error)
  301. } else {
  302. shadows = append(shadows, s)
  303. }
  304. } else if len(user) == 0 && uid < 0 && search {
  305. // Get all shadow fields
  306. rows, err := db.Find(&[]Shadow{}).Rows()
  307. if err != nil {
  308. slog.Error("GetShadow: Failed to get all shadow fields")
  309. } else {
  310. defer rows.Close()
  311. for rows.Next() {
  312. s := Shadow{}
  313. db.ScanRows(rows, &s)
  314. shadows = append(shadows, s)
  315. }
  316. }
  317. }
  318. return shadows
  319. }
  320. // Gets host,
  321. // specified with either
  322. // hostname, ipv4 or ipv6.
  323. // If more then one is provided
  324. // hostname will be used.
  325. // Search will return hosts
  326. // starting with searched hostname.
  327. // If search is provided with any other
  328. // argument, it will be ignored.
  329. // If name, ipv4 and ipv6 are empty string
  330. // and search is true
  331. // then all hosts are returned.
  332. func GetHost(db *gorm.DB, name string, ipv4 string, ipv6 string, search bool) []Host {
  333. hosts := []Host{}
  334. if search && len(name) == 0 && len(ipv4) == 0 && len(ipv6) == 0 {
  335. // Get all hosts
  336. rows, err := db.Find(&[]Host{}).Rows()
  337. if err != nil {
  338. slog.Error(fmt.Sprintf("GetHost: Failed to get all hosts: %s", err))
  339. } else {
  340. defer rows.Close()
  341. for rows.Next() {
  342. h := Host{}
  343. db.ScanRows(rows, &h)
  344. hosts = append(hosts, h)
  345. }
  346. }
  347. } else if len(name) > 0 && !search && len(ipv4) == 0 && len(ipv6) == 0 {
  348. // Get host with hostname
  349. h := Host{}
  350. res := db.Table("hosts").Where("hostnames = ?", name).First(&h)
  351. if res.Error != nil {
  352. slog.Error(fmt.Sprintf("GetHost: Failed tyo get host with hostname: %s, %s",
  353. name, res.Error))
  354. } else {
  355. hosts = append(hosts, h)
  356. }
  357. } else if len(name) > 0 && search && len(ipv4) == 0 && len(ipv6) == 0 {
  358. // Get host starting with hostname
  359. rows, err := db.Table("hosts").Where("hostnames LIKE ?",
  360. fmt.Sprintf("%%%s%%", name)).Rows()
  361. if err != nil {
  362. slog.Error(fmt.Sprintf("GetHost: Failed to get hosts starting with: %s, %s",
  363. name, err))
  364. } else {
  365. defer rows.Close()
  366. for rows.Next() {
  367. h := Host{}
  368. db.ScanRows(rows, &h)
  369. hosts = append(hosts, h)
  370. }
  371. }
  372. } else if len(ipv4) > 0 && !search && len(name) == 0 && len(ipv6) == 0 {
  373. // Get host with IPv4
  374. h := Host{}
  375. res := db.Table("hosts").Where("ipv4 = ?", ipv4).First(&h)
  376. if res.Error != nil {
  377. slog.Error(fmt.Sprintf("GetHost: Fasiled to get host with ipv4: %s, %s",
  378. ipv4, res.Error))
  379. } else {
  380. hosts = append(hosts, h)
  381. }
  382. } else if len(ipv6) > 0 && !search && len(ipv4) == 0 && len(name) == 0 {
  383. // Get host with IPv6
  384. h := Host{}
  385. res := db.Table("hosts").Where("ipv6 = ?", ipv6).First(&h)
  386. if res.Error != nil {
  387. slog.Error(fmt.Sprintf("GetHost: Failed to get host cwith ipv6: %s, %s",
  388. ipv6, res.Error))
  389. } else {
  390. hosts = append(hosts, h)
  391. }
  392. }
  393. return hosts
  394. }
  395. // Insert user in database
  396. func InsertUser(db *gorm.DB, conf common.Config, user Password) error {
  397. u := GetUser(db, user.Username, -1, false)
  398. if len(u) > 0 {
  399. return fmt.Errorf("Failed to add user: User with username: %s already exist.", user.Username)
  400. }
  401. uids := []int32{}
  402. gids := []int32{}
  403. rows, err := db.Table("passwords").Where("uid >= ?", conf.MinUid).Order("uid").Rows()
  404. if err != nil {
  405. return fmt.Errorf("Failed to get all users where Uid >= %d, %s",
  406. conf.MinUid, err)
  407. }
  408. for rows.Next() {
  409. p := Password{}
  410. db.ScanRows(rows, &p)
  411. uids = append(uids, p.UID)
  412. }
  413. rows, err = db.Table("groups").Where("g_id >= ?", conf.MinGid).Order("g_id").Rows()
  414. for rows.Next() {
  415. g := Group{}
  416. db.ScanRows(rows, &g)
  417. gids = append(gids, g.GID)
  418. }
  419. var uid, gid int32 = -1, -1
  420. if conf.MinUid == conf.MinGid {
  421. no := 0
  422. for i := uint64(conf.MinUid); no < len(uids); i++ {
  423. if ! slices.Contains(uids, int32(i)) {
  424. if ! slices.Contains(gids, int32(i)) {
  425. uid = int32(i)
  426. gid = uid
  427. break
  428. }
  429. }
  430. no++
  431. }
  432. if uid == -1 {
  433. if len(uids) > 0 {
  434. uid = uids[len(uids)-1] + 1
  435. } else {
  436. uid = int32(conf.MinUid)
  437. }
  438. for {
  439. if ! slices.Contains(gids, uid) {
  440. gid = uid
  441. break
  442. }
  443. uid++
  444. }
  445. }
  446. } else {
  447. uid = int32(conf.MinUid)
  448. for {
  449. if ! slices.Contains(uids, uid) {
  450. break
  451. }
  452. uid++
  453. }
  454. gid = int32(conf.MinGid)
  455. for {
  456. if ! slices.Contains(gids,gid) {
  457. break
  458. }
  459. gid++
  460. }
  461. }
  462. user.UID = uid
  463. user.GID = gid
  464. res := db.Create(&user)
  465. if res.Error != nil {
  466. return fmt.Errorf("Failed to insert user: %s in database, %s", user.Username, res.Error)
  467. }
  468. if res.RowsAffected > 1 {
  469. return fmt.Errorf("Database error, to many rows affected: %d", res.RowsAffected)
  470. }
  471. return nil
  472. }
  473. // Insert group in database
  474. func InsertGroup(db *gorm.DB, conf common.Config, group Group) error {
  475. grp := GetGroup(db, "", group.GID, false)
  476. if len(grp) > 0 {
  477. return fmt.Errorf("Failed to add group, group with GID = %d already exist.", group.GID)
  478. }
  479. grp = GetGroup(db, group.Groupname, -1, false)
  480. if len(grp) > 0 {
  481. return fmt.Errorf("Failed to add group, group with name: %s already exists.", group.Groupname)
  482. }
  483. if group.GID == 0 {
  484. gids := []int32{}
  485. rows, err := db.Table("groups").Where("g_id >= ?", conf.MinGid).Order("g_id").Rows()
  486. if err != nil {
  487. return fmt.Errorf("Failed to get all groups with GID >= %d from database: %s", err)
  488. }
  489. for rows.Next() {
  490. g := Group{}
  491. db.ScanRows(rows, &g)
  492. gids = append(gids, g.GID)
  493. }
  494. no := 0
  495. gid := int32(0)
  496. for i := uint64(conf.MinGid); no < len(gids); i++ {
  497. if ! slices.Contains(gids, int32(i)) {
  498. gid = int32(i)
  499. break
  500. }
  501. no++
  502. }
  503. if gid == 0 {
  504. if len(gids) > 0 {
  505. gid = gids[len(gids)-1]+1
  506. } else {
  507. gid = int32(conf.MinGid)
  508. }
  509. }
  510. group.GID = gid
  511. }
  512. res := db.Create(&group)
  513. if res.Error != nil {
  514. return fmt.Errorf("Failed to insert group: %s in database, %s", group.Groupname, res.Error)
  515. }
  516. if res.RowsAffected > 1 {
  517. return fmt.Errorf("Database error, to many rows affected: %d", res.RowsAffected)
  518. }
  519. return nil
  520. }
  521. // Insert new shadow in database
  522. // If uid >= 0 it will be used
  523. // otherwise shadow.Username
  524. // will be used
  525. func InsertShadow(db *gorm.DB, conf common.Config, shadow Shadow, uid int32) error {
  526. unixTime := time.Now().Unix()
  527. shadow.LastChange = uint32(unixTime)
  528. if uid >= 0 {
  529. shs := GetUser(db, "", uid, false)
  530. if len(shs) <= 0 {
  531. return fmt.Errorf("User with uid: %d does not exist", uid)
  532. } else if len(shs) > 1 {
  533. return fmt.Errorf("Wrong number of rows found in database for uid: %d", uid)
  534. }
  535. shadow.Username = shs[0].Username
  536. } else {
  537. shs := GetUser(db,shadow.Username, -1, false)
  538. if len(shs) <= 0 {
  539. return fmt.Errorf("User with username: %s does not exist", shadow.Username)
  540. } else if len(shs) > 1 {
  541. return fmt.Errorf("Wrong number of rows found in database for username: %s", shadow.Username)
  542. }
  543. }
  544. exist := GetShadow(db, shadow.Username, -1, false)
  545. if len(exist) > 0 {
  546. return fmt.Errorf("Password for username: %s, already exist", shadow.Username)
  547. }
  548. res := db.Create(&shadow)
  549. if res.Error != nil {
  550. return fmt.Errorf("Failed to insert password in database %s", res.Error)
  551. }
  552. if res.RowsAffected > 1 {
  553. return fmt.Errorf("Database error, to many rows affected: %d", res.RowsAffected)
  554. }
  555. return nil
  556. }
  557. // Insert new host in database
  558. func InsertHost(db *gorm.DB, conf common.Config, host Host) error {
  559. ip4Exist := GetHost(db, "", host.IPv4, "", false)
  560. if len(ip4Exist) > 0 {
  561. return fmt.Errorf("Failed to add host. Host with IPv4 address: %s, already exist.", host.IPv4)
  562. }
  563. ip6Exist := GetHost(db, "", "", host.IPv6, false)
  564. if len(ip6Exist) > 0 {
  565. return fmt.Errorf("Failed to add host. Host with IPv6 address: %s already exist.", host.IPv6)
  566. }
  567. var hExist []Host
  568. for _, h := range strings.Fields(host.Hostnames) {
  569. hExist = GetHost(db, h, "", "", true)
  570. if len(hExist) > 0 {
  571. return fmt.Errorf("Failed to add host. Hostname: %s already exist", h)
  572. }
  573. }
  574. res := db.Create(&host)
  575. if res.Error != nil {
  576. return fmt.Errorf("Failed to insert host in database %s", res.Error)
  577. }
  578. if res.RowsAffected > 1 {
  579. return fmt.Errorf("Database error, to many rows affected: %d", res.RowsAffected)
  580. }
  581. return nil
  582. }
  583. // Init database and return handle
  584. func InitDb(c common.Config) (*gorm.DB, error) {
  585. db, err := gorm.Open(sqlite.Open(c.Dbfile), &gorm.Config{})
  586. if err != nil {
  587. return &gorm.DB{}, errors.New(
  588. fmt.Sprintf("Failed to open database: %s, %s\n",
  589. "swsy.db", err),
  590. )
  591. }
  592. db.AutoMigrate(&Password{})
  593. db.AutoMigrate(&Group{})
  594. db.AutoMigrate(&Shadow{})
  595. db.AutoMigrate(&Host{})
  596. return db, nil
  597. }