keytab.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. // Package keytab implements Kerberos keytabs: https://web.mit.edu/kerberos/krb5-devel/doc/formats/keytab_file_format.html.
  2. package keytab
  3. import (
  4. "bytes"
  5. "encoding/binary"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "time"
  11. "unsafe"
  12. "gopkg.in/jcmturner/gokrb5.v7/types"
  13. )
  14. const (
  15. keytabFirstByte byte = 05
  16. )
  17. // Keytab struct.
  18. type Keytab struct {
  19. version uint8
  20. Entries []entry
  21. }
  22. // Keytab entry struct.
  23. type entry struct {
  24. Principal principal
  25. Timestamp time.Time
  26. KVNO8 uint8
  27. Key types.EncryptionKey
  28. KVNO uint32
  29. }
  30. // Keytab entry principal struct.
  31. type principal struct {
  32. NumComponents int16
  33. Realm string
  34. Components []string
  35. NameType int32
  36. }
  37. // New creates new, empty Keytab type.
  38. func New() *Keytab {
  39. var e []entry
  40. return &Keytab{
  41. version: 0,
  42. Entries: e,
  43. }
  44. }
  45. // GetEncryptionKey returns the EncryptionKey from the Keytab for the newest entry with the required kvno, etype and matching principal.
  46. func (kt *Keytab) GetEncryptionKey(princName types.PrincipalName, realm string, kvno int, etype int32) (types.EncryptionKey, error) {
  47. //TODO (theme: KVNO from keytab) this function should return the kvno too
  48. var key types.EncryptionKey
  49. var t time.Time
  50. for _, k := range kt.Entries {
  51. if k.Principal.Realm == realm && len(k.Principal.Components) == len(princName.NameString) &&
  52. k.Key.KeyType == etype &&
  53. (k.KVNO == uint32(kvno) || kvno == 0) &&
  54. k.Timestamp.After(t) {
  55. p := true
  56. for i, n := range k.Principal.Components {
  57. if princName.NameString[i] != n {
  58. p = false
  59. break
  60. }
  61. }
  62. if p {
  63. key = k.Key
  64. t = k.Timestamp
  65. }
  66. }
  67. }
  68. if len(key.KeyValue) < 1 {
  69. return key, fmt.Errorf("matching key not found in keytab. Looking for %v realm: %v kvno: %v etype: %v", princName.NameString, realm, kvno, etype)
  70. }
  71. return key, nil
  72. }
  73. // Create a new Keytab entry.
  74. func newKeytabEntry() entry {
  75. var b []byte
  76. return entry{
  77. Principal: newPrincipal(),
  78. Timestamp: time.Time{},
  79. KVNO8: 0,
  80. Key: types.EncryptionKey{
  81. KeyType: 0,
  82. KeyValue: b,
  83. },
  84. KVNO: 0,
  85. }
  86. }
  87. // Create a new principal.
  88. func newPrincipal() principal {
  89. var c []string
  90. return principal{
  91. NumComponents: 0,
  92. Realm: "",
  93. Components: c,
  94. NameType: 0,
  95. }
  96. }
  97. // Load a Keytab file into a Keytab type.
  98. func Load(ktPath string) (*Keytab, error) {
  99. kt := new(Keytab)
  100. b, err := ioutil.ReadFile(ktPath)
  101. if err != nil {
  102. return kt, err
  103. }
  104. err = kt.Unmarshal(b)
  105. return kt, err
  106. }
  107. // Marshal keytab into byte slice
  108. func (kt *Keytab) Marshal() ([]byte, error) {
  109. b := []byte{keytabFirstByte, kt.version}
  110. for _, e := range kt.Entries {
  111. eb, err := e.marshal(int(kt.version))
  112. if err != nil {
  113. return b, err
  114. }
  115. b = append(b, eb...)
  116. }
  117. return b, nil
  118. }
  119. // Write the keytab bytes to io.Writer.
  120. // Returns the number of bytes written
  121. func (kt *Keytab) Write(w io.Writer) (int, error) {
  122. b, err := kt.Marshal()
  123. if err != nil {
  124. return 0, fmt.Errorf("error marshaling keytab: %v", err)
  125. }
  126. return w.Write(b)
  127. }
  128. // Unmarshal byte slice of Keytab data into Keytab type.
  129. func (kt *Keytab) Unmarshal(b []byte) error {
  130. //The first byte of the file always has the value 5
  131. if b[0] != keytabFirstByte {
  132. return errors.New("invalid keytab data. First byte does not equal 5")
  133. }
  134. //Get keytab version
  135. //The 2nd byte contains the version number (1 or 2)
  136. kt.version = b[1]
  137. if kt.version != 1 && kt.version != 2 {
  138. return errors.New("invalid keytab data. Keytab version is neither 1 nor 2")
  139. }
  140. //Version 1 of the file format uses native byte order for integer representations. Version 2 always uses big-endian byte order
  141. var endian binary.ByteOrder
  142. endian = binary.BigEndian
  143. if kt.version == 1 && isNativeEndianLittle() {
  144. endian = binary.LittleEndian
  145. }
  146. /*
  147. After the two-byte version indicator, the file contains a sequence of signed 32-bit record lengths followed by key records or holes.
  148. A positive record length indicates a valid key entry whose size is equal to or less than the record length.
  149. A negative length indicates a zero-filled hole whose size is the inverse of the length.
  150. A length of 0 indicates the end of the file.
  151. */
  152. // n tracks position in the byte array
  153. n := 2
  154. l := readInt32(b, &n, &endian)
  155. for l != 0 {
  156. if l < 0 {
  157. //Zero padded so skip over
  158. l = l * -1
  159. n = n + int(l)
  160. } else {
  161. //fmt.Printf("Bytes for entry: %v\n", b[n:n+int(l)])
  162. eb := b[n : n+int(l)]
  163. n = n + int(l)
  164. ke := newKeytabEntry()
  165. // p keeps track as to where we are in the byte stream
  166. var p int
  167. parsePrincipal(eb, &p, kt, &ke, &endian)
  168. ke.Timestamp = readTimestamp(eb, &p, &endian)
  169. ke.KVNO8 = uint8(readInt8(eb, &p, &endian))
  170. ke.Key.KeyType = int32(readInt16(eb, &p, &endian))
  171. kl := int(readInt16(eb, &p, &endian))
  172. ke.Key.KeyValue = readBytes(eb, &p, kl, &endian)
  173. //The 32-bit key version overrides the 8-bit key version.
  174. // To determine if it is present, the implementation must check that at least 4 bytes remain in the record after the other fields are read,
  175. // and that the value of the 32-bit integer contained in those bytes is non-zero.
  176. if len(eb)-p >= 4 {
  177. // The 32-bit key may be present
  178. ke.KVNO = uint32(readInt32(eb, &p, &endian))
  179. }
  180. if ke.KVNO == 0 {
  181. // Handles if the value from the last 4 bytes was zero and also if there are not the 4 bytes present. Makes sense to put the same value here as KVNO8
  182. ke.KVNO = uint32(ke.KVNO8)
  183. }
  184. // Add the entry to the keytab
  185. kt.Entries = append(kt.Entries, ke)
  186. }
  187. // Check if there are still 4 bytes left to read
  188. if n > len(b) || len(b[n:]) < 4 {
  189. break
  190. }
  191. // Read the size of the next entry
  192. l = readInt32(b, &n, &endian)
  193. }
  194. return nil
  195. }
  196. func (e entry) marshal(v int) ([]byte, error) {
  197. var b []byte
  198. pb, err := e.Principal.marshal(v)
  199. if err != nil {
  200. return b, err
  201. }
  202. b = append(b, pb...)
  203. var endian binary.ByteOrder
  204. endian = binary.BigEndian
  205. if v == 1 && isNativeEndianLittle() {
  206. endian = binary.LittleEndian
  207. }
  208. t := make([]byte, 9)
  209. endian.PutUint32(t[0:4], uint32(e.Timestamp.Unix()))
  210. t[4] = e.KVNO8
  211. endian.PutUint16(t[5:7], uint16(e.Key.KeyType))
  212. endian.PutUint16(t[7:9], uint16(len(e.Key.KeyValue)))
  213. b = append(b, t...)
  214. buf := new(bytes.Buffer)
  215. err = binary.Write(buf, endian, e.Key.KeyValue)
  216. if err != nil {
  217. return b, err
  218. }
  219. b = append(b, buf.Bytes()...)
  220. t = make([]byte, 4)
  221. endian.PutUint32(t, e.KVNO)
  222. b = append(b, t...)
  223. // Add the length header
  224. t = make([]byte, 4)
  225. endian.PutUint32(t, uint32(len(b)))
  226. b = append(t, b...)
  227. return b, nil
  228. }
  229. // Parse the Keytab bytes of a principal into a Keytab entry's principal.
  230. func parsePrincipal(b []byte, p *int, kt *Keytab, ke *entry, e *binary.ByteOrder) error {
  231. ke.Principal.NumComponents = readInt16(b, p, e)
  232. if kt.version == 1 {
  233. //In version 1 the number of components includes the realm. Minus 1 to make consistent with version 2
  234. ke.Principal.NumComponents--
  235. }
  236. lenRealm := readInt16(b, p, e)
  237. ke.Principal.Realm = string(readBytes(b, p, int(lenRealm), e))
  238. for i := 0; i < int(ke.Principal.NumComponents); i++ {
  239. l := readInt16(b, p, e)
  240. ke.Principal.Components = append(ke.Principal.Components, string(readBytes(b, p, int(l), e)))
  241. }
  242. if kt.version != 1 {
  243. //Name Type is omitted in version 1
  244. ke.Principal.NameType = readInt32(b, p, e)
  245. }
  246. return nil
  247. }
  248. func (p principal) marshal(v int) ([]byte, error) {
  249. //var b []byte
  250. b := make([]byte, 2)
  251. var endian binary.ByteOrder
  252. endian = binary.BigEndian
  253. if v == 1 && isNativeEndianLittle() {
  254. endian = binary.LittleEndian
  255. }
  256. endian.PutUint16(b[0:], uint16(p.NumComponents))
  257. realm, err := marshalString(p.Realm, v)
  258. if err != nil {
  259. return b, err
  260. }
  261. b = append(b, realm...)
  262. for _, c := range p.Components {
  263. cb, err := marshalString(c, v)
  264. if err != nil {
  265. return b, err
  266. }
  267. b = append(b, cb...)
  268. }
  269. if v != 1 {
  270. t := make([]byte, 4)
  271. endian.PutUint32(t, uint32(p.NameType))
  272. b = append(b, t...)
  273. }
  274. return b, nil
  275. }
  276. func marshalString(s string, v int) ([]byte, error) {
  277. sb := []byte(s)
  278. b := make([]byte, 2)
  279. var endian binary.ByteOrder
  280. endian = binary.BigEndian
  281. if v == 1 && isNativeEndianLittle() {
  282. endian = binary.LittleEndian
  283. }
  284. endian.PutUint16(b[0:], uint16(len(sb)))
  285. buf := new(bytes.Buffer)
  286. err := binary.Write(buf, endian, sb)
  287. if err != nil {
  288. return b, err
  289. }
  290. b = append(b, buf.Bytes()...)
  291. return b, err
  292. }
  293. // Read bytes representing a timestamp.
  294. func readTimestamp(b []byte, p *int, e *binary.ByteOrder) time.Time {
  295. return time.Unix(int64(readInt32(b, p, e)), 0)
  296. }
  297. // Read bytes representing an eight bit integer.
  298. func readInt8(b []byte, p *int, e *binary.ByteOrder) (i int8) {
  299. buf := bytes.NewBuffer(b[*p : *p+1])
  300. binary.Read(buf, *e, &i)
  301. *p++
  302. return
  303. }
  304. // Read bytes representing a sixteen bit integer.
  305. func readInt16(b []byte, p *int, e *binary.ByteOrder) (i int16) {
  306. buf := bytes.NewBuffer(b[*p : *p+2])
  307. binary.Read(buf, *e, &i)
  308. *p += 2
  309. return
  310. }
  311. // Read bytes representing a thirty two bit integer.
  312. func readInt32(b []byte, p *int, e *binary.ByteOrder) (i int32) {
  313. buf := bytes.NewBuffer(b[*p : *p+4])
  314. binary.Read(buf, *e, &i)
  315. *p += 4
  316. return
  317. }
  318. func readBytes(b []byte, p *int, s int, e *binary.ByteOrder) []byte {
  319. buf := bytes.NewBuffer(b[*p : *p+s])
  320. r := make([]byte, s)
  321. binary.Read(buf, *e, &r)
  322. *p += s
  323. return r
  324. }
  325. func isNativeEndianLittle() bool {
  326. var x = 0x012345678
  327. var p = unsafe.Pointer(&x)
  328. var bp = (*[4]byte)(p)
  329. var endian bool
  330. if 0x01 == bp[0] {
  331. endian = false
  332. } else if (0x78 & 0xff) == (bp[0] & 0xff) {
  333. endian = true
  334. } else {
  335. // Default to big endian
  336. endian = false
  337. }
  338. return endian
  339. }