krb5conf.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. // Package config implements KRB5 client and service configuration as described at https://web.mit.edu/kerberos/krb5-latest/doc/admin/conf_files/krb5_conf.html
  2. package config
  3. import (
  4. "bufio"
  5. "encoding/hex"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "net"
  11. "os"
  12. "os/user"
  13. "regexp"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/jcmturner/gofork/encoding/asn1"
  18. "github.com/jcmturner/gokrb5/v8/iana/etypeID"
  19. )
  20. // Config represents the KRB5 configuration.
  21. type Config struct {
  22. LibDefaults LibDefaults
  23. Realms []Realm
  24. DomainRealm DomainRealm
  25. //CaPaths
  26. //AppDefaults
  27. //Plugins
  28. }
  29. // WeakETypeList is a list of encryption types that have been deemed weak.
  30. const WeakETypeList = "des-cbc-crc des-cbc-md4 des-cbc-md5 des-cbc-raw des3-cbc-raw des-hmac-sha1 arcfour-hmac-exp rc4-hmac-exp arcfour-hmac-md5-exp des"
  31. // New creates a new config struct instance.
  32. func New() *Config {
  33. d := make(DomainRealm)
  34. return &Config{
  35. LibDefaults: newLibDefaults(),
  36. DomainRealm: d,
  37. }
  38. }
  39. // LibDefaults represents the [libdefaults] section of the configuration.
  40. type LibDefaults struct {
  41. AllowWeakCrypto bool //default false
  42. // ap_req_checksum_type int //unlikely to support this
  43. Canonicalize bool //default false
  44. CCacheType int //default is 4. unlikely to implement older
  45. Clockskew time.Duration //max allowed skew in seconds, default 300
  46. //Default_ccache_name string // default /tmp/krb5cc_%{uid} //Not implementing as will hold in memory
  47. DefaultClientKeytabName string //default /usr/local/var/krb5/user/%{euid}/client.keytab
  48. DefaultKeytabName string //default /etc/krb5.keytab
  49. DefaultRealm string
  50. DefaultTGSEnctypes []string //default aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96 des3-cbc-sha1 arcfour-hmac-md5 camellia256-cts-cmac camellia128-cts-cmac des-cbc-crc des-cbc-md5 des-cbc-md4
  51. DefaultTktEnctypes []string //default aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96 des3-cbc-sha1 arcfour-hmac-md5 camellia256-cts-cmac camellia128-cts-cmac des-cbc-crc des-cbc-md5 des-cbc-md4
  52. DefaultTGSEnctypeIDs []int32 //default aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96 des3-cbc-sha1 arcfour-hmac-md5 camellia256-cts-cmac camellia128-cts-cmac des-cbc-crc des-cbc-md5 des-cbc-md4
  53. DefaultTktEnctypeIDs []int32 //default aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96 des3-cbc-sha1 arcfour-hmac-md5 camellia256-cts-cmac camellia128-cts-cmac des-cbc-crc des-cbc-md5 des-cbc-md4
  54. DNSCanonicalizeHostname bool //default true
  55. DNSLookupKDC bool //default false
  56. DNSLookupRealm bool
  57. ExtraAddresses []net.IP //Not implementing yet
  58. Forwardable bool //default false
  59. IgnoreAcceptorHostname bool //default false
  60. K5LoginAuthoritative bool //default false
  61. K5LoginDirectory string //default user's home directory. Must be owned by the user or root
  62. KDCDefaultOptions asn1.BitString //default 0x00000010 (KDC_OPT_RENEWABLE_OK)
  63. KDCTimeSync int //default 1
  64. //kdc_req_checksum_type int //unlikely to implement as for very old KDCs
  65. NoAddresses bool //default true
  66. PermittedEnctypes []string //default aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96 des3-cbc-sha1 arcfour-hmac-md5 camellia256-cts-cmac camellia128-cts-cmac des-cbc-crc des-cbc-md5 des-cbc-md4
  67. PermittedEnctypeIDs []int32
  68. //plugin_base_dir string //not supporting plugins
  69. PreferredPreauthTypes []int //default “17, 16, 15, 14”, which forces libkrb5 to attempt to use PKINIT if it is supported
  70. Proxiable bool //default false
  71. RDNS bool //default true
  72. RealmTryDomains int //default -1
  73. RenewLifetime time.Duration //default 0
  74. SafeChecksumType int //default 8
  75. TicketLifetime time.Duration //default 1 day
  76. UDPPreferenceLimit int // 1 means to always use tcp. MIT krb5 has a default value of 1465, and it prevents user setting more than 32700.
  77. VerifyAPReqNofail bool //default false
  78. }
  79. // Create a new LibDefaults struct.
  80. func newLibDefaults() LibDefaults {
  81. uid := "0"
  82. var hdir string
  83. usr, _ := user.Current()
  84. if usr != nil {
  85. uid = usr.Uid
  86. hdir = usr.HomeDir
  87. }
  88. opts := asn1.BitString{}
  89. opts.Bytes, _ = hex.DecodeString("00000010")
  90. opts.BitLength = len(opts.Bytes) * 8
  91. return LibDefaults{
  92. CCacheType: 4,
  93. Clockskew: time.Duration(300) * time.Second,
  94. DefaultClientKeytabName: fmt.Sprintf("/usr/local/var/krb5/user/%s/client.keytab", uid),
  95. DefaultKeytabName: "/etc/krb5.keytab",
  96. DefaultTGSEnctypes: []string{"aes256-cts-hmac-sha1-96", "aes128-cts-hmac-sha1-96", "des3-cbc-sha1", "arcfour-hmac-md5", "camellia256-cts-cmac", "camellia128-cts-cmac", "des-cbc-crc", "des-cbc-md5", "des-cbc-md4"},
  97. DefaultTktEnctypes: []string{"aes256-cts-hmac-sha1-96", "aes128-cts-hmac-sha1-96", "des3-cbc-sha1", "arcfour-hmac-md5", "camellia256-cts-cmac", "camellia128-cts-cmac", "des-cbc-crc", "des-cbc-md5", "des-cbc-md4"},
  98. DNSCanonicalizeHostname: true,
  99. K5LoginDirectory: hdir,
  100. KDCDefaultOptions: opts,
  101. KDCTimeSync: 1,
  102. NoAddresses: true,
  103. PermittedEnctypes: []string{"aes256-cts-hmac-sha1-96", "aes128-cts-hmac-sha1-96", "des3-cbc-sha1", "arcfour-hmac-md5", "camellia256-cts-cmac", "camellia128-cts-cmac", "des-cbc-crc", "des-cbc-md5", "des-cbc-md4"},
  104. RDNS: true,
  105. RealmTryDomains: -1,
  106. SafeChecksumType: 8,
  107. TicketLifetime: time.Duration(24) * time.Hour,
  108. UDPPreferenceLimit: 1465,
  109. PreferredPreauthTypes: []int{17, 16, 15, 14},
  110. }
  111. }
  112. // Parse the lines of the [libdefaults] section of the configuration into the LibDefaults struct.
  113. func (l *LibDefaults) parseLines(lines []string) error {
  114. for _, line := range lines {
  115. //Remove comments after the values
  116. if idx := strings.IndexAny(line, "#;"); idx != -1 {
  117. line = line[:idx]
  118. }
  119. line = strings.TrimSpace(line)
  120. if line == "" {
  121. continue
  122. }
  123. if !strings.Contains(line, "=") {
  124. return InvalidErrorf("libdefaults section line (%s)", line)
  125. }
  126. p := strings.Split(line, "=")
  127. key := strings.TrimSpace(strings.ToLower(p[0]))
  128. switch key {
  129. case "allow_weak_crypto":
  130. v, err := parseBoolean(p[1])
  131. if err != nil {
  132. return InvalidErrorf("libdefaults section line (%s): %v", line, err)
  133. }
  134. l.AllowWeakCrypto = v
  135. case "canonicalize":
  136. v, err := parseBoolean(p[1])
  137. if err != nil {
  138. return InvalidErrorf("libdefaults section line (%s): %v", line, err)
  139. }
  140. l.Canonicalize = v
  141. case "ccache_type":
  142. p[1] = strings.TrimSpace(p[1])
  143. v, err := strconv.ParseUint(p[1], 10, 32)
  144. if err != nil || v < 0 || v > 4 {
  145. return InvalidErrorf("libdefaults section line (%s)", line)
  146. }
  147. l.CCacheType = int(v)
  148. case "clockskew":
  149. d, err := parseDuration(p[1])
  150. if err != nil {
  151. return InvalidErrorf("libdefaults section line (%s): %v", line, err)
  152. }
  153. l.Clockskew = d
  154. case "default_client_keytab_name":
  155. l.DefaultClientKeytabName = strings.TrimSpace(p[1])
  156. case "default_keytab_name":
  157. l.DefaultKeytabName = strings.TrimSpace(p[1])
  158. case "default_realm":
  159. l.DefaultRealm = strings.TrimSpace(p[1])
  160. case "default_tgs_enctypes":
  161. l.DefaultTGSEnctypes = strings.Fields(p[1])
  162. case "default_tkt_enctypes":
  163. l.DefaultTktEnctypes = strings.Fields(p[1])
  164. case "dns_canonicalize_hostname":
  165. v, err := parseBoolean(p[1])
  166. if err != nil {
  167. return InvalidErrorf("libdefaults section line (%s): %v", line, err)
  168. }
  169. l.DNSCanonicalizeHostname = v
  170. case "dns_lookup_kdc":
  171. v, err := parseBoolean(p[1])
  172. if err != nil {
  173. return InvalidErrorf("libdefaults section line (%s): %v", line, err)
  174. }
  175. l.DNSLookupKDC = v
  176. case "dns_lookup_realm":
  177. v, err := parseBoolean(p[1])
  178. if err != nil {
  179. return InvalidErrorf("libdefaults section line (%s): %v", line, err)
  180. }
  181. l.DNSLookupRealm = v
  182. case "extra_addresses":
  183. ipStr := strings.TrimSpace(p[1])
  184. for _, ip := range strings.Split(ipStr, ",") {
  185. if eip := net.ParseIP(ip); eip != nil {
  186. l.ExtraAddresses = append(l.ExtraAddresses, eip)
  187. }
  188. }
  189. case "forwardable":
  190. v, err := parseBoolean(p[1])
  191. if err != nil {
  192. return InvalidErrorf("libdefaults section line (%s): %v", line, err)
  193. }
  194. l.Forwardable = v
  195. case "ignore_acceptor_hostname":
  196. v, err := parseBoolean(p[1])
  197. if err != nil {
  198. return InvalidErrorf("libdefaults section line (%s): %v", line, err)
  199. }
  200. l.IgnoreAcceptorHostname = v
  201. case "k5login_authoritative":
  202. v, err := parseBoolean(p[1])
  203. if err != nil {
  204. return InvalidErrorf("libdefaults section line (%s): %v", line, err)
  205. }
  206. l.K5LoginAuthoritative = v
  207. case "k5login_directory":
  208. l.K5LoginDirectory = strings.TrimSpace(p[1])
  209. case "kdc_default_options":
  210. v := strings.TrimSpace(p[1])
  211. v = strings.Replace(v, "0x", "", -1)
  212. b, err := hex.DecodeString(v)
  213. if err != nil {
  214. return InvalidErrorf("libdefaults section line (%s): %v", line, err)
  215. }
  216. l.KDCDefaultOptions.Bytes = b
  217. l.KDCDefaultOptions.BitLength = len(b) * 8
  218. case "kdc_timesync":
  219. p[1] = strings.TrimSpace(p[1])
  220. v, err := strconv.ParseInt(p[1], 10, 32)
  221. if err != nil || v < 0 {
  222. return InvalidErrorf("libdefaults section line (%s)", line)
  223. }
  224. l.KDCTimeSync = int(v)
  225. case "noaddresses":
  226. v, err := parseBoolean(p[1])
  227. if err != nil {
  228. return InvalidErrorf("libdefaults section line (%s): %v", line, err)
  229. }
  230. l.NoAddresses = v
  231. case "permitted_enctypes":
  232. l.PermittedEnctypes = strings.Fields(p[1])
  233. case "preferred_preauth_types":
  234. p[1] = strings.TrimSpace(p[1])
  235. t := strings.Split(p[1], ",")
  236. var v []int
  237. for _, s := range t {
  238. i, err := strconv.ParseInt(s, 10, 32)
  239. if err != nil {
  240. return InvalidErrorf("libdefaults section line (%s): %v", line, err)
  241. }
  242. v = append(v, int(i))
  243. }
  244. l.PreferredPreauthTypes = v
  245. case "proxiable":
  246. v, err := parseBoolean(p[1])
  247. if err != nil {
  248. return InvalidErrorf("libdefaults section line (%s): %v", line, err)
  249. }
  250. l.Proxiable = v
  251. case "rdns":
  252. v, err := parseBoolean(p[1])
  253. if err != nil {
  254. return InvalidErrorf("libdefaults section line (%s): %v", line, err)
  255. }
  256. l.RDNS = v
  257. case "realm_try_domains":
  258. p[1] = strings.TrimSpace(p[1])
  259. v, err := strconv.ParseInt(p[1], 10, 32)
  260. if err != nil || v < -1 {
  261. return InvalidErrorf("libdefaults section line (%s)", line)
  262. }
  263. l.RealmTryDomains = int(v)
  264. case "renew_lifetime":
  265. d, err := parseDuration(p[1])
  266. if err != nil {
  267. return InvalidErrorf("libdefaults section line (%s): %v", line, err)
  268. }
  269. l.RenewLifetime = d
  270. case "safe_checksum_type":
  271. p[1] = strings.TrimSpace(p[1])
  272. v, err := strconv.ParseInt(p[1], 10, 32)
  273. if err != nil || v < 0 {
  274. return InvalidErrorf("libdefaults section line (%s)", line)
  275. }
  276. l.SafeChecksumType = int(v)
  277. case "ticket_lifetime":
  278. d, err := parseDuration(p[1])
  279. if err != nil {
  280. return InvalidErrorf("libdefaults section line (%s): %v", line, err)
  281. }
  282. l.TicketLifetime = d
  283. case "udp_preference_limit":
  284. p[1] = strings.TrimSpace(p[1])
  285. v, err := strconv.ParseUint(p[1], 10, 32)
  286. if err != nil || v > 32700 {
  287. return InvalidErrorf("libdefaults section line (%s)", line)
  288. }
  289. l.UDPPreferenceLimit = int(v)
  290. case "verify_ap_req_nofail":
  291. v, err := parseBoolean(p[1])
  292. if err != nil {
  293. return InvalidErrorf("libdefaults section line (%s): %v", line, err)
  294. }
  295. l.VerifyAPReqNofail = v
  296. }
  297. }
  298. l.DefaultTGSEnctypeIDs = parseETypes(l.DefaultTGSEnctypes, l.AllowWeakCrypto)
  299. l.DefaultTktEnctypeIDs = parseETypes(l.DefaultTktEnctypes, l.AllowWeakCrypto)
  300. l.PermittedEnctypeIDs = parseETypes(l.PermittedEnctypes, l.AllowWeakCrypto)
  301. return nil
  302. }
  303. // Realm represents an entry in the [realms] section of the configuration.
  304. type Realm struct {
  305. Realm string
  306. AdminServer []string
  307. //auth_to_local //Not implementing for now
  308. //auth_to_local_names //Not implementing for now
  309. DefaultDomain string
  310. KDC []string
  311. KPasswdServer []string //default admin_server:464
  312. MasterKDC []string
  313. }
  314. // Parse the lines of a [realms] entry into the Realm struct.
  315. func (r *Realm) parseLines(name string, lines []string) (err error) {
  316. r.Realm = name
  317. var adminServerFinal bool
  318. var KDCFinal bool
  319. var kpasswdServerFinal bool
  320. var masterKDCFinal bool
  321. var ignore bool
  322. var c int // counts the depth of blocks within brackets { }
  323. for _, line := range lines {
  324. if ignore && c > 0 && !strings.Contains(line, "{") && !strings.Contains(line, "}") {
  325. continue
  326. }
  327. //Remove comments after the values
  328. if idx := strings.IndexAny(line, "#;"); idx != -1 {
  329. line = line[:idx]
  330. }
  331. line = strings.TrimSpace(line)
  332. if line == "" {
  333. continue
  334. }
  335. if !strings.Contains(line, "=") && !strings.Contains(line, "}") {
  336. return InvalidErrorf("realms section line (%s)", line)
  337. }
  338. if strings.Contains(line, "v4_") {
  339. ignore = true
  340. err = UnsupportedDirective{"v4 configurations are not supported"}
  341. }
  342. if strings.Contains(line, "{") {
  343. c++
  344. if ignore {
  345. continue
  346. }
  347. }
  348. if strings.Contains(line, "}") {
  349. c--
  350. if c < 0 {
  351. return InvalidErrorf("unpaired curly brackets")
  352. }
  353. if ignore {
  354. if c < 1 {
  355. c = 0
  356. ignore = false
  357. }
  358. continue
  359. }
  360. }
  361. p := strings.Split(line, "=")
  362. key := strings.TrimSpace(strings.ToLower(p[0]))
  363. v := strings.TrimSpace(p[1])
  364. switch key {
  365. case "admin_server":
  366. appendUntilFinal(&r.AdminServer, v, &adminServerFinal)
  367. case "default_domain":
  368. r.DefaultDomain = v
  369. case "kdc":
  370. if !strings.Contains(v, ":") {
  371. // No port number specified default to 88
  372. if strings.HasSuffix(v, `*`) {
  373. v = strings.TrimSpace(strings.TrimSuffix(v, `*`)) + ":88*"
  374. } else {
  375. v = strings.TrimSpace(v) + ":88"
  376. }
  377. }
  378. appendUntilFinal(&r.KDC, v, &KDCFinal)
  379. case "kpasswd_server":
  380. appendUntilFinal(&r.KPasswdServer, v, &kpasswdServerFinal)
  381. case "master_kdc":
  382. appendUntilFinal(&r.MasterKDC, v, &masterKDCFinal)
  383. }
  384. }
  385. //default for Kpasswd_server = admin_server:464
  386. if len(r.KPasswdServer) < 1 {
  387. for _, a := range r.AdminServer {
  388. s := strings.Split(a, ":")
  389. r.KPasswdServer = append(r.KPasswdServer, s[0]+":464")
  390. }
  391. }
  392. return
  393. }
  394. // Parse the lines of the [realms] section of the configuration into an slice of Realm structs.
  395. func parseRealms(lines []string) (realms []Realm, err error) {
  396. var name string
  397. var start int
  398. var c int
  399. for i, l := range lines {
  400. //Remove comments after the values
  401. if idx := strings.IndexAny(l, "#;"); idx != -1 {
  402. l = l[:idx]
  403. }
  404. l = strings.TrimSpace(l)
  405. if l == "" {
  406. continue
  407. }
  408. //if strings.Contains(l, "v4_") {
  409. // return nil, errors.New("v4 configurations are not supported in Realms section")
  410. //}
  411. if strings.Contains(l, "{") {
  412. c++
  413. if !strings.Contains(l, "=") {
  414. return nil, fmt.Errorf("realm configuration line invalid: %s", l)
  415. }
  416. if c == 1 {
  417. start = i
  418. p := strings.Split(l, "=")
  419. name = strings.TrimSpace(p[0])
  420. }
  421. }
  422. if strings.Contains(l, "}") {
  423. if c < 1 {
  424. // but not started a block!!!
  425. return nil, errors.New("invalid Realms section in configuration")
  426. }
  427. c--
  428. if c == 0 {
  429. var r Realm
  430. e := r.parseLines(name, lines[start+1:i])
  431. if e != nil {
  432. if _, ok := e.(UnsupportedDirective); !ok {
  433. err = e
  434. return
  435. }
  436. err = e
  437. }
  438. realms = append(realms, r)
  439. }
  440. }
  441. }
  442. return
  443. }
  444. // DomainRealm maps the domains to realms representing the [domain_realm] section of the configuration.
  445. type DomainRealm map[string]string
  446. // Parse the lines of the [domain_realm] section of the configuration and add to the mapping.
  447. func (d *DomainRealm) parseLines(lines []string) error {
  448. for _, line := range lines {
  449. //Remove comments after the values
  450. if idx := strings.IndexAny(line, "#;"); idx != -1 {
  451. line = line[:idx]
  452. }
  453. if strings.TrimSpace(line) == "" {
  454. continue
  455. }
  456. if !strings.Contains(line, "=") {
  457. return InvalidErrorf("realm line (%s)", line)
  458. }
  459. p := strings.Split(line, "=")
  460. domain := strings.TrimSpace(strings.ToLower(p[0]))
  461. realm := strings.TrimSpace(p[1])
  462. d.addMapping(domain, realm)
  463. }
  464. return nil
  465. }
  466. // Add a domain to realm mapping.
  467. func (d *DomainRealm) addMapping(domain, realm string) {
  468. (*d)[domain] = realm
  469. }
  470. // Delete a domain to realm mapping.
  471. func (d *DomainRealm) deleteMapping(domain, realm string) {
  472. delete(*d, domain)
  473. }
  474. // ResolveRealm resolves the kerberos realm for the specified domain name from the domain to realm mapping.
  475. // The most specific mapping is returned.
  476. func (c *Config) ResolveRealm(domainName string) string {
  477. domainName = strings.TrimSuffix(domainName, ".")
  478. // Try to match the entire hostname first
  479. if r, ok := c.DomainRealm[domainName]; ok {
  480. return r
  481. }
  482. // Try to match all DNS domain parts
  483. periods := strings.Count(domainName, ".") + 1
  484. for i := 2; i <= periods; i++ {
  485. z := strings.SplitN(domainName, ".", i)
  486. if r, ok := c.DomainRealm["."+z[len(z)-1]]; ok {
  487. return r
  488. }
  489. }
  490. return c.LibDefaults.DefaultRealm
  491. }
  492. // Load the KRB5 configuration from the specified file path.
  493. func Load(cfgPath string) (*Config, error) {
  494. fh, err := os.Open(cfgPath)
  495. if err != nil {
  496. return nil, errors.New("configuration file could not be opened: " + cfgPath + " " + err.Error())
  497. }
  498. defer fh.Close()
  499. scanner := bufio.NewScanner(fh)
  500. return NewFromScanner(scanner)
  501. }
  502. // NewFromString creates a new Config struct from a string.
  503. func NewFromString(s string) (*Config, error) {
  504. reader := strings.NewReader(s)
  505. return NewFromReader(reader)
  506. }
  507. // NewFromReader creates a new Config struct from an io.Reader.
  508. func NewFromReader(r io.Reader) (*Config, error) {
  509. scanner := bufio.NewScanner(r)
  510. return NewFromScanner(scanner)
  511. }
  512. // NewFromScanner creates a new Config struct from a bufio.Scanner.
  513. func NewFromScanner(scanner *bufio.Scanner) (*Config, error) {
  514. c := New()
  515. var e error
  516. sections := make(map[int]string)
  517. var sectionLineNum []int
  518. var lines []string
  519. for scanner.Scan() {
  520. // Skip comments and blank lines
  521. if matched, _ := regexp.MatchString(`^\s*(#|;|\n)`, scanner.Text()); matched {
  522. continue
  523. }
  524. if matched, _ := regexp.MatchString(`^\s*\[libdefaults\]\s*`, scanner.Text()); matched {
  525. sections[len(lines)] = "libdefaults"
  526. sectionLineNum = append(sectionLineNum, len(lines))
  527. continue
  528. }
  529. if matched, _ := regexp.MatchString(`^\s*\[realms\]\s*`, scanner.Text()); matched {
  530. sections[len(lines)] = "realms"
  531. sectionLineNum = append(sectionLineNum, len(lines))
  532. continue
  533. }
  534. if matched, _ := regexp.MatchString(`^\s*\[domain_realm\]\s*`, scanner.Text()); matched {
  535. sections[len(lines)] = "domain_realm"
  536. sectionLineNum = append(sectionLineNum, len(lines))
  537. continue
  538. }
  539. if matched, _ := regexp.MatchString(`^\s*\[.*\]\s*`, scanner.Text()); matched {
  540. sections[len(lines)] = "unknown_section"
  541. sectionLineNum = append(sectionLineNum, len(lines))
  542. continue
  543. }
  544. lines = append(lines, scanner.Text())
  545. }
  546. for i, start := range sectionLineNum {
  547. var end int
  548. if i+1 >= len(sectionLineNum) {
  549. end = len(lines)
  550. } else {
  551. end = sectionLineNum[i+1]
  552. }
  553. switch section := sections[start]; section {
  554. case "libdefaults":
  555. err := c.LibDefaults.parseLines(lines[start:end])
  556. if err != nil {
  557. if _, ok := err.(UnsupportedDirective); !ok {
  558. return nil, fmt.Errorf("error processing libdefaults section: %v", err)
  559. }
  560. e = err
  561. }
  562. case "realms":
  563. realms, err := parseRealms(lines[start:end])
  564. if err != nil {
  565. if _, ok := err.(UnsupportedDirective); !ok {
  566. return nil, fmt.Errorf("error processing realms section: %v", err)
  567. }
  568. e = err
  569. }
  570. c.Realms = realms
  571. case "domain_realm":
  572. err := c.DomainRealm.parseLines(lines[start:end])
  573. if err != nil {
  574. if _, ok := err.(UnsupportedDirective); !ok {
  575. return nil, fmt.Errorf("error processing domaain_realm section: %v", err)
  576. }
  577. e = err
  578. }
  579. }
  580. }
  581. return c, e
  582. }
  583. // Parse a space delimited list of ETypes into a list of EType numbers optionally filtering out weak ETypes.
  584. func parseETypes(s []string, w bool) []int32 {
  585. var eti []int32
  586. for _, et := range s {
  587. if !w {
  588. var weak bool
  589. for _, wet := range strings.Fields(WeakETypeList) {
  590. if et == wet {
  591. weak = true
  592. break
  593. }
  594. }
  595. if weak {
  596. continue
  597. }
  598. }
  599. i := etypeID.EtypeSupported(et)
  600. if i != 0 {
  601. eti = append(eti, i)
  602. }
  603. }
  604. return eti
  605. }
  606. // Parse a time duration string in the configuration to a golang time.Duration.
  607. func parseDuration(s string) (time.Duration, error) {
  608. s = strings.Replace(strings.TrimSpace(s), " ", "", -1)
  609. // handle Nd[NmNs]
  610. if strings.Contains(s, "d") {
  611. ds := strings.SplitN(s, "d", 2)
  612. dn, err := strconv.ParseUint(ds[0], 10, 32)
  613. if err != nil {
  614. return time.Duration(0), errors.New("invalid time duration")
  615. }
  616. d := time.Duration(dn*24) * time.Hour
  617. if ds[1] != "" {
  618. dp, err := time.ParseDuration(ds[1])
  619. if err != nil {
  620. return time.Duration(0), errors.New("invalid time duration")
  621. }
  622. d = d + dp
  623. }
  624. return d, nil
  625. }
  626. // handle Nm[Ns]
  627. d, err := time.ParseDuration(s)
  628. if err == nil {
  629. return d, nil
  630. }
  631. // handle N
  632. v, err := strconv.ParseUint(s, 10, 32)
  633. if err == nil && v > 0 {
  634. return time.Duration(v) * time.Second, nil
  635. }
  636. // handle h:m[:s]
  637. if strings.Contains(s, ":") {
  638. t := strings.Split(s, ":")
  639. if 2 > len(t) || len(t) > 3 {
  640. return time.Duration(0), errors.New("invalid time duration value")
  641. }
  642. var i []int
  643. for _, n := range t {
  644. j, err := strconv.ParseInt(n, 10, 16)
  645. if err != nil {
  646. return time.Duration(0), errors.New("invalid time duration value")
  647. }
  648. i = append(i, int(j))
  649. }
  650. d := time.Duration(i[0])*time.Hour + time.Duration(i[1])*time.Minute
  651. if len(i) == 3 {
  652. d = d + time.Duration(i[2])*time.Second
  653. }
  654. return d, nil
  655. }
  656. return time.Duration(0), errors.New("invalid time duration value")
  657. }
  658. // Parse possible boolean values to golang bool.
  659. func parseBoolean(s string) (bool, error) {
  660. s = strings.TrimSpace(s)
  661. v, err := strconv.ParseBool(s)
  662. if err == nil {
  663. return v, nil
  664. }
  665. switch strings.ToLower(s) {
  666. case "yes":
  667. return true, nil
  668. case "y":
  669. return true, nil
  670. case "no":
  671. return false, nil
  672. case "n":
  673. return false, nil
  674. }
  675. return false, errors.New("invalid boolean value")
  676. }
  677. // Parse array of strings but stop if an asterisk is placed at the end of a line.
  678. func appendUntilFinal(s *[]string, value string, final *bool) {
  679. if *final {
  680. return
  681. }
  682. if last := len(value) - 1; last >= 0 && value[last] == '*' {
  683. *final = true
  684. value = value[:len(value)-1]
  685. }
  686. *s = append(*s, value)
  687. }
  688. // JSON return details of the config in a JSON format.
  689. func (c *Config) JSON() (string, error) {
  690. b, err := json.MarshalIndent(c, "", " ")
  691. if err != nil {
  692. return "", err
  693. }
  694. return string(b), nil
  695. }