Example #1
0
        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////

        internal static String GetReturnUrl(bool useDefaultIfAbsent)
        {
            Initialize();

            HttpContext context   = HttpContext.Current;
            String      returnUrl = context.Request.QueryString[ReturnUrlVar];

            // If it is not in the QueryString, look in the Posted-body
            if (returnUrl == null)
            {
                returnUrl = context.Request.Form[ReturnUrlVar];
                if (!string.IsNullOrEmpty(returnUrl) && !returnUrl.Contains("/") && returnUrl.Contains("%"))
                {
                    returnUrl = HttpUtility.UrlDecode(returnUrl);
                }
            }

            // Make sure it is on the current server if EnableCrossAppRedirects is false
            if (!string.IsNullOrEmpty(returnUrl) && !EnableCrossAppRedirects)
            {
                if (!UrlPath.IsPathOnSameServer(returnUrl, context.Request.Url))
                {
                    returnUrl = null;
                }
            }

            // Make sure it is not dangerous, i.e. does not contain script, etc.
            if (!string.IsNullOrEmpty(returnUrl) && CrossSiteScriptingValidation.IsDangerousUrl(returnUrl))
            {
                throw new HttpException(SR.GetString(SR.Invalid_redirect_return_url));
            }

            return((returnUrl == null && useDefaultIfAbsent) ? DefaultUrl : returnUrl);
        }
Example #2
0
        internal static string GetReturnUrl(bool useDefaultIfAbsent)
        {
            Initialize();
            HttpContext current = HttpContext.Current;
            string      str     = current.Request.QueryString["ReturnUrl"];

            if (str == null)
            {
                str = current.Request.Form["ReturnUrl"];
                if ((!string.IsNullOrEmpty(str) && !str.Contains("/")) && str.Contains("%"))
                {
                    str = HttpUtility.UrlDecode(str);
                }
            }
            if ((!string.IsNullOrEmpty(str) && !EnableCrossAppRedirects) && !UrlPath.IsPathOnSameServer(str, current.Request.Url))
            {
                str = null;
            }
            if (!string.IsNullOrEmpty(str) && CrossSiteScriptingValidation.IsDangerousUrl(str))
            {
                throw new HttpException(System.Web.SR.GetString("Invalid_redirect_return_url"));
            }
            if ((str == null) && useDefaultIfAbsent)
            {
                return(DefaultUrl);
            }
            return(str);
        }
        public override bool ApplyChanges()
        {
            object editableObject = GetEditableObject();

            Debug.Assert(editableObject != null);
            if (editableObject == null)
            {
                return(true);
            }

            EnsureChildControls();

            int count = Controls.Count;

            Debug.Assert(count > 0);
            if (count == 0)
            {
                return(true);
            }

            PropertyDescriptorCollection properties = GetEditableProperties(editableObject, true);

            for (int i = 0; i < properties.Count; i++)
            {
                PropertyDescriptor pd            = properties[i];
                Control            editorControl = (Control)EditorControls[i];
                try {
                    object value = GetEditorControlValue(editorControl, pd);
                    // If the property is a url, validate protocol (VSWhidbey 290418)
                    if (pd.Attributes.Matches(urlPropertyAttribute) &&
                        CrossSiteScriptingValidation.IsDangerousUrl(value.ToString()))
                    {
                        _errorMessages[i] = SR.GetString(SR.EditorPart_ErrorBadUrl);
                    }
                    else
                    {
                        try {
                            pd.SetValue(editableObject, value);
                        }
                        catch (Exception e) {
                            _errorMessages[i] = CreateErrorMessage(e.Message);
                        }
                    }
                }
                catch {
                    // If custom errors are enabled, we do not want to render the property type to the browser.
                    // (VSWhidbey 381646)
                    if (Context != null && Context.IsCustomErrorEnabled)
                    {
                        _errorMessages[i] = SR.GetString(SR.EditorPart_ErrorConvertingProperty);
                    }
                    else
                    {
                        _errorMessages[i] = SR.GetString(SR.EditorPart_ErrorConvertingPropertyWithType, pd.PropertyType.FullName);
                    }
                }
            }

            return(!HasError);
        }
Example #4
0
        public static string GeneratePassword(int length, int numberOfNonAlphanumericCharacters)
        {
            string str;
            int    num;

            if ((length < 1) || (length > 0x80))
            {
                throw new ArgumentException(System.Web.SR.GetString("Membership_password_length_incorrect"));
            }
            if ((numberOfNonAlphanumericCharacters > length) || (numberOfNonAlphanumericCharacters < 0))
            {
                throw new ArgumentException(System.Web.SR.GetString("Membership_min_required_non_alphanumeric_characters_incorrect", new object[] { "numberOfNonAlphanumericCharacters" }));
            }
            do
            {
                byte[] data    = new byte[length];
                char[] chArray = new char[length];
                int    num2    = 0;
                new RNGCryptoServiceProvider().GetBytes(data);
                for (int i = 0; i < length; i++)
                {
                    int num4 = data[i] % 0x57;
                    if (num4 < 10)
                    {
                        chArray[i] = (char)(0x30 + num4);
                    }
                    else if (num4 < 0x24)
                    {
                        chArray[i] = (char)((0x41 + num4) - 10);
                    }
                    else if (num4 < 0x3e)
                    {
                        chArray[i] = (char)((0x61 + num4) - 0x24);
                    }
                    else
                    {
                        chArray[i] = punctuations[num4 - 0x3e];
                        num2++;
                    }
                }
                if (num2 < numberOfNonAlphanumericCharacters)
                {
                    Random random = new Random();
                    for (int j = 0; j < (numberOfNonAlphanumericCharacters - num2); j++)
                    {
                        int num6;
                        do
                        {
                            num6 = random.Next(0, length);
                        }while (!char.IsLetterOrDigit(chArray[num6]));
                        chArray[num6] = punctuations[random.Next(0, punctuations.Length)];
                    }
                }
                str = new string(chArray);
            }while (CrossSiteScriptingValidation.IsDangerousString(str, out num));
            return(str);
        }
 protected internal virtual bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex)
 {
     if (requestValidationSource == RequestValidationSource.Headers)
     {
         validationFailureIndex = 0;
         return(true); // Ignore Headers collection in the default implementation
     }
     return(!CrossSiteScriptingValidation.IsDangerousString(value, out validationFailureIndex));
 }
Example #6
0
        /// <summary>
        /// Check user-supplied text and return true if it contains any HTML, otherwise false.
        /// </summary>
        public static bool ContainsHtml(string s, out int matchIndex)
        {
            if (string.IsNullOrEmpty(s))
            {
                matchIndex = -1;
                return(false);
            }

            return(CrossSiteScriptingValidation.IsDangerousString(s, true, out matchIndex));
        }
Example #7
0
        /// <summary>
        /// Check user-supplied text and return true if it contains any script, otherwise false. The check
        /// is not perfect and errs on the safe side, so it may sometimes return true when there is no
        /// actual script.
        /// </summary>
        public static bool ContainsScript(string s)
        {
            if (string.IsNullOrEmpty(s))
            {
                return(false);
            }

            int dummy;

            return(CrossSiteScriptingValidation.IsDangerousString(s, false, out dummy));
        }
        public override bool ApplyChanges()
        {
            object editableObject = this.GetEditableObject();

            if (editableObject == null)
            {
                return(true);
            }
            this.EnsureChildControls();
            if (this.Controls.Count == 0)
            {
                return(true);
            }
            PropertyDescriptorCollection editableProperties = this.GetEditableProperties(editableObject, true);

            for (int i = 0; i < editableProperties.Count; i++)
            {
                PropertyDescriptor pd            = editableProperties[i];
                Control            editorControl = (Control)this.EditorControls[i];
                try
                {
                    object editorControlValue = this.GetEditorControlValue(editorControl, pd);
                    if (pd.Attributes.Matches(urlPropertyAttribute) && CrossSiteScriptingValidation.IsDangerousUrl(editorControlValue.ToString()))
                    {
                        this._errorMessages[i] = System.Web.SR.GetString("EditorPart_ErrorBadUrl");
                    }
                    else
                    {
                        try
                        {
                            pd.SetValue(editableObject, editorControlValue);
                        }
                        catch (Exception exception)
                        {
                            this._errorMessages[i] = base.CreateErrorMessage(exception.Message);
                        }
                    }
                }
                catch
                {
                    if ((this.Context != null) && this.Context.IsCustomErrorEnabled)
                    {
                        this._errorMessages[i] = System.Web.SR.GetString("EditorPart_ErrorConvertingProperty");
                    }
                    else
                    {
                        this._errorMessages[i] = System.Web.SR.GetString("EditorPart_ErrorConvertingPropertyWithType", new object[] { pd.PropertyType.FullName });
                    }
                }
            }
            return(!this.HasError);
        }
Example #9
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            string s = value as string;

            if (string.IsNullOrEmpty(s))
            {
                return(ValidationResult.Success);
            }

            return(CrossSiteScriptingValidation.IsDangerousString(s, out int matchIndex)
                ? new ValidationResult($"{validationContext.DisplayName} contains a potentially dangerous value.")
                : ValidationResult.Success);
        }
Example #10
0
            public static string Password(int length, int numberOfNonAlphanumericCharacters)
            {
                string str;
                int    num;

                do
                {
                    byte[] data    = new byte[length];
                    char[] chArray = new char[length];
                    int    num2    = 0;
                    new RNGCryptoServiceProvider().GetBytes(data);
                    for (int i = 0; i < length; i++)
                    {
                        int num4 = data[i] % 0x57;
                        if (num4 < 10)
                        {
                            chArray[i] = (char)(0x30 + num4);
                        }
                        else if (num4 < 0x24)
                        {
                            chArray[i] = (char)((0x41 + num4) - 10);
                        }
                        else if (num4 < 0x3e)
                        {
                            chArray[i] = (char)((0x61 + num4) - 0x24);
                        }
                        else
                        {
                            chArray[i] = punctuations[num4 - 0x3e];
                            num2++;
                        }
                    }
                    if (num2 < numberOfNonAlphanumericCharacters)
                    {
                        Random random = new Random();
                        for (int j = 0; j < (numberOfNonAlphanumericCharacters - num2); j++)
                        {
                            int num6;
                            do
                            {
                                num6 = random.Next(0, length);
                            }while (!char.IsLetterOrDigit(chArray[num6]));
                            chArray[num6] = punctuations[random.Next(0, punctuations.Length)];
                        }
                    }
                    str = new string(chArray);
                }while (CrossSiteScriptingValidation.IsDangerousString(str, out num));
                return(str);
            }
Example #11
0
    internal static bool IsDangerousString(string s, out int matchIndex)
    {
        matchIndex = 0;
        int startIndex = 0;

        while (true)
        {
            int index = s.IndexOfAny(CrossSiteScriptingValidation.startingChars, startIndex);
            if (index >= 0 && index != s.Length - 1)
            {
                matchIndex = index;
                switch (s[index])
                {
                case '&':
                    if ((int)s[index + 1] != 35)
                    {
                        break;
                    }
                    else
                    {
                        goto label_7;
                    }

                case '<':
                    if (CrossSiteScriptingValidation.IsAtoZ(s[index + 1]) || (int)s[index + 1] == 33 || ((int)s[index + 1] == 47 || (int)s[index + 1] == 63))
                    {
                        goto label_5;
                    }
                    else
                    {
                        break;
                    }
                }
                startIndex = index + 1;
            }
            else
            {
                break;
            }
        }
        return(false);

label_5:
        return(true);

label_7:
        return(true);
    }
Example #12
0
        public async Task Invoke(HttpContext context)
        {
            // Check XSS in URL
            if (!string.IsNullOrWhiteSpace(context.Request.Path.Value))
            {
                var url = context.Request.Path.Value;

                if (CrossSiteScriptingValidation.IsDangerousString(url, out _))
                {
                    await RespondWithAnError(context).ConfigureAwait(false);

                    return;
                }
            }

            // Check XSS in query string
            if (!string.IsNullOrWhiteSpace(context.Request.QueryString.Value))
            {
                var queryString = WebUtility.UrlDecode(context.Request.QueryString.Value);

                if (CrossSiteScriptingValidation.IsDangerousString(queryString, out _))
                {
                    await RespondWithAnError(context).ConfigureAwait(false);

                    return;
                }
            }

            // Check XSS in request content
            var originalBody = context.Request.Body;

            try
            {
                var content = await ReadRequestBody(context);

                if (CrossSiteScriptingValidation.IsDangerousString(content, out _))
                {
                    await RespondWithAnError(context).ConfigureAwait(false);

                    return;
                }
                await _next(context).ConfigureAwait(false);
            }
            finally
            {
                context.Request.Body = originalBody;
            }
        }
Example #13
0
        /// <devdoc>
        /// Handles databinding the field and its controls.
        /// </devdoc>
        protected virtual void OnDataBindField(object sender, EventArgs e)
        {
            Control boundControl     = (Control)sender;
            Control controlContainer = boundControl.NamingContainer;
            string  urlValue         = null;
            string  nullImageUrl     = NullImageUrl;
            string  altText          = GetFormattedAlternateText(controlContainer);

            if (DesignMode && (boundControl is TableCell))
            {
                if (boundControl.Controls.Count == 0 || !(boundControl.Controls[0] is Image))
                {
                    throw new HttpException(SR.GetString(SR.ImageField_WrongControlType, DataImageUrlField));
                }
                ((Image)boundControl.Controls[0]).Visible = false;
                ((TableCell)boundControl).Text            = GetDesignTimeValue();
                return;
            }

            object data = GetValue(controlContainer, DataImageUrlField, ref _imageFieldDesc);

            urlValue = FormatImageUrlValue(data);
            if (boundControl is TableCell)      // read-only
            {
                TableCell cell = (TableCell)boundControl;
                if (cell.Controls.Count < 2 || !(cell.Controls[0] is Image) || !(cell.Controls[1] is Label))
                {
                    throw new HttpException(SR.GetString(SR.ImageField_WrongControlType, DataImageUrlField));
                }
                Image image = (Image)cell.Controls[0];
                Label label = (Label)cell.Controls[1];

                label.Visible = false;
                if (urlValue == null || (ConvertEmptyStringToNull && urlValue.Length == 0))
                {
                    if (nullImageUrl.Length > 0)
                    {
                        urlValue = nullImageUrl;
                    }
                    else
                    {
                        image.Visible = false;
                        label.Text    = NullDisplayText;
                        label.Visible = true;
                    }
                }
                if (!CrossSiteScriptingValidation.IsDangerousUrl(urlValue))
                {
                    image.ImageUrl = urlValue;
                }
                image.AlternateText = altText;
            }
            else    // edit/insert
            {
                if (!(boundControl is TextBox))
                {
                    throw new HttpException(SR.GetString(SR.ImageField_WrongControlType, DataImageUrlField));
                }
                ((TextBox)boundControl).Text    = data.ToString();
                ((TextBox)boundControl).ToolTip = altText;

                if (data != null)
                {
                    // size down the textbox for certain types
                    if (data.GetType().IsPrimitive)
                    {
                        ((TextBox)boundControl).Columns = 5;
                    }
                }
            }
        }
Example #14
0
        public override bool ApplyChanges()
        {
            WebPart webPart = WebPartToEdit;

            Debug.Assert(webPart != null);
            if (webPart != null)
            {
                EnsureChildControls();

                bool allowLayoutChange = webPart.Zone.AllowLayoutChange;

                if (allowLayoutChange)
                {
                    try {
                        webPart.AllowClose = _allowClose.Checked;
                    }
                    catch (Exception e) {
                        _allowCloseErrorMessage = CreateErrorMessage(e.Message);
                    }
                }

                try {
                    webPart.AllowConnect = _allowConnect.Checked;
                }
                catch (Exception e) {
                    _allowConnectErrorMessage = CreateErrorMessage(e.Message);
                }

                if (allowLayoutChange)
                {
                    try {
                        webPart.AllowHide = _allowHide.Checked;
                    }
                    catch (Exception e) {
                        _allowHideErrorMessage = CreateErrorMessage(e.Message);
                    }
                }

                if (allowLayoutChange)
                {
                    try {
                        webPart.AllowMinimize = _allowMinimize.Checked;
                    }
                    catch (Exception e) {
                        _allowMinimizeErrorMessage = CreateErrorMessage(e.Message);
                    }
                }

                if (allowLayoutChange)
                {
                    try {
                        webPart.AllowZoneChange = _allowZoneChange.Checked;
                    }
                    catch (Exception e) {
                        _allowZoneChangeErrorMessage = CreateErrorMessage(e.Message);
                    }
                }

                try {
                    TypeConverter exportModeConverter = TypeDescriptor.GetConverter(typeof(WebPartExportMode));
                    webPart.ExportMode = (WebPartExportMode)exportModeConverter.ConvertFromString(_exportMode.SelectedValue);
                }
                catch (Exception e) {
                    _exportModeErrorMessage = CreateErrorMessage(e.Message);
                }

                try {
                    TypeConverter helpModeConverter = TypeDescriptor.GetConverter(typeof(WebPartHelpMode));
                    webPart.HelpMode = (WebPartHelpMode)helpModeConverter.ConvertFromString(_helpMode.SelectedValue);
                }
                catch (Exception e) {
                    _helpModeErrorMessage = CreateErrorMessage(e.Message);
                }

                try {
                    webPart.Description = _description.Text;
                }
                catch (Exception e) {
                    _descriptionErrorMessage = CreateErrorMessage(e.Message);
                }

                string value = _titleUrl.Text;
                if (CrossSiteScriptingValidation.IsDangerousUrl(value))
                {
                    _titleUrlErrorMessage = SR.GetString(SR.EditorPart_ErrorBadUrl);
                }
                else
                {
                    try {
                        webPart.TitleUrl = value;
                    }
                    catch (Exception e) {
                        _titleUrlErrorMessage = CreateErrorMessage(e.Message);
                    }
                }

                value = _titleIconImageUrl.Text;
                if (CrossSiteScriptingValidation.IsDangerousUrl(value))
                {
                    _titleIconImageUrlErrorMessage = SR.GetString(SR.EditorPart_ErrorBadUrl);
                }
                else
                {
                    try {
                        webPart.TitleIconImageUrl = value;
                    }
                    catch (Exception e) {
                        _titleIconImageUrlErrorMessage = CreateErrorMessage(e.Message);
                    }
                }

                value = _catalogIconImageUrl.Text;
                if (CrossSiteScriptingValidation.IsDangerousUrl(value))
                {
                    _catalogIconImageUrlErrorMessage = SR.GetString(SR.EditorPart_ErrorBadUrl);
                }
                else
                {
                    try {
                        webPart.CatalogIconImageUrl = value;
                    }
                    catch (Exception e) {
                        _catalogIconImageUrlErrorMessage = CreateErrorMessage(e.Message);
                    }
                }

                value = _helpUrl.Text;
                if (CrossSiteScriptingValidation.IsDangerousUrl(value))
                {
                    _helpUrlErrorMessage = SR.GetString(SR.EditorPart_ErrorBadUrl);
                }
                else
                {
                    try {
                        webPart.HelpUrl = value;
                    }
                    catch (Exception e) {
                        _helpUrlErrorMessage = CreateErrorMessage(e.Message);
                    }
                }

                try {
                    webPart.ImportErrorMessage = _importErrorMessage.Text;
                }
                catch (Exception e) {
                    _importErrorMessageErrorMessage = CreateErrorMessage(e.Message);
                }

                try {
                    webPart.AuthorizationFilter = _authorizationFilter.Text;
                }
                catch (Exception e) {
                    _authorizationFilterErrorMessage = CreateErrorMessage(e.Message);
                }

                try {
                    webPart.AllowEdit = _allowEdit.Checked;
                }
                catch (Exception e) {
                    _allowEditErrorMessage = CreateErrorMessage(e.Message);
                }
            }

            return(!HasError);
        }
Example #15
0
        private void OnDataBindField(object sender, EventArgs e)
        {
            HyperLink link            = (HyperLink)sender;
            Control   namingContainer = link.NamingContainer;
            object    component       = null;

            if (namingContainer == null)
            {
                throw new HttpException(System.Web.SR.GetString("DataControlField_NoContainer"));
            }
            component = DataBinder.GetDataItem(namingContainer);
            if ((component == null) && !base.DesignMode)
            {
                throw new HttpException(System.Web.SR.GetString("DataItem_Not_Found"));
            }
            if ((this.textFieldDesc == null) && (this.urlFieldDescs == null))
            {
                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(component);
                string dataTextField = this.DataTextField;
                if (dataTextField.Length != 0)
                {
                    this.textFieldDesc = properties.Find(dataTextField, true);
                    if ((this.textFieldDesc == null) && !base.DesignMode)
                    {
                        throw new HttpException(System.Web.SR.GetString("Field_Not_Found", new object[] { dataTextField }));
                    }
                }
                string[] dataNavigateUrlFields = this.DataNavigateUrlFields;
                int      num = dataNavigateUrlFields.Length;
                this.urlFieldDescs = new PropertyDescriptor[num];
                for (int i = 0; i < num; i++)
                {
                    dataTextField = dataNavigateUrlFields[i];
                    if (dataTextField.Length != 0)
                    {
                        this.urlFieldDescs[i] = properties.Find(dataTextField, true);
                        if ((this.urlFieldDescs[i] == null) && !base.DesignMode)
                        {
                            throw new HttpException(System.Web.SR.GetString("Field_Not_Found", new object[] { dataTextField }));
                        }
                    }
                }
            }
            string str2 = string.Empty;

            if ((this.textFieldDesc != null) && (component != null))
            {
                object dataTextValue = this.textFieldDesc.GetValue(component);
                str2 = this.FormatDataTextValue(dataTextValue);
            }
            if ((base.DesignMode && (this.DataTextField.Length != 0)) && (str2.Length == 0))
            {
                str2 = System.Web.SR.GetString("Sample_Databound_Text");
            }
            if (str2.Length > 0)
            {
                link.Text = str2;
            }
            int    length = this.urlFieldDescs.Length;
            string str3   = string.Empty;

            if (((this.urlFieldDescs != null) && (length > 0)) && (component != null))
            {
                object[] dataUrlValues = new object[length];
                for (int j = 0; j < length; j++)
                {
                    if (this.urlFieldDescs[j] != null)
                    {
                        dataUrlValues[j] = this.urlFieldDescs[j].GetValue(component);
                    }
                }
                string s = this.FormatDataNavigateUrlValue(dataUrlValues);
                if (!CrossSiteScriptingValidation.IsDangerousUrl(s))
                {
                    str3 = s;
                }
            }
            if ((base.DesignMode && (this.DataNavigateUrlFields.Length != 0)) && (str3.Length == 0))
            {
                str3 = "url";
            }
            if (str3.Length > 0)
            {
                link.NavigateUrl = str3;
            }
        }
Example #16
0
        /// <devdoc>
        /// </devdoc>
        private void OnDataBindField(object sender, EventArgs e)
        {
            Debug.Assert((DataTextField.Length != 0) || (DataNavigateUrlFields.Length != 0),
                         "Shouldn't be DataBinding without a DataTextField and DataNavigateUrlField");

            HyperLink boundControl     = (HyperLink)sender;
            Control   controlContainer = boundControl.NamingContainer;
            object    dataItem         = null;


            if (controlContainer == null)
            {
                throw new HttpException(SR.GetString(SR.DataControlField_NoContainer));
            }

            // Get the DataItem from the container
            dataItem = DataBinder.GetDataItem(controlContainer);

            if (dataItem == null && !DesignMode)
            {
                throw new HttpException(SR.GetString(SR.DataItem_Not_Found));
            }

            if ((textFieldDesc == null) && (urlFieldDescs == null))
            {
                PropertyDescriptorCollection props = TypeDescriptor.GetProperties(dataItem);
                string fieldName;

                fieldName = DataTextField;
                if (fieldName.Length != 0)
                {
                    textFieldDesc = props.Find(fieldName, true);
                    if ((textFieldDesc == null) && !DesignMode)
                    {
                        throw new HttpException(SR.GetString(SR.Field_Not_Found, fieldName));
                    }
                }

                string[] dataNavigateUrlFields       = DataNavigateUrlFields;
                int      dataNavigateUrlFieldsLength = dataNavigateUrlFields.Length;
                urlFieldDescs = new PropertyDescriptor[dataNavigateUrlFieldsLength];

                for (int i = 0; i < dataNavigateUrlFieldsLength; i++)
                {
                    fieldName = dataNavigateUrlFields[i];
                    if (fieldName.Length != 0)
                    {
                        urlFieldDescs[i] = props.Find(fieldName, true);
                        if ((urlFieldDescs[i] == null) && !DesignMode)
                        {
                            throw new HttpException(SR.GetString(SR.Field_Not_Found, fieldName));
                        }
                    }
                }
            }

            string dataTextValue = String.Empty;

            if (textFieldDesc != null && dataItem != null)
            {
                object data = textFieldDesc.GetValue(dataItem);
                dataTextValue = FormatDataTextValue(data);
            }
            if (DesignMode && (DataTextField.Length != 0) && dataTextValue.Length == 0)
            {
                dataTextValue = SR.GetString(SR.Sample_Databound_Text);
            }

            if (dataTextValue.Length > 0)
            {
                boundControl.Text = dataTextValue;
            }

            int    urlFieldDescsLength = urlFieldDescs.Length;
            string dataNavValue        = String.Empty;

            if (urlFieldDescs != null && urlFieldDescsLength > 0 && dataItem != null)
            {
                object[] data = new object[urlFieldDescsLength];

                for (int i = 0; i < urlFieldDescsLength; i++)
                {
                    if (urlFieldDescs[i] != null)
                    {
                        data[i] = urlFieldDescs[i].GetValue(dataItem);
                    }
                }
                string urlValue = FormatDataNavigateUrlValue(data);
                if (!CrossSiteScriptingValidation.IsDangerousUrl(urlValue))
                {
                    dataNavValue = urlValue;
                }
            }
            if (DesignMode && (DataNavigateUrlFields.Length != 0) && dataNavValue.Length == 0)
            {
                dataNavValue = "url";
            }

            if (dataNavValue.Length > 0)
            {
                boundControl.NavigateUrl = dataNavValue;
            }
        }
        protected virtual void OnDataBindField(object sender, EventArgs e)
        {
            Control control         = (Control)sender;
            Control namingContainer = control.NamingContainer;
            string  s                      = null;
            string  nullImageUrl           = this.NullImageUrl;
            string  formattedAlternateText = this.GetFormattedAlternateText(namingContainer);

            if (base.DesignMode && (control is TableCell))
            {
                if ((control.Controls.Count == 0) || !(control.Controls[0] is Image))
                {
                    throw new HttpException(System.Web.SR.GetString("ImageField_WrongControlType", new object[] { this.DataImageUrlField }));
                }
                ((Image)control.Controls[0]).Visible = false;
                ((TableCell)control).Text            = this.GetDesignTimeValue();
            }
            else
            {
                object dataValue = this.GetValue(namingContainer, this.DataImageUrlField, ref this._imageFieldDesc);
                s = this.FormatImageUrlValue(dataValue);
                if (control is TableCell)
                {
                    TableCell cell = (TableCell)control;
                    if (((cell.Controls.Count < 2) || !(cell.Controls[0] is Image)) || !(cell.Controls[1] is Label))
                    {
                        throw new HttpException(System.Web.SR.GetString("ImageField_WrongControlType", new object[] { this.DataImageUrlField }));
                    }
                    Image image = (Image)cell.Controls[0];
                    Label label = (Label)cell.Controls[1];
                    label.Visible = false;
                    if ((s == null) || (this.ConvertEmptyStringToNull && (s.Length == 0)))
                    {
                        if (nullImageUrl.Length > 0)
                        {
                            s = nullImageUrl;
                        }
                        else
                        {
                            image.Visible = false;
                            label.Text    = this.NullDisplayText;
                            label.Visible = true;
                        }
                    }
                    if (!CrossSiteScriptingValidation.IsDangerousUrl(s))
                    {
                        image.ImageUrl = s;
                    }
                    image.AlternateText = formattedAlternateText;
                }
                else
                {
                    if (!(control is TextBox))
                    {
                        throw new HttpException(System.Web.SR.GetString("ImageField_WrongControlType", new object[] { this.DataImageUrlField }));
                    }
                    ((TextBox)control).Text    = dataValue.ToString();
                    ((TextBox)control).ToolTip = formattedAlternateText;
                    if ((dataValue != null) && dataValue.GetType().IsPrimitive)
                    {
                        ((TextBox)control).Columns = 5;
                    }
                }
            }
        }
Example #18
0
        public static string GeneratePassword(int length, int numberOfNonAlphanumericCharacters)
        {
            if (length < 1 || length > 128)
            {
                throw new ArgumentException(SR.GetString(SR.Membership_password_length_incorrect));
            }

            if (numberOfNonAlphanumericCharacters > length || numberOfNonAlphanumericCharacters < 0)
            {
                throw new ArgumentException(SR.GetString(SR.Membership_min_required_non_alphanumeric_characters_incorrect,
                                                         "numberOfNonAlphanumericCharacters"));
            }

            string password;
            int    index;

            byte[] buf;
            char[] cBuf;
            int    count;

            do
            {
                buf   = new byte[length];
                cBuf  = new char[length];
                count = 0;

                (new RNGCryptoServiceProvider()).GetBytes(buf);

                for (int iter = 0; iter < length; iter++)
                {
                    int i = (int)(buf[iter] % 87);
                    if (i < 10)
                    {
                        cBuf[iter] = (char)('0' + i);
                    }
                    else if (i < 36)
                    {
                        cBuf[iter] = (char)('A' + i - 10);
                    }
                    else if (i < 62)
                    {
                        cBuf[iter] = (char)('a' + i - 36);
                    }
                    else
                    {
                        cBuf[iter] = punctuations[i - 62];
                        count++;
                    }
                }

                if (count < numberOfNonAlphanumericCharacters)
                {
                    int    j, k;
                    Random rand = new Random();

                    for (j = 0; j < numberOfNonAlphanumericCharacters - count; j++)
                    {
                        do
                        {
                            k = rand.Next(0, length);
                        }while(!Char.IsLetterOrDigit(cBuf[k]));

                        cBuf[k] = punctuations[rand.Next(0, punctuations.Length)];
                    }
                }

                password = new string(cBuf);
            }while(CrossSiteScriptingValidation.IsDangerousString(password, out index));

            return(password);
        }
        private void CreateAvailableWebPartDescriptions()
        {
            if (this._availableWebPartDescriptions == null)
            {
                if ((base.WebPartManager == null) || string.IsNullOrEmpty(this._importedPartDescription))
                {
                    this._availableWebPartDescriptions = new WebPartDescriptionCollection();
                }
                else
                {
                    PermissionSet set = new PermissionSet(PermissionState.None);
                    set.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
                    set.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Minimal));
                    set.PermitOnly();
                    bool   flag        = true;
                    string str         = null;
                    string description = null;
                    string imageUrl    = null;
                    try
                    {
                        try
                        {
                            using (StringReader reader = new StringReader(this._importedPartDescription))
                            {
                                using (XmlTextReader reader2 = new XmlTextReader(reader))
                                {
                                    if (reader2 == null)
                                    {
                                        goto Label_02F7;
                                    }
                                    reader2.MoveToContent();
                                    reader2.MoveToContent();
                                    reader2.ReadStartElement("webParts");
                                    reader2.ReadStartElement("webPart");
                                    reader2.ReadStartElement("metaData");
                                    string str4 = null;
                                    string path = null;
                                    while (reader2.Name != "type")
                                    {
                                        reader2.Skip();
                                        if (reader2.EOF)
                                        {
                                            throw new EndOfStreamException();
                                        }
                                    }
                                    if (reader2.Name == "type")
                                    {
                                        str4 = reader2.GetAttribute("name");
                                        path = reader2.GetAttribute("src");
                                    }
                                    bool isShared = base.WebPartManager.Personalization.Scope == PersonalizationScope.Shared;
                                    if (!string.IsNullOrEmpty(str4))
                                    {
                                        PermissionSet set2 = new PermissionSet(PermissionState.None);
                                        set2.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
                                        set2.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Medium));
                                        CodeAccessPermission.RevertPermitOnly();
                                        flag = false;
                                        set2.PermitOnly();
                                        flag = true;
                                        Type type = WebPartUtil.DeserializeType(str4, true);
                                        CodeAccessPermission.RevertPermitOnly();
                                        flag = false;
                                        set.PermitOnly();
                                        flag = true;
                                        if (!base.WebPartManager.IsAuthorized(type, null, null, isShared))
                                        {
                                            this._importErrorMessage = System.Web.SR.GetString("WebPartManager_ForbiddenType");
                                        }
                                        else
                                        {
                                            if (type.IsSubclassOf(typeof(WebPart)) || type.IsSubclassOf(typeof(Control)))
                                            {
                                                goto Label_02DD;
                                            }
                                            this._importErrorMessage = System.Web.SR.GetString("WebPartManager_TypeMustDeriveFromControl");
                                        }
                                    }
                                    else
                                    {
                                        if (base.WebPartManager.IsAuthorized(typeof(UserControl), path, null, isShared))
                                        {
                                            goto Label_02DD;
                                        }
                                        this._importErrorMessage = System.Web.SR.GetString("WebPartManager_ForbiddenType");
                                    }
                                    return;

Label_021E:
                                    reader2.Read();
Label_0226:
                                    if (!reader2.EOF && ((reader2.NodeType != XmlNodeType.Element) || !(reader2.Name == "property")))
                                    {
                                        goto Label_021E;
                                    }
                                    if (reader2.EOF)
                                    {
                                        goto Label_02F7;
                                    }
                                    string attribute = reader2.GetAttribute("name");
                                    if (attribute == "Title")
                                    {
                                        str = reader2.ReadElementString();
                                    }
                                    else if (attribute == "Description")
                                    {
                                        description = reader2.ReadElementString();
                                    }
                                    else if (attribute == "CatalogIconImageUrl")
                                    {
                                        string s = reader2.ReadElementString().Trim();
                                        if (!CrossSiteScriptingValidation.IsDangerousUrl(s))
                                        {
                                            imageUrl = s;
                                        }
                                    }
                                    else
                                    {
                                        reader2.Read();
                                        goto Label_02DD;
                                    }
                                    if (((str != null) && (description != null)) && (imageUrl != null))
                                    {
                                        goto Label_02F7;
                                    }
                                    reader2.Read();
Label_02DD:
                                    if (!reader2.EOF)
                                    {
                                        goto Label_0226;
                                    }
                                }
Label_02F7:
                                if (string.IsNullOrEmpty(str))
                                {
                                    str = System.Web.SR.GetString("Part_Untitled");
                                }
                                this._availableWebPartDescriptions = new WebPartDescriptionCollection(new WebPartDescription[] { new WebPartDescription("ImportedWebPart", str, description, imageUrl) });
                            }
                        }
                        catch (XmlException)
                        {
                            this._importErrorMessage = System.Web.SR.GetString("WebPartManager_ImportInvalidFormat");
                        }
                        catch
                        {
                            this._importErrorMessage = !string.IsNullOrEmpty(this._importErrorMessage) ? this._importErrorMessage : System.Web.SR.GetString("WebPart_DefaultImportErrorMessage");
                        }
                        finally
                        {
                            if (flag)
                            {
                                CodeAccessPermission.RevertPermitOnly();
                            }
                        }
                    }
                    catch
                    {
                        throw;
                    }
                }
            }
        }
        private void CreateAvailableWebPartDescriptions()
        {
            if (_availableWebPartDescriptions != null)
            {
                return;
            }

            if (WebPartManager == null || String.IsNullOrEmpty(_importedPartDescription))
            {
                _availableWebPartDescriptions = new WebPartDescriptionCollection();
                return;
            }

            // Run in minimal trust
            PermissionSet pset = new PermissionSet(PermissionState.None);

            // add in whatever perms are appropriate
            pset.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
            pset.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Minimal));

            pset.PermitOnly();
            bool   permitOnly  = true;
            string title       = null;
            string description = null;
            string icon        = null;

            // Extra try-catch block to prevent elevation of privilege attack via exception filter
            try {
                try {
                    // Get the WebPart description from its saved XML description.
                    using (StringReader sr = new StringReader(_importedPartDescription)) {
                        using (XmlReader reader = XmlUtils.CreateXmlReader(sr)) {
                            if (reader != null)
                            {
                                reader.MoveToContent();
                                // Check if imported part is authorized

                                // Get to the metadata
                                reader.MoveToContent();
                                reader.ReadStartElement(WebPartManager.ExportRootElement);
                                reader.ReadStartElement(WebPartManager.ExportPartElement);
                                reader.ReadStartElement(WebPartManager.ExportMetaDataElement);

                                // Get the type name
                                string partTypeName        = null;
                                string userControlTypeName = null;
                                while (reader.Name != WebPartManager.ExportTypeElement)
                                {
                                    reader.Skip();
                                    if (reader.EOF)
                                    {
                                        throw new EndOfStreamException();
                                    }
                                }
                                if (reader.Name == WebPartManager.ExportTypeElement)
                                {
                                    partTypeName        = reader.GetAttribute(WebPartManager.ExportTypeNameAttribute);
                                    userControlTypeName = reader.GetAttribute(WebPartManager.ExportUserControlSrcAttribute);
                                }

                                // If we are in shared scope, we are importing a shared WebPart
                                bool isShared = (WebPartManager.Personalization.Scope == PersonalizationScope.Shared);

                                if (!String.IsNullOrEmpty(partTypeName))
                                {
                                    // Need medium trust to call BuildManager.GetType()
                                    PermissionSet mediumPset = new PermissionSet(PermissionState.None);
                                    mediumPset.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
                                    mediumPset.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Medium));

                                    CodeAccessPermission.RevertPermitOnly();
                                    permitOnly = false;
                                    mediumPset.PermitOnly();
                                    permitOnly = true;

                                    Type partType = WebPartUtil.DeserializeType(partTypeName, true);

                                    CodeAccessPermission.RevertPermitOnly();
                                    permitOnly = false;
                                    pset.PermitOnly();
                                    permitOnly = true;

                                    // First check if the type is authorized
                                    if (!WebPartManager.IsAuthorized(partType, null, null, isShared))
                                    {
                                        _importErrorMessage = SR.GetString(SR.WebPartManager_ForbiddenType);
                                        return;
                                    }
                                    // If the type is not a webpart, create a generic Web Part
                                    if (!partType.IsSubclassOf(typeof(WebPart)) && !partType.IsSubclassOf(typeof(Control)))
                                    {
                                        // We only allow for Controls (VSWhidbey 428511)
                                        _importErrorMessage = SR.GetString(SR.WebPartManager_TypeMustDeriveFromControl);
                                        return;
                                    }
                                }
                                else
                                {
                                    // Check if the path is authorized
                                    if (!WebPartManager.IsAuthorized(typeof(UserControl), userControlTypeName, null, isShared))
                                    {
                                        _importErrorMessage = SR.GetString(SR.WebPartManager_ForbiddenType);
                                        return;
                                    }
                                }
                                while (!reader.EOF)
                                {
                                    while (!reader.EOF && !(reader.NodeType == XmlNodeType.Element &&
                                                            reader.Name == WebPartManager.ExportPropertyElement))
                                    {
                                        reader.Read();
                                    }
                                    if (reader.EOF)
                                    {
                                        break;
                                    }
                                    string name = reader.GetAttribute(WebPartManager.ExportPropertyNameAttribute);
                                    if (name == TitlePropertyName)
                                    {
                                        title = reader.ReadElementString();
                                    }
                                    else if (name == DescriptionPropertyName)
                                    {
                                        description = reader.ReadElementString();
                                    }
                                    else if (name == IconPropertyName)
                                    {
                                        string url = reader.ReadElementString().Trim();
                                        if (!CrossSiteScriptingValidation.IsDangerousUrl(url))
                                        {
                                            icon = url;
                                        }
                                    }
                                    else
                                    {
                                        reader.Read();
                                        continue;
                                    }
                                    if (title != null && description != null && icon != null)
                                    {
                                        break;
                                    }
                                    reader.Read();
                                }
                            }
                        }
                        if (String.IsNullOrEmpty(title))
                        {
                            title = SR.GetString(SR.Part_Untitled);
                        }

                        _availableWebPartDescriptions = new WebPartDescriptionCollection(
                            new WebPartDescription[] { new WebPartDescription(ImportedWebPartID, title, description, icon) });
                    }
                }
                catch (XmlException) {
                    _importErrorMessage = SR.GetString(SR.WebPartManager_ImportInvalidFormat);
                    return;
                }
                catch {
                    _importErrorMessage = (!String.IsNullOrEmpty(_importErrorMessage)) ?
                                          _importErrorMessage :
                                          SR.GetString(SR.WebPart_DefaultImportErrorMessage);
                    return;
                }
                finally {
                    if (permitOnly)
                    {
                        // revert if you're not just exiting the stack frame anyway
                        CodeAccessPermission.RevertPermitOnly();
                    }
                }
            }
            catch {
                throw;
            }
        }
        public override bool ApplyChanges()
        {
            WebPart webPartToEdit = base.WebPartToEdit;

            if (webPartToEdit != null)
            {
                this.EnsureChildControls();
                bool allowLayoutChange = webPartToEdit.Zone.AllowLayoutChange;
                if (allowLayoutChange)
                {
                    try
                    {
                        webPartToEdit.AllowClose = this._allowClose.Checked;
                    }
                    catch (Exception exception)
                    {
                        this._allowCloseErrorMessage = base.CreateErrorMessage(exception.Message);
                    }
                }
                try
                {
                    webPartToEdit.AllowConnect = this._allowConnect.Checked;
                }
                catch (Exception exception2)
                {
                    this._allowConnectErrorMessage = base.CreateErrorMessage(exception2.Message);
                }
                if (allowLayoutChange)
                {
                    try
                    {
                        webPartToEdit.AllowHide = this._allowHide.Checked;
                    }
                    catch (Exception exception3)
                    {
                        this._allowHideErrorMessage = base.CreateErrorMessage(exception3.Message);
                    }
                }
                if (allowLayoutChange)
                {
                    try
                    {
                        webPartToEdit.AllowMinimize = this._allowMinimize.Checked;
                    }
                    catch (Exception exception4)
                    {
                        this._allowMinimizeErrorMessage = base.CreateErrorMessage(exception4.Message);
                    }
                }
                if (allowLayoutChange)
                {
                    try
                    {
                        webPartToEdit.AllowZoneChange = this._allowZoneChange.Checked;
                    }
                    catch (Exception exception5)
                    {
                        this._allowZoneChangeErrorMessage = base.CreateErrorMessage(exception5.Message);
                    }
                }
                try
                {
                    TypeConverter converter = TypeDescriptor.GetConverter(typeof(WebPartExportMode));
                    webPartToEdit.ExportMode = (WebPartExportMode)converter.ConvertFromString(this._exportMode.SelectedValue);
                }
                catch (Exception exception6)
                {
                    this._exportModeErrorMessage = base.CreateErrorMessage(exception6.Message);
                }
                try
                {
                    TypeConverter converter2 = TypeDescriptor.GetConverter(typeof(WebPartHelpMode));
                    webPartToEdit.HelpMode = (WebPartHelpMode)converter2.ConvertFromString(this._helpMode.SelectedValue);
                }
                catch (Exception exception7)
                {
                    this._helpModeErrorMessage = base.CreateErrorMessage(exception7.Message);
                }
                try
                {
                    webPartToEdit.Description = this._description.Text;
                }
                catch (Exception exception8)
                {
                    this._descriptionErrorMessage = base.CreateErrorMessage(exception8.Message);
                }
                string text = this._titleUrl.Text;
                if (CrossSiteScriptingValidation.IsDangerousUrl(text))
                {
                    this._titleUrlErrorMessage = System.Web.SR.GetString("EditorPart_ErrorBadUrl");
                }
                else
                {
                    try
                    {
                        webPartToEdit.TitleUrl = text;
                    }
                    catch (Exception exception9)
                    {
                        this._titleUrlErrorMessage = base.CreateErrorMessage(exception9.Message);
                    }
                }
                text = this._titleIconImageUrl.Text;
                if (CrossSiteScriptingValidation.IsDangerousUrl(text))
                {
                    this._titleIconImageUrlErrorMessage = System.Web.SR.GetString("EditorPart_ErrorBadUrl");
                }
                else
                {
                    try
                    {
                        webPartToEdit.TitleIconImageUrl = text;
                    }
                    catch (Exception exception10)
                    {
                        this._titleIconImageUrlErrorMessage = base.CreateErrorMessage(exception10.Message);
                    }
                }
                text = this._catalogIconImageUrl.Text;
                if (CrossSiteScriptingValidation.IsDangerousUrl(text))
                {
                    this._catalogIconImageUrlErrorMessage = System.Web.SR.GetString("EditorPart_ErrorBadUrl");
                }
                else
                {
                    try
                    {
                        webPartToEdit.CatalogIconImageUrl = text;
                    }
                    catch (Exception exception11)
                    {
                        this._catalogIconImageUrlErrorMessage = base.CreateErrorMessage(exception11.Message);
                    }
                }
                text = this._helpUrl.Text;
                if (CrossSiteScriptingValidation.IsDangerousUrl(text))
                {
                    this._helpUrlErrorMessage = System.Web.SR.GetString("EditorPart_ErrorBadUrl");
                }
                else
                {
                    try
                    {
                        webPartToEdit.HelpUrl = text;
                    }
                    catch (Exception exception12)
                    {
                        this._helpUrlErrorMessage = base.CreateErrorMessage(exception12.Message);
                    }
                }
                try
                {
                    webPartToEdit.ImportErrorMessage = this._importErrorMessage.Text;
                }
                catch (Exception exception13)
                {
                    this._importErrorMessageErrorMessage = base.CreateErrorMessage(exception13.Message);
                }
                try
                {
                    webPartToEdit.AuthorizationFilter = this._authorizationFilter.Text;
                }
                catch (Exception exception14)
                {
                    this._authorizationFilterErrorMessage = base.CreateErrorMessage(exception14.Message);
                }
                try
                {
                    webPartToEdit.AllowEdit = this._allowEdit.Checked;
                }
                catch (Exception exception15)
                {
                    this._allowEditErrorMessage = base.CreateErrorMessage(exception15.Message);
                }
            }
            return(!this.HasError);
        }