# -*- coding: binary -*-

module Msf
  class Exploit
    class Remote
      module Kerberos
        module Client
          # Methods for processing TGS responses.
          module TgsResponse

            # Extracts the Kerberos credentials, building a MIT Cache Credential,
            # from a Kerberos TGS response.
            #
            # @param res [Rex::Proto::Kerberos::Model::KdcResponse]
            # @param key [String]
            # @param msg_type [Rex::Proto::Kerberos::Crypto::KeyUsage]
            # @return [Rex::Proto::Kerberos::Model::EncKdcResponse]
            # @see Rex::Proto::Kerberos::Model::EncKdcResponse
            # @see Rex::Proto::Kerberos::Model::EncKdcResponse.decode
            # @see Rex::Proto::Kerberos::CredentialCache::Krb5Ccache
            def decrypt_kdc_tgs_rep_enc_part(res, key, msg_type:)
              decrypt_res = res.enc_part.decrypt_asn1(key, msg_type)
              Rex::Proto::Kerberos::Model::EncKdcResponse.decode(decrypt_res)
            end

            # Extracts the Kerberos credentials, building a MIT Cache Credential,
            # from a Kerberos TGS response.
            #
            # @param res [Rex::Proto::Kerberos::Model::KdcResponse]
            # @param key [String]
            # @return [Rex::Proto::Kerberos::CredentialCache::Krb5Ccache]
            # @see Rex::Proto::Kerberos::Model::EncKdcResponse
            # @see Rex::Proto::Kerberos::Model::EncKdcResponse.decode
            # @see Msf::Kerberos::Client::CacheCredential
            # @see Rex::Proto::Kerberos::CredentialCache::Cache
            def extract_kerb_creds(res, key, msg_type: Rex::Proto::Kerberos::Crypto::KeyUsage::TGS_REP_ENCPART_AUTHENTICATOR_SUB_KEY)
              enc_res = decrypt_kdc_tgs_rep_enc_part(res, key, msg_type: msg_type)

              Rex::Proto::Kerberos::CredentialCache::Krb5Ccache.from_responses(res, enc_res)
            end
          end
        end
      end
    end
  end
end
