Ticket.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. package messages
  2. import (
  3. "fmt"
  4. "log"
  5. "time"
  6. "github.com/jcmturner/gofork/encoding/asn1"
  7. "github.com/jcmturner/gokrb5/v8/asn1tools"
  8. "github.com/jcmturner/gokrb5/v8/crypto"
  9. "github.com/jcmturner/gokrb5/v8/iana"
  10. "github.com/jcmturner/gokrb5/v8/iana/adtype"
  11. "github.com/jcmturner/gokrb5/v8/iana/asnAppTag"
  12. "github.com/jcmturner/gokrb5/v8/iana/errorcode"
  13. "github.com/jcmturner/gokrb5/v8/iana/flags"
  14. "github.com/jcmturner/gokrb5/v8/iana/keyusage"
  15. "github.com/jcmturner/gokrb5/v8/keytab"
  16. "github.com/jcmturner/gokrb5/v8/krberror"
  17. "github.com/jcmturner/gokrb5/v8/pac"
  18. "github.com/jcmturner/gokrb5/v8/types"
  19. )
  20. // Reference: https://www.ietf.org/rfc/rfc4120.txt
  21. // Section: 5.3
  22. // Ticket implements the Kerberos ticket.
  23. type Ticket struct {
  24. TktVNO int `asn1:"explicit,tag:0"`
  25. Realm string `asn1:"generalstring,explicit,tag:1"`
  26. SName types.PrincipalName `asn1:"explicit,tag:2"`
  27. EncPart types.EncryptedData `asn1:"explicit,tag:3"`
  28. DecryptedEncPart EncTicketPart `asn1:"optional"` // Not part of ASN1 bytes so marked as optional so unmarshalling works
  29. }
  30. // EncTicketPart is the encrypted part of the Ticket.
  31. type EncTicketPart struct {
  32. Flags asn1.BitString `asn1:"explicit,tag:0"`
  33. Key types.EncryptionKey `asn1:"explicit,tag:1"`
  34. CRealm string `asn1:"generalstring,explicit,tag:2"`
  35. CName types.PrincipalName `asn1:"explicit,tag:3"`
  36. Transited TransitedEncoding `asn1:"explicit,tag:4"`
  37. AuthTime time.Time `asn1:"generalized,explicit,tag:5"`
  38. StartTime time.Time `asn1:"generalized,explicit,optional,tag:6"`
  39. EndTime time.Time `asn1:"generalized,explicit,tag:7"`
  40. RenewTill time.Time `asn1:"generalized,explicit,optional,tag:8"`
  41. CAddr types.HostAddresses `asn1:"explicit,optional,tag:9"`
  42. AuthorizationData types.AuthorizationData `asn1:"explicit,optional,tag:10"`
  43. }
  44. // TransitedEncoding part of the ticket's encrypted part.
  45. type TransitedEncoding struct {
  46. TRType int32 `asn1:"explicit,tag:0"`
  47. Contents []byte `asn1:"explicit,tag:1"`
  48. }
  49. // NewTicket creates a new Ticket instance.
  50. func NewTicket(cname types.PrincipalName, crealm string, sname types.PrincipalName, srealm string, flags asn1.BitString, sktab *keytab.Keytab, eTypeID int32, kvno int, authTime, startTime, endTime, renewTill time.Time) (Ticket, types.EncryptionKey, error) {
  51. etype, err := crypto.GetEtype(eTypeID)
  52. if err != nil {
  53. return Ticket{}, types.EncryptionKey{}, krberror.Errorf(err, krberror.EncryptingError, "error getting etype for new ticket")
  54. }
  55. sessionKey, err := types.GenerateEncryptionKey(etype)
  56. if err != nil {
  57. return Ticket{}, types.EncryptionKey{}, krberror.Errorf(err, krberror.EncryptingError, "error generating session key")
  58. }
  59. etp := EncTicketPart{
  60. Flags: flags,
  61. Key: sessionKey,
  62. CRealm: crealm,
  63. CName: cname,
  64. Transited: TransitedEncoding{},
  65. AuthTime: authTime,
  66. StartTime: startTime,
  67. EndTime: endTime,
  68. RenewTill: renewTill,
  69. }
  70. b, err := asn1.Marshal(etp)
  71. if err != nil {
  72. return Ticket{}, types.EncryptionKey{}, krberror.Errorf(err, krberror.EncodingError, "error marshalling ticket encpart")
  73. }
  74. b = asn1tools.AddASNAppTag(b, asnAppTag.EncTicketPart)
  75. skey, _, err := sktab.GetEncryptionKey(sname, srealm, kvno, eTypeID)
  76. if err != nil {
  77. return Ticket{}, types.EncryptionKey{}, krberror.Errorf(err, krberror.EncryptingError, "error getting encryption key for new ticket")
  78. }
  79. ed, err := crypto.GetEncryptedData(b, skey, keyusage.KDC_REP_TICKET, kvno)
  80. if err != nil {
  81. return Ticket{}, types.EncryptionKey{}, krberror.Errorf(err, krberror.EncryptingError, "error encrypting ticket encpart")
  82. }
  83. tkt := Ticket{
  84. TktVNO: iana.PVNO,
  85. Realm: srealm,
  86. SName: sname,
  87. EncPart: ed,
  88. }
  89. return tkt, sessionKey, nil
  90. }
  91. // Unmarshal bytes b into a Ticket struct.
  92. func (t *Ticket) Unmarshal(b []byte) error {
  93. _, err := asn1.UnmarshalWithParams(b, t, fmt.Sprintf("application,explicit,tag:%d", asnAppTag.Ticket))
  94. return err
  95. }
  96. // Marshal the Ticket.
  97. func (t *Ticket) Marshal() ([]byte, error) {
  98. b, err := asn1.Marshal(*t)
  99. if err != nil {
  100. return nil, err
  101. }
  102. b = asn1tools.AddASNAppTag(b, asnAppTag.Ticket)
  103. return b, nil
  104. }
  105. // Unmarshal bytes b into the EncTicketPart struct.
  106. func (t *EncTicketPart) Unmarshal(b []byte) error {
  107. _, err := asn1.UnmarshalWithParams(b, t, fmt.Sprintf("application,explicit,tag:%d", asnAppTag.EncTicketPart))
  108. return err
  109. }
  110. // unmarshalTicket returns a ticket from the bytes provided.
  111. func unmarshalTicket(b []byte) (t Ticket, err error) {
  112. err = t.Unmarshal(b)
  113. return
  114. }
  115. // UnmarshalTicketsSequence returns a slice of Tickets from a raw ASN1 value.
  116. func unmarshalTicketsSequence(in asn1.RawValue) ([]Ticket, error) {
  117. //This is a workaround to a asn1 decoding issue in golang - https://github.com/golang/go/issues/17321. It's not pretty I'm afraid
  118. //We pull out raw values from the larger raw value (that is actually the data of the sequence of raw values) and track our position moving along the data.
  119. b := in.Bytes
  120. // Ignore the head of the asn1 stream (1 byte for tag and those for the length) as this is what tells us its a sequence but we're handling it ourselves
  121. p := 1 + asn1tools.GetNumberBytesInLengthHeader(in.Bytes)
  122. var tkts []Ticket
  123. var raw asn1.RawValue
  124. for p < (len(b)) {
  125. _, err := asn1.UnmarshalWithParams(b[p:], &raw, fmt.Sprintf("application,tag:%d", asnAppTag.Ticket))
  126. if err != nil {
  127. return nil, fmt.Errorf("unmarshaling sequence of tickets failed getting length of ticket: %v", err)
  128. }
  129. t, err := unmarshalTicket(b[p:])
  130. if err != nil {
  131. return nil, fmt.Errorf("unmarshaling sequence of tickets failed: %v", err)
  132. }
  133. p += len(raw.FullBytes)
  134. tkts = append(tkts, t)
  135. }
  136. MarshalTicketSequence(tkts)
  137. return tkts, nil
  138. }
  139. // MarshalTicketSequence marshals a slice of Tickets returning an ASN1 raw value containing the ticket sequence.
  140. func MarshalTicketSequence(tkts []Ticket) (asn1.RawValue, error) {
  141. raw := asn1.RawValue{
  142. Class: 2,
  143. IsCompound: true,
  144. }
  145. if len(tkts) < 1 {
  146. // There are no tickets to marshal
  147. return raw, nil
  148. }
  149. var btkts []byte
  150. for i, t := range tkts {
  151. b, err := t.Marshal()
  152. if err != nil {
  153. return raw, fmt.Errorf("error marshaling ticket number %d in sequence of tickets", i+1)
  154. }
  155. btkts = append(btkts, b...)
  156. }
  157. // The ASN1 wrapping consists of 2 bytes:
  158. // 1st byte -> Identifier Octet - In this case an OCTET STRING (ASN TAG
  159. // 2nd byte -> The length (this will be the size indicated in the input bytes + 2 for the additional bytes we add here.
  160. // Application Tag:
  161. //| Byte: | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 |
  162. //| Value: | 0 | 1 | 1 | From the RFC spec 4120 |
  163. //| Explanation | Defined by the ASN1 encoding rules for an application tag | A value of 1 indicates a constructed type | The ASN Application tag value |
  164. btkts = append(asn1tools.MarshalLengthBytes(len(btkts)), btkts...)
  165. btkts = append([]byte{byte(32 + asn1.TagSequence)}, btkts...)
  166. raw.Bytes = btkts
  167. // If we need to create the full bytes then identifier octet is "context-specific" = 128 + "constructed" + 32 + the wrapping explicit tag (11)
  168. //fmt.Fprintf(os.Stderr, "mRaw fb: %v\n", raw.FullBytes)
  169. return raw, nil
  170. }
  171. // DecryptEncPart decrypts the encrypted part of the ticket.
  172. // The sname argument can be used to specify which service principal's key should be used to decrypt the ticket.
  173. // If nil is passed as the sname then the service principal specified within the ticket it used.
  174. func (t *Ticket) DecryptEncPart(keytab *keytab.Keytab, sname *types.PrincipalName) error {
  175. if sname == nil {
  176. sname = &t.SName
  177. }
  178. key, _, err := keytab.GetEncryptionKey(*sname, t.Realm, t.EncPart.KVNO, t.EncPart.EType)
  179. if err != nil {
  180. return NewKRBError(t.SName, t.Realm, errorcode.KRB_AP_ERR_NOKEY, fmt.Sprintf("Could not get key from keytab: %v", err))
  181. }
  182. return t.Decrypt(key)
  183. }
  184. // Decrypt decrypts the encrypted part of the ticket using the key provided.
  185. func (t *Ticket) Decrypt(key types.EncryptionKey) error {
  186. b, err := crypto.DecryptEncPart(t.EncPart, key, keyusage.KDC_REP_TICKET)
  187. if err != nil {
  188. return fmt.Errorf("error decrypting Ticket EncPart: %v", err)
  189. }
  190. var denc EncTicketPart
  191. err = denc.Unmarshal(b)
  192. if err != nil {
  193. return fmt.Errorf("error unmarshaling encrypted part: %v", err)
  194. }
  195. t.DecryptedEncPart = denc
  196. return nil
  197. }
  198. // GetPACType returns a Microsoft PAC that has been extracted from the ticket and processed.
  199. func (t *Ticket) GetPACType(keytab *keytab.Keytab, sname *types.PrincipalName, l *log.Logger) (bool, pac.PACType, error) {
  200. var isPAC bool
  201. for _, ad := range t.DecryptedEncPart.AuthorizationData {
  202. if ad.ADType == adtype.ADIfRelevant {
  203. var ad2 types.AuthorizationData
  204. err := ad2.Unmarshal(ad.ADData)
  205. if err != nil {
  206. l.Printf("PAC authorization data could not be unmarshaled: %v", err)
  207. continue
  208. }
  209. if ad2[0].ADType == adtype.ADWin2KPAC {
  210. isPAC = true
  211. var p pac.PACType
  212. err = p.Unmarshal(ad2[0].ADData)
  213. if err != nil {
  214. return isPAC, p, fmt.Errorf("error unmarshaling PAC: %v", err)
  215. }
  216. if sname == nil {
  217. sname = &t.SName
  218. }
  219. key, _, err := keytab.GetEncryptionKey(*sname, t.Realm, t.EncPart.KVNO, t.EncPart.EType)
  220. if err != nil {
  221. return isPAC, p, NewKRBError(t.SName, t.Realm, errorcode.KRB_AP_ERR_NOKEY, fmt.Sprintf("Could not get key from keytab: %v", err))
  222. }
  223. err = p.ProcessPACInfoBuffers(key, l)
  224. return isPAC, p, err
  225. }
  226. }
  227. }
  228. return isPAC, pac.PACType{}, nil
  229. }
  230. // Valid checks it the ticket is currently valid. Max duration passed endtime passed in as argument.
  231. func (t *Ticket) Valid(d time.Duration) (bool, error) {
  232. // Check for future tickets or invalid tickets
  233. time := time.Now().UTC()
  234. if t.DecryptedEncPart.StartTime.Sub(time) > d || types.IsFlagSet(&t.DecryptedEncPart.Flags, flags.Invalid) {
  235. return false, NewKRBError(t.SName, t.Realm, errorcode.KRB_AP_ERR_TKT_NYV, "service ticket provided is not yet valid")
  236. }
  237. // Check for expired ticket
  238. if time.Sub(t.DecryptedEncPart.EndTime) > d {
  239. return false, NewKRBError(t.SName, t.Realm, errorcode.KRB_AP_ERR_TKT_EXPIRED, "service ticket provided has expired")
  240. }
  241. return true, nil
  242. }