Ejemplo n.º 1
0
 public PatternDetails(XElement pattern)
 {
     Dbms  = XmlHelpers.GetAttributeValue <string>(pattern, "dbms", string.Empty);
     Value = pattern.Value;
 }
Ejemplo n.º 2
0
        public static async Task <bool> CouldHandleAsync(this Saml2Options options, string scheme, HttpContext context)
        {
            // Determine this is a valid request for our handler
            if (!context.Request.Path.StartsWithSegments(options.SPOptions.ModulePath, StringComparison.Ordinal))
            {
                return(false);
            }

            var idp = options.IdentityProviders.IsEmpty ? null : options.IdentityProviders.Default;

            if (idp == null)
            {
                return(false);
            }

            if (context.Request.Query["scheme"].FirstOrDefault() == scheme)
            {
                return(true);
            }

            // We need to pull out and parse the response or request SAML envelope
            XmlElement envelope = null;

            try
            {
                if (string.Equals(context.Request.Method, "POST", StringComparison.OrdinalIgnoreCase) &&
                    context.Request.HasFormContentType)
                {
                    string encodedMessage;
                    if (context.Request.Form.TryGetValue("SAMLResponse", out var response))
                    {
                        encodedMessage = response.FirstOrDefault();
                    }
                    else
                    {
                        encodedMessage = context.Request.Form["SAMLRequest"];
                    }
                    if (string.IsNullOrWhiteSpace(encodedMessage))
                    {
                        return(false);
                    }
                    envelope = XmlHelpers.XmlDocumentFromString(
                        Encoding.UTF8.GetString(Convert.FromBase64String(encodedMessage)))?.DocumentElement;
                }
                else if (string.Equals(context.Request.Method, "GET", StringComparison.OrdinalIgnoreCase))
                {
                    var encodedPayload = context.Request.Query["SAMLRequest"].FirstOrDefault() ??
                                         context.Request.Query["SAMLResponse"].FirstOrDefault();
                    try
                    {
                        var payload = Convert.FromBase64String(encodedPayload);
                        using var compressed         = new MemoryStream(payload);
                        using var decompressedStream = new DeflateStream(compressed, CompressionMode.Decompress, true);
                        using var deCompressed       = new MemoryStream();
                        await decompressedStream.CopyToAsync(deCompressed);

                        envelope = XmlHelpers.XmlDocumentFromString(
                            Encoding.UTF8.GetString(deCompressed.GetBuffer(), 0, (int)deCompressed.Length))?.DocumentElement;
                    }
                    catch (FormatException ex)
                    {
                        throw new FormatException($"\'{encodedPayload}\' is not a valid Base64 encoded string: {ex.Message}", ex);
                    }
                }
            }
            catch
            {
                return(false);
            }

            if (envelope == null)
            {
                return(false);
            }

            // Double check the entity Ids
            var entityId = envelope["Issuer", Saml2Namespaces.Saml2Name]?.InnerText.Trim();

            if (!string.Equals(entityId, idp.EntityId.Id, StringComparison.InvariantCultureIgnoreCase))
            {
                return(false);
            }

            if (options.SPOptions.WantAssertionsSigned)
            {
                var assertion         = envelope["Assertion", Saml2Namespaces.Saml2Name];
                var isAssertionSigned = assertion != null && XmlHelpers.IsSignedByAny(assertion, idp.SigningKeys,
                                                                                      options.SPOptions.ValidateCertificates, options.SPOptions.MinIncomingSigningAlgorithm);
                if (!isAssertionSigned)
                {
                    throw new Exception("Cannot verify SAML assertion signature.");
                }
            }

            return(true);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Read the supplied Xml and parse it into a response.
        /// </summary>
        /// <param name="xml">xml data.</param>
        /// <param name="expectedInResponseTo">The expected value of the
        /// InReplyTo parameter in the message.</param>
        /// <returns>Saml2Response</returns>
        /// <exception cref="XmlException">On xml errors or unexpected xml structure.</exception>
        public static Saml2Response Read(string xml, Saml2Id expectedInResponseTo)
        {
            var x = XmlHelpers.XmlDocumentFromString(xml);

            return(new Saml2Response(x.DocumentElement, expectedInResponseTo));
        }
Ejemplo n.º 4
0
 /// <summary>Default constructor.</summary>
 public PlayerCredential()
 {
     credentialFile = (TextAsset)UnityEngine.Resources.Load("xml/credentials");
     loginInfos     = XmlHelpers.loadCredentials(credentialFile);
 }
Ejemplo n.º 5
0
 public void XmlHelpers_GetCorrespondingDigestAlgorithmName_Sha256()
 {
     XmlHelpers.GetCorrespondingDigestAlgorithm(SignedXml.XmlDsigRSASHA256Url)
     .Should().Be(SignedXml.XmlDsigSHA256Url);
 }
Ejemplo n.º 6
0
 private static bool FindElement(XmlReader reader, string name)
 {
     return(XmlHelpers.FindNextElementInSequence(reader, name, LdmlNodeComparer.CompareElementNames));
 }
        XmlDocument ResolveXml(ref List <object> forEachParms, object parentExitData, Dictionary <string, ParameterInfo> globalParamSets)
        {
            string context = "ResolveXml";
            string errData = __nodata;

            try
            {
                XmlDocument parms = null;

                if (HasInheritedValues)
                {
                    context = "InheritedValues=>Clone";
                    errData = InheritedValues.GetType().ToString();
                    parms   = (XmlDocument)((XmlDocument)((ParameterInfo)InheritedValues).Values).Clone();
                }

                if (HasUri)
                {
                    context = "Uri=>Fetch";
                    try { errData = new Uri(Uri).ToString(); } catch { errData = Uri.ToString(); }

                    string uriContent = WebRequestClient.GetString(Uri);
                    context = "Uri=>Fetch, LoadXml";
                    errData = uriContent;
                    XmlDocument uriXml = new XmlDocument();
                    uriXml.LoadXml(uriContent);

                    context = parms != null ? "Merge->Inherited" : "Assign to parms";
                    context = $"Uri=>{context}";
                    errData = XmlHelpers.Serialize <XmlDocument>(uriXml);
                    if (parms != null)
                    {
                        XmlHelpers.Merge(ref parms, uriXml);
                    }
                    else
                    {
                        parms = uriXml;
                    }
                }

                //merge parms
                if (HasValues)
                {
                    context = "HasValues=>LoadXml";
                    errData = Values.ToString();
                    XmlDocument values = new XmlDocument();
                    values.LoadXml(Values.ToString());

                    context = parms != null ? "Merge->Inherited+Uri+Values" : "Assign to parms";
                    context = $"Uri=>{context}";
                    errData = XmlHelpers.Serialize <XmlDocument>(values);
                    if (parms != null)
                    {
                        XmlHelpers.Merge(ref parms, values);
                    }
                    else
                    {
                        parms = values;
                    }
                }


                if (parms == null)
                {
                    parms = new XmlDocument();
                }


                //kv_replace
                if (HasDynamic)
                {
                    context = "HasDynamic=>Merge->Inherited+Uri+Values+Dynamic";
                    try { errData = YamlHelpers.Serialize(_dynamicData); } catch { errData = __nodata; }   //YamlHelpers not a mistake, used it on purpose for easy to read error data
                    XmlHelpers.Merge(ref parms, Dynamic, _dynamicData);
                }

                if (HasParentExitData && parentExitData != null)
                {
                    context = "ParentExitData=>Init Xml Source";
                    errData = parentExitData.GetType().ToString();

                    XmlDocument xd = new XmlDocument();
                    if (parentExitData is XmlNode)
                    {
                        xd.InnerXml = ((XmlNode)parentExitData).OuterXml;
                    }
                    else if (parentExitData is XmlNode[])
                    {
                        xd.InnerXml = ((XmlNode[])parentExitData)[0].OuterXml;
                    }
                    else if (parentExitData is string)
                    {
                        xd.InnerXml = (string)parentExitData;
                    }
                    else
                    {
                        xd = (XmlDocument)parentExitData;
                    }

                    context = "ParentExitData=>Merge->Inhetited+Uri+Values+Dynamic+ParentExitData";
                    errData = XmlHelpers.Serialize <XmlDocument>(xd);
                    XmlHelpers.Merge(ref parms, ParentExitData, ref xd);
                }

                if (HasForEach && parms != null)
                {
                    //assemble ForEach variables
                    if (ForEach.HasParameterSourceItems)
                    {
                        context = "ForEach=>HasParameterSourceItems";
                        errData = null;
                        XmlHelpers.SelectForEachFromValues(ForEach.ParameterSourceItems, ref parms, globalParamSets, parentExitData);
                    }

                    //expand ForEach variables
                    context = "ForEach=>ExpandForEach";
                    try { errData = XmlHelpers.Serialize <XmlDocument>(parms); } catch { errData = __nodata; }
                    forEachParms = XmlHelpers.ExpandForEachAndApplyPatchValues(ref parms, ForEach);
                }


                return(parms);
            }
            catch (Exception ex)
            {
                throw new Exception(GetResolveExceptionMessage(context, errData), ex);
            }
        }
        public List <FinancialTransaction> Calculate(Stream file, FileFormatEnum format)
        {
            List <FinancialTransaction> result = new List <FinancialTransaction>();

            try
            {
                using (var textReader = new StreamReader(file))
                {
                    switch (format)
                    {
                    case FileFormatEnum.XML:
                        result = XmlHelpers.ReadFile <Portfolio>(file)?.Trade;
                        break;

                    case FileFormatEnum.CSV:
                        result = CsvHelpers.ReadFile <FinancialTransaction>(textReader, typeof(FinancialTransactionMapper));
                        break;

                    default:
                        break;
                    }
                }

                using (var dbContext = new DatabaseContext())
                {
                    //Maybe save this list to cache is better solution - somthing like redis
                    var companies   = dbContext.Companies.Include(t => t.Currency).ToList();
                    var currentDate = Convert.ToDateTime(ConfigurationReader.ReadAppConfig("CurrentDate", "2016, 4, 1"));
                    Parallel.ForEach(result, (FinancialTransactionItem) =>
                    {
                        var company = companies.FirstOrDefault(t => t.Name == FinancialTransactionItem.Name.Trim());
                        if (company == null)
                        {
                            FinancialTransactionItem.Result = "Invalid Company Name";
                        }
                        else
                        {
                            var expireDate = Convert.ToDateTime(FinancialTransactionItem.ExpiryDate);

                            double yearOfExpiery = expireDate.YearsDiffrent(currentDate);
                            CallPutFlag callPutFlag;
                            if (!Enum.TryParse(FinancialTransactionItem.CallPutFlag, out callPutFlag))
                            {
                                FinancialTransactionItem.Result = "Invalid Data";
                            }
                            else
                            {
                                FinancialTransactionItem.Price  = _blackScholes.CalculateBlackScholes(callPutFlag, company.StockPrice, FinancialTransactionItem.StrikePrice, yearOfExpiery, company.Currency.RiskFreeRate, company.Volatility);
                                FinancialTransactionItem.Result = "Success";
                            }
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                result = new List <FinancialTransaction>();
                log.Error($"Error occured in {this.GetType().FullName} - {MethodBase.GetCurrentMethod().Name}", ex);
            }

            return(result);
        }
 public string ToXml(bool prettyPrint)
 {
     return(XmlHelpers.Serialize <ActiveDirectoryHandlerResults>(this, true, true, prettyPrint));
 }
Ejemplo n.º 10
0
        private void btnOverrideCurrentSettings_Click(object sender, RoutedEventArgs e)
        {
            string mappingFile = txtMappingFile.Text.Trim();

            if (!string.IsNullOrEmpty(mappingFile))
            {
                if (!File.Exists(mappingFile))
                {
                    MessageBox.Show("Could not load file");
                    return;
                }

                string injectionStrategyTypeName = XmlHelpers.GetAttributeValueFromDoc <string>(mappingFile, "/map/injection-strategy", "name",
                                                                                                string.Empty);

                int injectionStrategyNrOriginalQueryCols = XmlHelpers.GetElementValueFromDoc <int>(mappingFile,
                                                                                                   "/map/injection-strategy/columns/originalquery", 0);

                int injectionStrategyNrHtmlCols = XmlHelpers.GetElementValueFromDoc <int>(mappingFile,
                                                                                          "/map/injection-strategy/columns/resultinghtml", 0);

                string injectionStrategyColumnIndexes = XmlHelpers.GetElementValueFromDoc <string>(mappingFile,
                                                                                                   "/map/injection-strategy/columns/indexes", string.Empty);


                string vulnerableUrl = XmlHelpers.GetElementValueFromDoc <string>(mappingFile, "/map/vulnerable-url", string.Empty);

                string dbms = XmlHelpers.GetAttributeValueFromDoc <string>(mappingFile, "/map/dbms", "name",
                                                                           string.Empty);

                IInjectionStrategy strategy = _injectionStrategies.Where(i => i.GetType().Name == injectionStrategyTypeName).FirstOrDefault();
                if (strategy != null)
                {
                    cbCurrentInjectionStrategy.SelectedValue = strategy.DisplayName;
                }
                if (_currentInjectionStrategy != null)
                {
                    if (!string.IsNullOrEmpty(vulnerableUrl))
                    {
                        txtUrl.Text = vulnerableUrl;
                        UrlOrStrategyChange();
                        //ParameterChange();
                    }
                    _currentInjectionStrategy.NrColumnsInOriginalQuery  = injectionStrategyNrOriginalQueryCols;
                    _currentInjectionStrategy.NumberOfResultsPerRequest = injectionStrategyNrHtmlCols;
                    _currentInjectionStrategy.ColumnIndexes             = ListHelpers.CommaSeparatedValuesToList <int>(injectionStrategyColumnIndexes);
                }

                if (!string.IsNullOrEmpty(dbms))
                {
                    cbDbms.SelectedValue = dbms;
                }

                var databasesElem = XmlHelpers.GetXmlElementViaXpath(mappingFile, "/map/databases");
                if (databasesElem != null)
                {
                    var newRootElement = UIHelpers.ClearTreeView(tvDs);

                    UIHelpers.BuildNodes(newRootElement, databasesElem);

                    #region different approach
                    //    XmlDataProvider dataProvider = this.FindResource("xmlDataProvider") as XmlDataProvider;
                    //    var bindDoc = new XmlDocument();
                    //    var reader = databasesElem.CreateReader();
                    //    reader.MoveToContent();
                    //    bindDoc.LoadXml(reader.ReadOuterXml());
                    //    dataProvider.Document = bindDoc;
                    #endregion different approach
                }
            }
        }
Ejemplo n.º 11
0
        private void btnCheckUrls_Click(object sender, RoutedEventArgs e)
        {
            IList <string> vulnerableResults = new List <string>();
            IList <string> urlsToCheck       = new List <string>();

            string[] separators             = new string[] { Environment.NewLine };
            IList <PatternDetails> patterns = new List <PatternDetails>();
            string urlBatch = txtUrls.Text;

            btnCheckUrls.IsEnabled = false;
            txtProbablyVulnerableUrls.Clear();
            bool possiblyVulnerable = false;


            var th = new Thread(() =>
            {
                var queryRunner = new SimpleQueryRunner();

                if (!string.IsNullOrEmpty(urlBatch))
                {
                    urlsToCheck = urlBatch.Split(separators, StringSplitOptions.RemoveEmptyEntries).ToList();
                }

                foreach (var url in urlsToCheck)
                {
                    if (_stopCurActionFilterUrlsTab == true)
                    {
                        break;
                    }

                    possiblyVulnerable = false;

                    IList <string> possiblyVulnerableUrls = Seringa.Engine.Utils.UrlHelpers.GeneratePossibleVulnerableUrls(url);//TODO:multiple possible vulnerable urls

                    foreach (var possiblyVulnerableUrl in possiblyVulnerableUrls)
                    {
                        string pageHtml = string.Empty;

                        try
                        {
                            pageHtml = queryRunner.GetPageHtml(possiblyVulnerableUrl, null);//@TODO:proxify
                        }
                        catch (Exception ex)
                        {
                            //@TODO: Log Exception
                        }

                        patterns = XmlHelpers.GetObjectsFromXml <PatternDetails>(FileHelpers.GetCurrentDirectory() + "\\xml\\patterns.xml", "pattern", null);

                        foreach (var pattern in patterns)
                        {
                            if (pattern != null && !string.IsNullOrEmpty(pattern.Value))
                            {
                                if (pageHtml.IndexOf(pattern.Value) > -1)
                                {
                                    possiblyVulnerable = true;
                                    break;
                                }
                            }
                        }

                        if (possiblyVulnerable)
                        {
                            gridFilterUrls.Dispatcher.Invoke(
                                System.Windows.Threading.DispatcherPriority.Normal,
                                new Action(
                                    delegate()
                            {
                                txtProbablyVulnerableUrls.Text += possiblyVulnerableUrl + Environment.NewLine;
                            }));
                        }
                    }
                }

                _stopCurActionFilterUrlsTab = false;

                gridFilterUrls.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(
                        delegate()
                {
                    btnCheckUrls.IsEnabled = true;
                }
                        ));
            });

            th.Start();
        }
Ejemplo n.º 12
0
        private void btnExecuteCustomQuery_Click(object sender, RoutedEventArgs e)
        {
            txtCustomQueryResult.Clear();
            DisableAll();

            var th = new Thread(() =>
            {
                string result = string.Empty;

                int total = 0;

                try
                {
                    total = _currentInjectionStrategy.GetTotalNoOfCustomQueryResultRows();
                }
                catch (Exception ex)
                {
                    txtCustomQueryResult.Dispatcher.Invoke(
                        System.Windows.Threading.DispatcherPriority.Normal,
                        new Action(
                            delegate()
                    {
                        txtCustomQueryResult.Text = ex.Message;
                    }
                            ));
                }

                if (_currentInjectionStrategy.NumberOfResultsPerRequest > 0)
                {
                    for (int i = 0; i < total; i = i + _currentInjectionStrategy.NumberOfResultsPerRequest)
                    {
                        if (_stopCurrentActionSingleUrlTab)
                        {
                            break;
                        }
                        try
                        {
                            result = _currentInjectionStrategy.GetSingleCustomQueryResultRow(i);
                        }
                        catch (Exception ex)
                        {
                            result = ex.Message;
                        }
                        if (!string.IsNullOrEmpty(result))
                        {
                            #region map to ui

                            List <string> valuesToInsert = new List <string>();
                            if (result.Contains(Environment.NewLine))
                            {
                                valuesToInsert.AddRange(result.Split(new string[] { Environment.NewLine }, StringSplitOptions.None));
                            }
                            else
                            {
                                valuesToInsert.Add(result);
                            }

                            if (_currentInjectionStrategy.PayloadDetails != null &&
                                !string.IsNullOrEmpty(_currentInjectionStrategy.PayloadDetails.NodeToMapTo))
                            {
                                var xpath = XmlHelpers.CreateProperMapToNodeFinderXpath(_currentInjectionStrategy.PayloadDetails, _currentInjectionStrategy);
                                //var xpath = XmlHelpers.CreateProperMapToNodeCreatorXpath(_currentInjectionStrategy.PayloadDetails,
                                //    result);
                                var tagName = XmlHelpers.GetLastTagFromXpath(xpath);

                                XmlTreeViewItem newChildItem  = null;
                                XmlTreeViewItem oldParentItem = null;

                                if (tagName == "databases")//@TODO: no more hardconding
                                {
                                    oldParentItem = UIHelpers.GetTreeViewRoot(tvDs);
                                }
                                else if (tagName == "db" || tagName == "table")//@TODO: no more hardconding
                                {
                                    oldParentItem = _selectedTreeViewItem;
                                }

                                if (oldParentItem != null)
                                {
                                    foreach (var value in valuesToInsert)
                                    {
                                        if (!string.IsNullOrEmpty(value))
                                        {
                                            tvDs.Dispatcher.Invoke(
                                                System.Windows.Threading.DispatcherPriority.Normal,
                                                new Action(
                                                    delegate()
                                            {
                                                newChildItem = UIHelpers.GetXmlTreeViewItemRec(oldParentItem,
                                                                                               _currentInjectionStrategy.PayloadDetails.NodeToMapTo,
                                                                                               value);
                                            }
                                                    ));
                                            if (newChildItem == null)
                                            {
                                                tvDs.Dispatcher.Invoke(
                                                    System.Windows.Threading.DispatcherPriority.Normal,
                                                    new Action(
                                                        delegate()
                                                {
                                                    UIHelpers.XmlTreeViewAdd(oldParentItem, _currentInjectionStrategy.PayloadDetails.NodeToMapTo, value);
                                                }
                                                        ));
                                            }
                                        }
                                    }
                                }
                            }
                            #endregion map to ui

                            txtCustomQueryResult.Dispatcher.Invoke(
                                System.Windows.Threading.DispatcherPriority.Normal,
                                new Action(
                                    delegate()
                            {
                                txtCustomQueryResult.Text += result + Environment.NewLine;
                            }
                                    ));
                        }
                    }
                }

                _stopCurrentActionSingleUrlTab = false;
                EnableAllFromOtherThread();
            });

            th.Start();
        }
Ejemplo n.º 13
0
        private void btnAutodetect_Click(object sender, RoutedEventArgs e)
        {
            bool                   findAllPossibleAttackVectors = true;//@TODO: this should be a setting and come from somewhere, maybe the UI
            bool                   vuln            = false;
            string                 msg             = string.Empty;
            IList <string>         dbMgmtSystems   = new List <string>();
            IList <ExploitDetails> exploits        = new List <ExploitDetails>();
            List <dynamic>         filters         = null;
            dynamic                filter          = null;
            ProxyType              proxyType       = ProxyType.None;
            string                 url             = txtUrl.Text;
            string                 fullProxyAdress = txtProxyFullAddress.Text;
            bool                   useProxy        = (chkUseProxy.IsChecked != null) ? chkUseProxy.IsChecked.Value : false;;

            ClearAll();
            DisableAll();

            if (cmbProxyType.SelectedValue != null)
            {
                Enum.TryParse <ProxyType>(cmbProxyType.SelectedValue.ToString(), out proxyType);
            }

            var th = new Thread(() =>
            {
                dbMgmtSystems = XmlHelpers.GetAllAttributeValuesFromDoc(FileHelpers.GetCurrentDirectory() + "\\xml\\exploits.xml",
                                                                        "exploit", "dbms");

                foreach (var injectionStrategy in _injectionStrategies)
                {
                    if (_stopCurrentActionSingleUrlTab)
                    {
                        break;
                    }

                    foreach (var dbMgmtSystem in dbMgmtSystems)
                    {
                        if (_stopCurrentActionSingleUrlTab)
                        {
                            break;
                        }

                        filters = new List <dynamic>();
                        filter  = new ExpandoObject();
                        filter.AttributeName = "dbms"; filter.AttributeValue = dbMgmtSystem;
                        filters.Add(filter);
                        filter = new ExpandoObject();
                        filter.AttributeName = "injection-strategy"; filter.AttributeValue = injectionStrategy.GetType().Name;
                        filters.Add(filter);
                        exploits = XmlHelpers.GetObjectsFromXml <ExploitDetails>(FileHelpers.GetCurrentDirectory() + "\\xml\\exploits.xml", "exploit",
                                                                                 filters);

                        foreach (var exploit in exploits)
                        {
                            if (_stopCurrentActionSingleUrlTab)
                            {
                                break;
                            }

                            //populate
                            injectionStrategy.ExploitDetails = exploit; injectionStrategy.Url = url;
                            if (useProxy)
                            {
                                injectionStrategy.UseProxy     = true;
                                injectionStrategy.ProxyDetails = new ProxyDetails()
                                {
                                    FullProxyAddress = fullProxyAdress,
                                    ProxyType        = proxyType
                                };
                            }

                            //test
                            //var superGigi = UrlHelpers.HexEncodeValue("gigi");

                            try
                            {
                                vuln = injectionStrategy.TestIfVulnerable();
                            }
                            catch (Exception ex)
                            {
                                //TODO: log this maybe?
                            }

                            //depopulate
                            injectionStrategy.ExploitDetails = null; injectionStrategy.Url = null; injectionStrategy.ProxyDetails = null;
                            injectionStrategy.UseProxy       = false;

                            if (vuln)
                            {
                                msg += string.Format("Vulnerable using  the injection strategy: {0} with the exploit: {1}. Detected DBMS: {2}",
                                                     injectionStrategy.DisplayName, exploit.UserFriendlyName, dbMgmtSystem)
                                       + Environment.NewLine;
                                if (!findAllPossibleAttackVectors)
                                {
                                    _stopCurrentActionSingleUrlTab = true;
                                }
                                else
                                {
                                    vuln = false;
                                }
                            }
                        }
                    }
                }

                if (string.IsNullOrEmpty(msg))
                {
                    msg = "Not vulnerable given any available expoit";
                }

                txtCustomQueryResult.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(
                        delegate()
                {
                    txtCustomQueryResult.Text = msg;
                }
                        ));
                _stopCurrentActionSingleUrlTab = false;
                EnableAllFromOtherThread();
            });

            try
            {
                th.Start();
            }
            catch (Exception ex)
            {
                txtCustomQueryResult.Text = string.Format("Error: {0}", ex.Message);
            }
        }
Ejemplo n.º 14
0
 private void PopulateDbms()
 {
     cbDbms.DataContext = XmlHelpers.GetAllAttributeValuesFromDoc(FileHelpers.GetCurrentDirectory() + "\\xml\\payloads.xml",
                                                                  "payload", "dbms");
 }
Ejemplo n.º 15
0
        public void SignAndLoadAndSave_DocumentWithWhitespaceAndIndentation_DoesNotBreakSignatures()
        {
            // Signatures are sensitive to even whitespace changes. While this library deliberately avoids generating
            // whitespace to keep it simple, we cannot assume that all input is without whitespace.
            // The library must be capable of preserving signed parts of existing documents that contain whitespace.

            var cpixStream = GenerateNontrivialCpixStream();

            // Now create a nicely formatted copy.
            var formattedCpixStream = new MemoryStream();

            XmlHelpers.PrettyPrintXml(cpixStream, formattedCpixStream);

            // Now sign it!
            var document = new XmlDocument();

            document.PreserveWhitespace = true;

            formattedCpixStream.Position = 0;
            document.Load(formattedCpixStream);

            // Note that the collections are not given IDs as they were not signed on save.
            // We need to manually give them IDs. That's fine - we can also verify that we have no ID format dependencies!
            var namespaces = XmlHelpers.CreateCpixNamespaceManager(document);

            const string recipientsId  = "id-for-recipients----";
            const string contentKeysId = "_id_for_content_keys";
            const string usageRulesId  = "a.0a.0a.0a.0a.0a.a0.0a0.0404040......";

            SetElementId(document, namespaces, "/cpix:CPIX/cpix:DeliveryDataList", recipientsId);
            SetElementId(document, namespaces, "/cpix:CPIX/cpix:ContentKeyList", contentKeysId);
            SetElementId(document, namespaces, "/cpix:CPIX/cpix:ContentKeyUsageRuleList", usageRulesId);

            CryptographyHelpers.SignXmlElement(document, recipientsId, TestHelpers.Certificate1WithPrivateKey);
            CryptographyHelpers.SignXmlElement(document, contentKeysId, TestHelpers.Certificate1WithPrivateKey);
            CryptographyHelpers.SignXmlElement(document, usageRulesId, TestHelpers.Certificate1WithPrivateKey);
            CryptographyHelpers.SignXmlElement(document, usageRulesId, TestHelpers.Certificate2WithPrivateKey);
            CryptographyHelpers.SignXmlElement(document, "", TestHelpers.Certificate1WithPrivateKey);

            // Okay, that's fine. Save!
            var signedCpixStream = new MemoryStream();

            using (var writer = XmlWriter.Create(signedCpixStream, new XmlWriterSettings
            {
                Encoding = Encoding.UTF8,
                CloseOutput = false
            }))
            {
                document.Save(writer);
            }

            signedCpixStream.Position = 0;

            // Now it should be a nice valid and signed CPIX document.
            var cpix = CpixDocument.Load(signedCpixStream);

            Assert.NotNull(cpix.SignedBy);
            Assert.Single(cpix.Recipients.SignedBy);
            Assert.Single(cpix.ContentKeys.SignedBy);
            Assert.Equal(2, cpix.UsageRules.SignedBy.Count());

            // And save/load should preserve all the niceness.
            cpix = TestHelpers.Reload(cpix);

            Assert.NotNull(cpix.SignedBy);
            Assert.Single(cpix.Recipients.SignedBy);
            Assert.Single(cpix.ContentKeys.SignedBy);
            Assert.Equal(2, cpix.UsageRules.SignedBy.Count());

            // And, of course, the data should still be there.
            Assert.Equal(2, cpix.ContentKeys.Count);
            Assert.Equal(2, cpix.Recipients.Count);
            Assert.Equal(2, cpix.UsageRules.Count);

            // No exception? Success!
        }
        public void TransformXml()
        {
            string result = XmlHelpers.Transform(_baseXml, _xslt);

            Assert.AreEqual(_serversXml, result);
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Finds and reads the EndElement "&lt;/special&gt;"
 /// </summary>
 /// <param name="reader"></param>
 protected static void ReadSpecialEndElement(XmlReader reader)
 {
     XmlHelpers.ReadEndElement(reader, "special");
 }
        public void ConvertXml(FormatType format)
        {
            string result = XmlHelpers.ConvertToFormat(_baseXml, format);

            CompareConvertResult(result, format);
        }
Ejemplo n.º 19
0
        public dynamic BuildDisplay(XElement description, XElement data, IContent contentPart, string displayType, IDictionary <string, IEnumerator <XElement> > dataEnumerators = null)
        {
            switch (description.Name.LocalName.ToLowerInvariant())
            {
            case "part":
                var layoutElement = description.FindParentWithAttributes("width", "height") ?? new XElement("layout");
                if (contentPart == null)
                {
                    return(null);
                }
                var partTypeName = XmlHelpers.Attr(description, "part");
                if (string.IsNullOrWhiteSpace(partTypeName))
                {
                    return(null);
                }
                if (contentPart.ContentItem.Parts.All(
                        p => p != null && p.GetType().Name != partTypeName))
                {
                    var secondaryItem = contentPart as ISecondaryContent;
                    if (secondaryItem != null)
                    {
                        contentPart = secondaryItem.GetPrimaryContentItem();
                        if (contentPart == null)
                        {
                            return(null);
                        }
                    }
                }
                var partDriver = _partDrivers.Value.FirstOrDefault(
                    h => {
                    var driverType = h.GetType().BaseType;
                    if (driverType == null ||
                        (!driverType.IsGenericType) ||
                        (driverType.Name != "ContentPartDriver`1"))
                    {
                        return(false);
                    }
                    var driverPartTypeName = driverType.GetGenericArguments()[0].Name;
                    return(driverPartTypeName == partTypeName);
                });
                if (partDriver == null)
                {
                    return(null);
                }
                var workContext = _wca.GetContext();
                var partShapes  = BuildShape(workContext, contentPart, displayType, partDriver);
                return(Shape.LayoutElements_Part(
                           Name: T("Part"),
                           PartName: partTypeName,
                           PartShapes: partShapes,
                           Top: description.AttrLength("top"),
                           Left: description.AttrLength("left"),
                           LayoutWidth: layoutElement.AttrInt("width"),
                           LayoutHeight: layoutElement.AttrInt("height"),
                           CssClass: XmlHelpers.Attr(description, "class"),
                           ElementTitle: XmlHelpers.Attr(description, "title"),
                           ContentPart: contentPart,
                           ContentItem: contentPart.ContentItem));

            case "field":
                layoutElement = description.FindParentWithAttributes("width", "height") ?? new XElement("layout");
                if (contentPart == null || contentPart.ContentItem == null)
                {
                    return(null);
                }
                var fieldName = XmlHelpers.Attr(description, "field");
                if (string.IsNullOrWhiteSpace(fieldName))
                {
                    return(null);
                }
                var field = GetField(contentPart, fieldName);
                if (field == null)
                {
                    var secondaryItem = contentPart as ISecondaryContent;
                    if (secondaryItem != null)
                    {
                        contentPart = secondaryItem.GetPrimaryContentItem();
                        if (contentPart == null)
                        {
                            return(null);
                        }
                        field = GetField(contentPart, fieldName);
                        if (field == null)
                        {
                            return(null);
                        }
                    }
                }
                var fieldTypeName = field == null ? "" : field.GetType().Name;
                var fieldDriver   = _fieldDrivers.Value.FirstOrDefault(
                    h => {
                    var driverType = h.GetType().BaseType;
                    if (driverType == null ||
                        (!driverType.IsGenericType) ||
                        (driverType.Name != "ContentFieldDriver`1"))
                    {
                        return(false);
                    }
                    var driverFieldTypeName = driverType.GetGenericArguments()[0].Name;
                    return(driverFieldTypeName == fieldTypeName);
                });
                if (fieldDriver == null)
                {
                    return(null);
                }
                workContext = _wca.GetContext();
                var fieldShapes = BuildShape(workContext, contentPart, displayType, fieldDriver: fieldDriver, fieldName: fieldName);
                return(Shape.LayoutElements_Field(
                           Name: T("Field"),
                           FieldName: fieldName,
                           FieldShapes: fieldShapes,
                           Top: description.AttrLength("top"),
                           Left: description.AttrLength("left"),
                           LayoutWidth: layoutElement.AttrInt("width"),
                           LayoutHeight: layoutElement.AttrInt("height"),
                           CssClass: XmlHelpers.Attr(description, "class"),
                           ElementTitle: XmlHelpers.Attr(description, "title"),
                           ContentPart: contentPart,
                           ContentItem: contentPart.ContentItem));
            }
            return(null);
        }
Ejemplo n.º 20
0
 public T Add(T value)
 {
     return(XmlHelpers.AddToDb(value));
 }
Ejemplo n.º 21
0
 public SimpleIPObtainerStrategy()
 {
     QueryRunner = new SimpleQueryRunner();
     _details    = XmlHelpers.GetObjectFromXml <IpObtainerDetails>(FileHelpers.GetCurrentDirectory() + "\\xml\\ipcheckers.xml", "ipchecker", 0);
 }
Ejemplo n.º 22
0
 public void SaveMap(string path)
 {
     XmlHelpers.SaveToXML <MapObject>(Application.dataPath + "/Resources/Save/" + path, mapObject);
 }
Ejemplo n.º 23
0
 public void XmlHelpers_GetCorrespondingDigestAlgorithmName_Sha256()
 {
     XmlHelpers.GetCorrespondingDigestAlgorithm(SecurityAlgorithms.RsaSha256Signature)
     .Should().Be(SecurityAlgorithms.Sha256Digest);
 }
Ejemplo n.º 24
0
 public IpObtainerDetails(XElement details)
 {
     Url        = XmlHelpers.GetElementValueViaXpath <string>(details, "url", string.Empty);
     LowerBound = XmlHelpers.GetElementValueViaXpath <string>(details, "lowerbound", string.Empty);
     UpperBound = XmlHelpers.GetElementValueViaXpath <string>(details, "upperbound", string.Empty);
 }
Ejemplo n.º 25
0
        public void MetadataCommand_Run_CompleteMetadata()
        {
            var options = StubFactory.CreateOptions();

            options.SPOptions.DiscoveryServiceUrl = new Uri("http://ds.example.com");
            options.SPOptions.AuthenticateRequestSigningBehavior = SigningBehavior.Always;
            options.SPOptions.OutboundSigningAlgorithm           = SignedXml.XmlDsigRSASHA384Url;
            options.SPOptions.ServiceCertificates.Add(new ServiceCertificate()
            {
                Certificate             = SignedXmlHelper.TestCertSignOnly,
                Use                     = CertificateUse.Signing,
                MetadataPublishOverride = MetadataPublishOverrideType.PublishUnspecified
            });

            var subject = new MetadataCommand().Run(request, options);

            var payloadXml = XmlHelpers.XmlDocumentFromString(subject.Content);

            // Validate signature, location of it  and then drop it. It contains
            // a reference to the ID which makes it unsuitable for string matching.
            payloadXml.DocumentElement.IsSignedBy(SignedXmlHelper.TestCertSignOnly).Should().BeTrue();
            payloadXml.DocumentElement.FirstChild.LocalName.Should().Be("Signature");
            payloadXml.DocumentElement.FirstChild["KeyInfo"].Should().NotBeNull();
            payloadXml.DocumentElement.FirstChild["SignedInfo"]["SignatureMethod"].GetAttribute("Algorithm")
            .Should().Be(SignedXml.XmlDsigRSASHA384Url);
            payloadXml.DocumentElement.RemoveChild("Signature", SignedXml.XmlDsigNamespaceUrl);

            // Ignore the ID attribute, it is just filled with a GUID that can't be easily tested.
            payloadXml.DocumentElement.Attributes.Remove("ID");

            // Test and then drop validUntil, can't be text compared.
            DateTime.Parse(payloadXml.DocumentElement.Attributes["validUntil"].Value)
            .Should().BeCloseTo(DateTime.UtcNow.AddDays(24).ToLocalTime(), 2000);
            payloadXml.DocumentElement.Attributes.Remove("validUntil");

            var expectedXml =
                "<EntityDescriptor entityID=\"https://github.com/SustainsysIT/Saml2\" cacheDuration=\"PT42S\" xmlns:saml2=\"urn:oasis:names:tc:SAML:2.0:assertion\" xmlns=\"urn:oasis:names:tc:SAML:2.0:metadata\">"
                + "<SPSSODescriptor AuthnRequestsSigned=\"true\" WantAssertionsSigned=\"true\" protocolSupportEnumeration=\"urn:oasis:names:tc:SAML:2.0:protocol\">"
                + "<Extensions>"
                + "<DiscoveryResponse Binding=\"urn:oasis:names:tc:SAML:profiles:SSO:idp-discovery-protocol\" Location=\"http://localhost/Saml2/SignIn\" index=\"0\" isDefault=\"true\" xmlns=\"urn:oasis:names:tc:SAML:profiles:SSO:idp-discovery-protocol\" />"
                + "</Extensions>"
                + "<KeyDescriptor><KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><X509Data><X509Certificate>MIIDIzCCAg+gAwIBAgIQg7mOjTf994NAVxZu4jqXpzAJBgUrDgMCHQUAMCQxIjAgBgNVBAMTGUtlbnRvci5BdXRoU2VydmljZXMuVGVzdHMwHhcNMTMwOTI1MTMzNTQ0WhcNMzkxMjMxMjM1OTU5WjAkMSIwIAYDVQQDExlLZW50b3IuQXV0aFNlcnZpY2VzLlRlc3RzMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwVGpfvK9N//MnA5Jo1q2liyPR24406Dp25gv7LB3HK4DWgqsb7xXM6KIV/WVOyCV2g/O1ErBlB+HLhVZ4XUJvbqBbgAJqFO+TZwcCIe8u4nTEXeU660FdtkKClA17sbtMrAGdDfOPwVBHSuavdHeD7jHNI4RUDGKnEW13/0EvnHDilIetwODRxrX/+41R24sJThFbMczByS3OAL2dcIxoAynaGeM90gXsVYow1QhJUy21+cictikb7jW4mW6dvFCBrWIceom9J295DcQIHoxJy5NoZwMir/JV00qs1wDVoN20Ve1DC5ImwcG46XPF7efQ44yLh2j5Yexw+xloA81dwIDAQABo1kwVzBVBgNVHQEETjBMgBAWIahoZhXVUogbAqkS7zwfoSYwJDEiMCAGA1UEAxMZS2VudG9yLkF1dGhTZXJ2aWNlcy5UZXN0c4IQg7mOjTf994NAVxZu4jqXpzAJBgUrDgMCHQUAA4IBAQA2aGzmuKw4AYXWMhrGj5+i8vyAoifUn1QVOFsUukEA77CrqhqqaWFoeagfJp/45vlvrfrEwtF0QcWfmO9w1VvHwm7sk1G/cdYyJ71sU+llDsdPZm7LxQvWZYkK+xELcinQpSwt4ExavS+jLcHoOYHYwIZMBn3U8wZw7Kq29oGnoFQz7HLCEl/G9i3QRyvFITNlWTjoScaqMjHTzq6HCMaRsL09DLcY3KB+cedfpC0/MBlzaxZv0DctTulyaDfM9DCYOyokGN/rQ6qkAR0DDm8fVwknbJY7kURXNGoUetulTb5ow8BvD1gncOaYHSD0kbHZG+bLsUZDFatEr2KW8jbG</X509Certificate></X509Data></KeyInfo></KeyDescriptor>"
                + "<SingleLogoutService Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect\" Location=\"http://localhost/Saml2/Logout\" />"
                + "<SingleLogoutService Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\" Location=\"http://localhost/Saml2/Logout\" />"
                + "<AssertionConsumerService Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\" Location=\"http://localhost/Saml2/Acs\" index=\"0\" isDefault=\"true\" />"
                + "<AssertionConsumerService Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact\" Location=\"http://localhost/Saml2/Acs\" index=\"1\" isDefault=\"false\" />"
                + "<AttributeConsumingService index=\"0\" isDefault=\"true\">"
                + "<ServiceName xml:lang=\"en\">attributeServiceName</ServiceName>"
                + "<RequestedAttribute Name=\"urn:attributeName\" isRequired=\"true\" NameFormat=\"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\" FriendlyName=\"friendlyName\">"
                + "<saml2:AttributeValue>value1</saml2:AttributeValue>"
                + "<saml2:AttributeValue>value2</saml2:AttributeValue>"
                + "</RequestedAttribute>"
                + "<RequestedAttribute Name=\"someName\" isRequired=\"false\" />"
                + "</AttributeConsumingService>"
                + "</SPSSODescriptor>"
                + "<Organization>"
                + "<OrganizationName xml:lang=\"\">Sustainsys.Saml2</OrganizationName>"
                + "<OrganizationDisplayName xml:lang=\"\">Sustainsys Saml2</OrganizationDisplayName>"
                + "<OrganizationURL xml:lang=\"\">http://github.com/SustainsysIT/Saml2</OrganizationURL>"
                + "</Organization>"
                + "<ContactPerson contactType=\"support\">"
                + "<Company>Sustainsys</Company>"
                + "<GivenName>Anders</GivenName>"
                + "<SurName>Abel</SurName>"
                + "<EmailAddress>[email protected]</EmailAddress>"
                + "<EmailAddress>[email protected]</EmailAddress>"
                + "<TelephoneNumber>+46 8 587 650 00</TelephoneNumber>"
                + "<TelephoneNumber>+46 708 96 50 63</TelephoneNumber>"
                + "</ContactPerson>"
                + "<ContactPerson contactType=\"technical\" />"
                + "</EntityDescriptor>";

            payloadXml.Should().BeEquivalentTo(XmlHelpers.XmlDocumentFromString(expectedXml));
            subject.ContentType.Should().Be("application/samlmetadata+xml");
        }
Ejemplo n.º 26
0
        protected override void Initialize(XElement extensionElement, GamePack package)
        {
            var speedElement = XmlHelpers.GetChild(extensionElement, "speed");

            Speed = XmlHelpers.GetFloat(speedElement);
        }
Ejemplo n.º 27
0
        private static LogData ProcessLogItem(Dictionary <string, Object> logItem, string userAgent, string userHostAddress,
                                              string requestId, DateTime serverSideTimeUtc, string url, XmlElement xe)
        {
            string serversideLoggerNameOverride = XmlHelpers.OptionalAttribute(xe, "serverSideLogger", null);
            string messageFormat = XmlHelpers.OptionalAttribute(xe, "serverSideMessageFormat", "%message");
            string levelOverride = XmlHelpers.OptionalAttribute(xe, "serverSideLevel", null, LevelUtils.LevelRegex());
            string dateFormat    = XmlHelpers.OptionalAttribute(xe, "dateFormat", "o");

            // ----------------

            string message = logItem["m"].ToString();
            string logger  = logItem["n"].ToString();
            string level   = logItem["l"].ToString(); // note that level as sent by the javascript is a number

            DateTime utcTimestamp = DateTime.UtcNow;
            string   timestampMs  = logItem["t"].ToString();

            try
            {
                double ms = double.Parse(timestampMs);
                utcTimestamp = DateTime.SpecifyKind((new DateTime(1970, 1, 1)).AddMilliseconds(ms), DateTimeKind.Utc);
            }
            catch
            {
            }

            // ----------------

            if (string.IsNullOrWhiteSpace(logger))
            {
                logger = Constants.RootLoggerNameServerSide;
            }
            string finalLoggerName = serversideLoggerNameOverride ?? logger;

            string finalLevel = levelOverride ?? level;

            // ----------------

            string jsonmessage = "";

            if (messageFormat.Contains("%jsonmessage"))
            {
                jsonmessage = LogMessageHelpers.EnsureValidJson(message);
            }

            // ----------------

            string finalMessage = messageFormat
                                  .Replace("%message", message)
                                  .Replace("%jsonmessage", jsonmessage)
                                  .Replace("%utcDateServer", serverSideTimeUtc.ToString(dateFormat))
                                  .Replace("%utcDate", utcTimestamp.ToString(dateFormat))
                                  .Replace("%dateServer", Utils.UtcToLocalDateTime(serverSideTimeUtc).ToString(dateFormat))
                                  .Replace("%date", Utils.UtcToLocalDateTime(utcTimestamp).ToString(dateFormat))
                                  .Replace("%level", level)
                                  .Replace("%newline", System.Environment.NewLine)
                                  .Replace("%userAgent", userAgent)
                                  .Replace("%userHostAddress", userHostAddress)
                                  .Replace("%requestId", requestId ?? "")
                                  .Replace("%url", url)
                                  .Replace("%logger", logger);

            // ---------------

            LogData logData = new LogData(
                finalMessage, finalLoggerName, LevelUtils.ParseLevel(finalLevel).Value, LevelUtils.LevelNumber(finalLevel),
                message, int.Parse(level), logger, requestId,
                utcTimestamp, serverSideTimeUtc, Utils.UtcToLocalDateTime(utcTimestamp), Utils.UtcToLocalDateTime(serverSideTimeUtc),
                userAgent, userHostAddress, url);

            return(logData);
        }
Ejemplo n.º 28
0
        protected virtual void DecryptElement(XmlElement element, string password)
        {
            var saltXmlAttributeNode = XmlHelpers.GetAttributeNode(element, "Salt");

            if (string.IsNullOrEmpty(saltXmlAttributeNode?.Value))
            {
                throw new InvalidXmlException($"Encrypted element {element.Name} does not contain required Attribute \"Salt\", or its contents is empty", element);
            }
            byte[] rgbSalt;
            try
            {
                rgbSalt = Convert.FromBase64String(saltXmlAttributeNode.Value);
            }
            catch (FormatException)
            {
                throw new InvalidXmlException($"Invalid value of Attribute \"Salt\" ({saltXmlAttributeNode.Value}) in encrypted element {element.Name}", element);
            }
            var ivXmlAttributeNode = XmlHelpers.GetAttributeNode(element, "IV");

            if (string.IsNullOrEmpty(ivXmlAttributeNode?.Value))
            {
                throw new InvalidXmlException($"Encrypted element {element.Name} does not contain required Attribute \"IV\", or its contents is empty", element);
            }
            byte[] iv;
            try
            {
                iv = Convert.FromBase64String(ivXmlAttributeNode.Value);
            }
            catch (FormatException)
            {
                throw new InvalidXmlException($"Invalid value of Attribute \"IV\" ({ivXmlAttributeNode.Value}) in encrypted element {element.Name} ", element);
            }
            var cryptoServiceProvider = new TripleDESCryptoServiceProvider {
                IV = iv
            };

            var passwordDeriveBytes = new PasswordDeriveBytes(password, rgbSalt);

            cryptoServiceProvider.Key = passwordDeriveBytes.CryptDeriveKey("TripleDES", "SHA1", 192,
                                                                           cryptoServiceProvider.IV);
            string xml;

            byte[] buffer;
            try
            {
                buffer = Convert.FromBase64String(element.InnerText);
            }
            catch (FormatException)
            {
                throw new InvalidXmlException($"Invalid value of encrypted element {element.Name}.", element);
            }
            try
            {
                using (var memoryStream = new MemoryStream(buffer))
                {
                    using (
                        var cryptoStream = new CryptoStream(memoryStream, cryptoServiceProvider.CreateDecryptor(),
                                                            CryptoStreamMode.Read))
                    {
                        using (var streamReader = new StreamReader(cryptoStream, Encoding.UTF8))
                            xml = streamReader.ReadToEnd();
                    }
                }
            }
            catch (CryptographicException)
            {
                throw new InvalidPaswordException();
            }

            var xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(xml);

            // The reason to not simply import the new node is because namespace declaration will also be imported with the node.
            element.Attributes.Remove(saltXmlAttributeNode);
            element.Attributes.Remove(ivXmlAttributeNode);

            foreach (XmlNode childNode in element.ChildNodes)
            {
                element.RemoveChild(childNode);
            }
            element.InnerXml = xmlDocument.DocumentElement?.InnerXml;
        }
Ejemplo n.º 29
0
        public void LogoutCommand_Run_HandlesLogoutRequest_ReceivedThroughRedirectBinding()
        {
            var request = new Saml2LogoutRequest()
            {
                DestinationUrl     = new Uri("http://sp.example.com/path/Saml2/logout"),
                Issuer             = new EntityId("https://idp.example.com"),
                SigningCertificate = SignedXmlHelper.TestCert,
                NameId             = new Saml2NameIdentifier("NameId"),
                SessionIndex       = "SessionID",
                SigningAlgorithm   = SecurityAlgorithms.RsaSha256Signature
            };

            var bindResult = Saml2Binding.Get(Saml2BindingType.HttpRedirect)
                             .Bind(request);

            var httpRequest = new HttpRequestData("GET", bindResult.Location);

            var options = StubFactory.CreateOptions();

            options.SPOptions.ServiceCertificates.Add(SignedXmlHelper.TestCert);

            CommandResult notifiedCommandResult = null;

            options.Notifications.LogoutCommandResultCreated = cr =>
            {
                notifiedCommandResult = cr;
            };

            // We're using unbind to verify the created message and UnBind
            // expects the issuer to be a known Idp for signature validation.
            // Add a dummy with the right issuer name and key.
            var dummyIdp = new IdentityProvider(options.SPOptions.EntityId, options.SPOptions);

            dummyIdp.SigningKeys.AddConfiguredKey(SignedXmlHelper.TestCert);
            options.IdentityProviders.Add(dummyIdp);

            var actual = CommandFactory.GetCommand(CommandFactory.LogoutCommandName)
                         .Run(httpRequest, options);

            var expected = new CommandResult()
            {
                HttpStatusCode        = HttpStatusCode.SeeOther,
                TerminateLocalSession = true
                                        // Deliberately not comparing Location
            };

            HttpUtility.ParseQueryString(actual.Location.Query)["Signature"]
            .Should().NotBeNull("LogoutResponse should be signed");

            actual.Should().BeEquivalentTo(expected, opt => opt.Excluding(cr => cr.Location));
            actual.Should().BeSameAs(notifiedCommandResult);

            var actualUnbindResult = Saml2Binding.Get(Saml2BindingType.HttpRedirect)
                                     .Unbind(new HttpRequestData("GET", actual.Location), options);

            var actualMessage = actualUnbindResult.Data;

            var expectedMessage = XmlHelpers.XmlDocumentFromString(
                $@"<samlp:LogoutResponse xmlns:samlp=""urn:oasis:names:tc:SAML:2.0:protocol""
                    xmlns=""urn:oasis:names:tc:SAML:2.0:assertion""
                    Destination=""https://idp.example.com/logout""
                    Version=""2.0"">
                    <Issuer>{options.SPOptions.EntityId.Id}</Issuer>
                    <samlp:Status>
                        <samlp:StatusCode Value=""urn:oasis:names:tc:SAML:2.0:status:Success""/>
                    </samlp:Status>
                </samlp:LogoutResponse>").DocumentElement;

            // Set generated attributes to actual values.
            expectedMessage.SetAttribute("ID", actualMessage.GetAttribute("ID"));
            expectedMessage.SetAttribute("IssueInstant", actualMessage.GetAttribute("IssueInstant"));
            expectedMessage.SetAttribute("InResponseTo", request.Id.Value);

            actualMessage.Should().BeEquivalentTo(expectedMessage);

            actualUnbindResult.RelayState.Should().Be(request.RelayState);
            actualUnbindResult.TrustLevel.Should().Be(TrustLevel.Signature);
        }
Ejemplo n.º 30
0
        public dynamic BuildEditor(XElement description, XElement data, string prefix, IDictionary <string, IEnumerator <XElement> > dataEnumerators = null)
        {
            switch (description.Name.LocalName.ToLowerInvariant())
            {
            case "img":
                var src        = XmlHelpers.Attr(data, "src");
                var defaultUrl = XmlHelpers.Attr(description, "default");
                var defaultAlt = XmlHelpers.Attr(description, "defaultalt");
                return(Shape.LayoutElements_Image_Edit(
                           Name: T("Image"),
                           Url: src,
                           DefaultUrl: defaultUrl,
                           AlternateText: XmlHelpers.Attr(data, "alt"),
                           DefaultAlt: defaultAlt,
                           Title: XmlHelpers.Attr(description, "title"),
                           Prefix: prefix,
                           UsesIndex: true));

            case "text":
                var text        = XmlHelpers.Attr(data, "text");
                var defaultText = XmlHelpers.Attr(description, "default");
                return(Shape.LayoutElements_Text_Edit(
                           Name: T("Text"),
                           Text: text,
                           DefaultText: defaultText,
                           Title: XmlHelpers.Attr(description, "title"),
                           Prefix: prefix,
                           UsesIndex: true));

            case "link":
                var linkText        = XmlHelpers.Attr(data, "text");
                var defaultLinkText = XmlHelpers.Attr(description, "default");
                var href            = XmlHelpers.Attr(data, "href");
                var defaultHref     = XmlHelpers.Attr(description, "defaulturl");
                return(Shape.LayoutElements_Link_Edit(
                           Name: T("Link"),
                           Text: linkText,
                           DefaultText: defaultLinkText,
                           Url: href,
                           DefaultUrl: defaultHref,
                           Title: XmlHelpers.Attr(description, "title"),
                           Prefix: prefix,
                           UsesIndex: true));

            case "container":
                var      hasLink           = description.AttrBool("haslink");
                var      hasContext        = description.AttrBool("hascontext");
                var      hasBackground     = description.AttrBool("hasbackground");
                var      background        = XmlHelpers.Attr(data, "background");
                var      defaultBackground = XmlHelpers.Attr(description, "defaultbackground");
                IContent context           = null;
                if (hasContext)
                {
                    var contextId = data.AttrInt("context");
                    context = _contentManager.Get(contextId);
                }
                return(Shape.LayoutElements_Container_Edit(
                           Name: T("Container"),
                           Title: XmlHelpers.Attr(description, "title"),
                           HasTargetUrl: hasLink,
                           TargetUrl: XmlHelpers.Attr(data, "href"),
                           HasBackground: hasBackground,
                           Background: background,
                           DefaultBackground: defaultBackground,
                           Elements: _templateService.Value.GetLayoutElementEditors(
                               description, data, prefix, dataEnumerators).ToList(),
                           UsesIndex: hasLink || hasBackground || hasContext,
                           HasContext: hasContext,
                           Context: context,
                           Prefix: prefix));
            }
            return(null);
        }