ccache.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. package credentials
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "errors"
  6. "io/ioutil"
  7. "strings"
  8. "time"
  9. "unsafe"
  10. "github.com/jcmturner/gofork/encoding/asn1"
  11. "gopkg.in/jcmturner/gokrb5.v7/types"
  12. )
  13. const (
  14. headerFieldTagKDCOffset = 1
  15. )
  16. // The first byte of the file always has the value 5.
  17. // The value of the second byte contains the version number (1 through 4)
  18. // Versions 1 and 2 of the file format use native byte order for integer representations.
  19. // Versions 3 and 4 always use big-endian byte order
  20. // After the two-byte version indicator, the file has three parts:
  21. // 1) the header (in version 4 only)
  22. // 2) the default principal name
  23. // 3) a sequence of credentials
  24. // CCache is the file credentials cache as define here: https://web.mit.edu/kerberos/krb5-latest/doc/formats/ccache_file_format.html
  25. type CCache struct {
  26. Version uint8
  27. Header header
  28. DefaultPrincipal principal
  29. Credentials []*Credential
  30. Path string
  31. }
  32. type header struct {
  33. length uint16
  34. fields []headerField
  35. }
  36. type headerField struct {
  37. tag uint16
  38. length uint16
  39. value []byte
  40. }
  41. // Credential cache entry principal struct.
  42. type principal struct {
  43. Realm string
  44. PrincipalName types.PrincipalName
  45. }
  46. // Credential holds a Kerberos client's ccache credential information.
  47. type Credential struct {
  48. Client principal
  49. Server principal
  50. Key types.EncryptionKey
  51. AuthTime time.Time
  52. StartTime time.Time
  53. EndTime time.Time
  54. RenewTill time.Time
  55. IsSKey bool
  56. TicketFlags asn1.BitString
  57. Addresses []types.HostAddress
  58. AuthData []types.AuthorizationDataEntry
  59. Ticket []byte
  60. SecondTicket []byte
  61. }
  62. // LoadCCache loads a credential cache file into a CCache type.
  63. func LoadCCache(cpath string) (*CCache, error) {
  64. c := new(CCache)
  65. b, err := ioutil.ReadFile(cpath)
  66. if err != nil {
  67. return c, err
  68. }
  69. err = c.Unmarshal(b)
  70. return c, err
  71. }
  72. // Unmarshal a byte slice of credential cache data into CCache type.
  73. func (c *CCache) Unmarshal(b []byte) error {
  74. p := 0
  75. //The first byte of the file always has the value 5
  76. if int8(b[p]) != 5 {
  77. return errors.New("Invalid credential cache data. First byte does not equal 5")
  78. }
  79. p++
  80. //Get credential cache version
  81. //The second byte contains the version number (1 to 4)
  82. c.Version = b[p]
  83. if c.Version < 1 || c.Version > 4 {
  84. return errors.New("Invalid credential cache data. Keytab version is not within 1 to 4")
  85. }
  86. p++
  87. //Version 1 or 2 of the file format uses native byte order for integer representations. Versions 3 & 4 always uses big-endian byte order
  88. var endian binary.ByteOrder
  89. endian = binary.BigEndian
  90. if (c.Version == 1 || c.Version == 2) && isNativeEndianLittle() {
  91. endian = binary.LittleEndian
  92. }
  93. if c.Version == 4 {
  94. err := parseHeader(b, &p, c, &endian)
  95. if err != nil {
  96. return err
  97. }
  98. }
  99. c.DefaultPrincipal = parsePrincipal(b, &p, c, &endian)
  100. for p < len(b) {
  101. cred, err := parseCredential(b, &p, c, &endian)
  102. if err != nil {
  103. return err
  104. }
  105. c.Credentials = append(c.Credentials, cred)
  106. }
  107. return nil
  108. }
  109. func parseHeader(b []byte, p *int, c *CCache, e *binary.ByteOrder) error {
  110. if c.Version != 4 {
  111. return errors.New("Credentials cache version is not 4 so there is no header to parse.")
  112. }
  113. h := header{}
  114. h.length = uint16(readInt16(b, p, e))
  115. for *p <= int(h.length) {
  116. f := headerField{}
  117. f.tag = uint16(readInt16(b, p, e))
  118. f.length = uint16(readInt16(b, p, e))
  119. f.value = b[*p : *p+int(f.length)]
  120. *p += int(f.length)
  121. if !f.valid() {
  122. return errors.New("Invalid credential cache header found")
  123. }
  124. h.fields = append(h.fields, f)
  125. }
  126. c.Header = h
  127. return nil
  128. }
  129. // Parse the Keytab bytes of a principal into a Keytab entry's principal.
  130. func parsePrincipal(b []byte, p *int, c *CCache, e *binary.ByteOrder) (princ principal) {
  131. if c.Version != 1 {
  132. //Name Type is omitted in version 1
  133. princ.PrincipalName.NameType = readInt32(b, p, e)
  134. }
  135. nc := int(readInt32(b, p, e))
  136. if c.Version == 1 {
  137. //In version 1 the number of components includes the realm. Minus 1 to make consistent with version 2
  138. nc--
  139. }
  140. lenRealm := readInt32(b, p, e)
  141. princ.Realm = string(readBytes(b, p, int(lenRealm), e))
  142. for i := 0; i < nc; i++ {
  143. l := readInt32(b, p, e)
  144. princ.PrincipalName.NameString = append(princ.PrincipalName.NameString, string(readBytes(b, p, int(l), e)))
  145. }
  146. return princ
  147. }
  148. func parseCredential(b []byte, p *int, c *CCache, e *binary.ByteOrder) (cred *Credential, err error) {
  149. cred = new(Credential)
  150. cred.Client = parsePrincipal(b, p, c, e)
  151. cred.Server = parsePrincipal(b, p, c, e)
  152. key := types.EncryptionKey{}
  153. key.KeyType = int32(readInt16(b, p, e))
  154. if c.Version == 3 {
  155. //repeated twice in version 3
  156. key.KeyType = int32(readInt16(b, p, e))
  157. }
  158. key.KeyValue = readData(b, p, e)
  159. cred.Key = key
  160. cred.AuthTime = readTimestamp(b, p, e)
  161. cred.StartTime = readTimestamp(b, p, e)
  162. cred.EndTime = readTimestamp(b, p, e)
  163. cred.RenewTill = readTimestamp(b, p, e)
  164. if ik := readInt8(b, p, e); ik == 0 {
  165. cred.IsSKey = false
  166. } else {
  167. cred.IsSKey = true
  168. }
  169. cred.TicketFlags = types.NewKrbFlags()
  170. cred.TicketFlags.Bytes = readBytes(b, p, 4, e)
  171. l := int(readInt32(b, p, e))
  172. cred.Addresses = make([]types.HostAddress, l, l)
  173. for i := range cred.Addresses {
  174. cred.Addresses[i] = readAddress(b, p, e)
  175. }
  176. l = int(readInt32(b, p, e))
  177. cred.AuthData = make([]types.AuthorizationDataEntry, l, l)
  178. for i := range cred.AuthData {
  179. cred.AuthData[i] = readAuthDataEntry(b, p, e)
  180. }
  181. cred.Ticket = readData(b, p, e)
  182. cred.SecondTicket = readData(b, p, e)
  183. return
  184. }
  185. // GetClientPrincipalName returns a PrincipalName type for the client the credentials cache is for.
  186. func (c *CCache) GetClientPrincipalName() types.PrincipalName {
  187. return c.DefaultPrincipal.PrincipalName
  188. }
  189. // GetClientRealm returns the reals of the client the credentials cache is for.
  190. func (c *CCache) GetClientRealm() string {
  191. return c.DefaultPrincipal.Realm
  192. }
  193. // GetClientCredentials returns a Credentials object representing the client of the credentials cache.
  194. func (c *CCache) GetClientCredentials() *Credentials {
  195. return &Credentials{
  196. username: c.DefaultPrincipal.PrincipalName.PrincipalNameString(),
  197. realm: c.GetClientRealm(),
  198. cname: c.DefaultPrincipal.PrincipalName,
  199. }
  200. }
  201. // Contains tests if the cache contains a credential for the provided server PrincipalName
  202. func (c *CCache) Contains(p types.PrincipalName) bool {
  203. for _, cred := range c.Credentials {
  204. if cred.Server.PrincipalName.Equal(p) {
  205. return true
  206. }
  207. }
  208. return false
  209. }
  210. // GetEntry returns a specific credential for the PrincipalName provided.
  211. func (c *CCache) GetEntry(p types.PrincipalName) (*Credential, bool) {
  212. cred := new(Credential)
  213. var found bool
  214. for i := range c.Credentials {
  215. if c.Credentials[i].Server.PrincipalName.Equal(p) {
  216. cred = c.Credentials[i]
  217. found = true
  218. break
  219. }
  220. }
  221. if !found {
  222. return cred, false
  223. }
  224. return cred, true
  225. }
  226. // GetEntries filters out configuration entries an returns a slice of credentials.
  227. func (c *CCache) GetEntries() []*Credential {
  228. creds := make([]*Credential, 0)
  229. for _, cred := range c.Credentials {
  230. // Filter out configuration entries
  231. if strings.HasPrefix(cred.Server.Realm, "X-CACHECONF") {
  232. continue
  233. }
  234. creds = append(creds, cred)
  235. }
  236. return creds
  237. }
  238. func (h *headerField) valid() bool {
  239. // At this time there is only one defined header field.
  240. // Its tag value is 1, its length is always 8.
  241. // Its contents are two 32-bit integers giving the seconds and microseconds
  242. // of the time offset of the KDC relative to the client.
  243. // Adding this offset to the current time on the client should give the current time on the KDC, if that offset has not changed since the initial authentication.
  244. // Done as a switch in case other tag values are added in the future.
  245. switch h.tag {
  246. case headerFieldTagKDCOffset:
  247. if h.length != 8 || len(h.value) != 8 {
  248. return false
  249. }
  250. return true
  251. }
  252. return false
  253. }
  254. func readData(b []byte, p *int, e *binary.ByteOrder) []byte {
  255. l := readInt32(b, p, e)
  256. return readBytes(b, p, int(l), e)
  257. }
  258. func readAddress(b []byte, p *int, e *binary.ByteOrder) types.HostAddress {
  259. a := types.HostAddress{}
  260. a.AddrType = int32(readInt16(b, p, e))
  261. a.Address = readData(b, p, e)
  262. return a
  263. }
  264. func readAuthDataEntry(b []byte, p *int, e *binary.ByteOrder) types.AuthorizationDataEntry {
  265. a := types.AuthorizationDataEntry{}
  266. a.ADType = int32(readInt16(b, p, e))
  267. a.ADData = readData(b, p, e)
  268. return a
  269. }
  270. // Read bytes representing a timestamp.
  271. func readTimestamp(b []byte, p *int, e *binary.ByteOrder) time.Time {
  272. return time.Unix(int64(readInt32(b, p, e)), 0)
  273. }
  274. // Read bytes representing an eight bit integer.
  275. func readInt8(b []byte, p *int, e *binary.ByteOrder) (i int8) {
  276. buf := bytes.NewBuffer(b[*p : *p+1])
  277. binary.Read(buf, *e, &i)
  278. *p++
  279. return
  280. }
  281. // Read bytes representing a sixteen bit integer.
  282. func readInt16(b []byte, p *int, e *binary.ByteOrder) (i int16) {
  283. buf := bytes.NewBuffer(b[*p : *p+2])
  284. binary.Read(buf, *e, &i)
  285. *p += 2
  286. return
  287. }
  288. // Read bytes representing a thirty two bit integer.
  289. func readInt32(b []byte, p *int, e *binary.ByteOrder) (i int32) {
  290. buf := bytes.NewBuffer(b[*p : *p+4])
  291. binary.Read(buf, *e, &i)
  292. *p += 4
  293. return
  294. }
  295. func readBytes(b []byte, p *int, s int, e *binary.ByteOrder) []byte {
  296. buf := bytes.NewBuffer(b[*p : *p+s])
  297. r := make([]byte, s)
  298. binary.Read(buf, *e, &r)
  299. *p += s
  300. return r
  301. }
  302. func isNativeEndianLittle() bool {
  303. var x = 0x012345678
  304. var p = unsafe.Pointer(&x)
  305. var bp = (*[4]byte)(p)
  306. var endian bool
  307. if 0x01 == bp[0] {
  308. endian = false
  309. } else if (0x78 & 0xff) == (bp[0] & 0xff) {
  310. endian = true
  311. } else {
  312. // Default to big endian
  313. endian = false
  314. }
  315. return endian
  316. }