Пример #1
0
		public LosFormatter (bool enableMac, string macKeyModifier)
		{
			osf = new ObjectStateFormatter ();
			if (enableMac && macKeyModifier != null && macKeyModifier.Length > 0) {
				SetMacKey (Convert.FromBase64String (macKeyModifier));
			}
		}
        public override void Load()
        {
            // depend on HiddenFieldPageStatePersister for heavy lifting and crypto
            base.Load();

            CompressedSerializedData compressedData = ViewState as CompressedSerializedData;
            if (compressedData == null && ControlState != null)
            {
                // the underlying data was not compressed
                return;
            }

            // decompress
            using (MemoryStream uncompressedStream = new MemoryStream())
            {
                using (GZipStream zipStream = new GZipStream(uncompressedStream, CompressionMode.Decompress, leaveOpen: true))
                {
                    zipStream.Write(compressedData.RawData, 0, compressedData.RawData.Length);
                }

                uncompressedStream.Position = 0;
                ObjectStateFormatter formatter = new ObjectStateFormatter();
                Pair pair = (Pair)formatter.Deserialize(uncompressedStream);

                // extract
                ViewState = pair.First;
                ControlState = pair.Second;
            }
        }
Пример #3
0
		public LosFormatter (bool enableMac, byte[] macKeyModifier)
		{
			if (enableMac)
				osf = new ObjectStateFormatter (macKeyModifier);
			else
				osf = new ObjectStateFormatter ();
		}
        public override void Save()
        {
            using (MemoryStream uncompressedStream = new MemoryStream())
            {
                ObjectStateFormatter formatter = new ObjectStateFormatter();
                formatter.Serialize(uncompressedStream, new Pair(ViewState, ControlState));

                using (MemoryStream compressedStream = new MemoryStream())
                {
                    using (GZipStream zipStream = new GZipStream(compressedStream, CompressionLevel.Optimal, leaveOpen: true))
                    {
                        zipStream.Write(uncompressedStream.GetBuffer(), 0, checked((int)uncompressedStream.Length));
                    }

                    if (uncompressedStream.Length > compressedStream.Length)
                    {
                        // compressing will probably save space
                        // CompressedSerializeData uses BinaryFormatter, which ObjectStateFormatter serializes better than byte[]
                        ViewState = new CompressedSerializedData() { RawData = compressedStream.ToArray() };
                        ControlState = null;
                    }

                    // depend on HiddenFieldPageStatePersister for heavy lifting and crypto
                    base.Save();
                }
            }
        }
Пример #5
0
		public LosFormatter (bool enableMac, byte[] macKeyModifier)
		{
			osf = new ObjectStateFormatter ();
			if (enableMac && (macKeyModifier != null)) {
				SetMacKey (macKeyModifier);
			}
		}
Пример #6
0
		public LosFormatter (bool enableMac, string macKeyModifier)
		{
			osf = new ObjectStateFormatter ();
			if (enableMac && !String.IsNullOrEmpty (macKeyModifier)) {
				SetMacKey (Convert.FromBase64String (macKeyModifier));
			}
		}
Пример #7
0
 public LosFormatter(bool enableMac, string macKeyModifier)
 {
     osf = new ObjectStateFormatter();
     if (enableMac && macKeyModifier != null && macKeyModifier.Length > 0)
     {
         SetMacKey(Convert.FromBase64String(macKeyModifier));
     }
 }
Пример #8
0
 LosFormatter(bool enableMac, byte[] macKeyModifier)
 {
     osf = new ObjectStateFormatter();
     if (enableMac && (macKeyModifier != null))
     {
         SetMacKey(macKeyModifier);
     }
 }
Пример #9
0
 public LosFormatter(bool enableMac, byte[] macKeyModifier) {
     _enableMac = enableMac;
     if (enableMac) {
         _formatter = new ObjectStateFormatter(macKeyModifier);
     }
     else {
         _formatter = new ObjectStateFormatter();
     }
 }
Пример #10
0
 protected override void SavePageStateToPersistenceMedium(object state)
 {
     string value = new ObjectStateFormatter().Serialize(state);
     string viewStateID = (DateTime.Now.Ticks + (long)this.GetHashCode()).ToString(); //产生离散的id号码
     string fn = Server.MapPath(@"~/App_Data/ViewState/" + viewStateID);
     //ThreadPool.QueueUserWorkItem(File.WriteAllText(fn, value));
     File.WriteAllText(fn, value);
     Cache.Insert(viewStateID, value);
     base.SavePageStateToPersistenceMedium(viewStateID);
 }
Пример #11
0
 LosFormatter(bool enableMac, byte[] macKeyModifier)
 {
     if (enableMac)
     {
         osf = new ObjectStateFormatter(macKeyModifier);
     }
     else
     {
         osf = new ObjectStateFormatter();
     }
 }
Пример #12
0
 public LosFormatter(bool enableMac, byte[] macKeyModifier)
 {
     _enableMac = enableMac;
     if (enableMac)
     {
         _formatter = new ObjectStateFormatter(macKeyModifier);
     }
     else
     {
         _formatter = new ObjectStateFormatter();
     }
 }
Пример #13
0
            public void readExternal(java.io.ObjectInput __p1)
            {
                Page page = CurrentPage;
                ObjectStateFormatter osf         = new ObjectStateFormatter(page);
                ObjectInputStream    inputStream = new ObjectInputStream(__p1);

                if (page.NeedViewStateEncryption || page.EnableViewStateMac)
                {
                    _state = osf.Deserialize((string)inputStream.readObject());
                }
                else
                {
                    _state = osf.Deserialize(inputStream);
                }
            }
Пример #14
0
            public void writeExternal(java.io.ObjectOutput __p1)
            {
                Page page = CurrentPage;
                ObjectStateFormatter osf          = new ObjectStateFormatter(page);
                ObjectOutputStream   outputStream = new ObjectOutputStream(__p1);

                if (page.NeedViewStateEncryption || page.EnableViewStateMac)
                {
                    outputStream.writeObject(osf.Serialize(_state));
                }
                else
                {
                    osf.Serialize(outputStream, _state);
                }
            }
Пример #15
0
 public LosFormatter()
 {
     osf = new ObjectStateFormatter();
 }
Пример #16
0
        private void context_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            var app = sender as HttpApplication;

            if (app != null)
            {
                var ctx = app.Context;

                if (ctx.Request.AppRelativeCurrentExecutionFilePath.ToLowerInvariant().Contains("MakeTransfer.aspx".ToLowerInvariant()))
                {
                    return;
                }

                if (ctx.Handler != null)
                {
                    var page = ctx.Handler as Page;

                    if (page != null)
                    {
                        page.PreRender += page_PreRender;

                        if (ctx.Request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
                        {
                            var cookie = ctx.Request.Cookies[cookieName];
                            var hidden = ctx.Request.Form[hiddenField];
                            var cookieValue = string.Empty;

                            if (cookie != null)
                            {
                                cookieValue = cookie.Value;
                            }

                            if (string.IsNullOrWhiteSpace(cookieValue) && string.IsNullOrWhiteSpace(hidden))
                            {
                                throw new Exception("Cookie and Form field missing");
                            }

                            if (string.IsNullOrWhiteSpace(cookieValue))
                            {
                                throw new Exception("Cookie missing");
                            }

                            if (string.IsNullOrWhiteSpace(hidden))
                            {
                                throw new Exception("Form field missing");
                            }

                            var tokenField = string.Empty;
                            var osf = new ObjectStateFormatter();

                            try
                            {
                                tokenField = osf.Deserialize(hidden).ToString();
                                //tokenField = hidden;
                            }
                            catch
                            {
                                throw new Exception("Invalid form field format");
                            }

                            if (string.IsNullOrWhiteSpace(tokenField))
                            {
                                throw new Exception("Invalid token");
                            }

                            if (!tokenField.Equals(cookieValue))
                            {
                                throw new Exception("Tokens mismatch");
                            }
                        }
                    }
                }
            }
        }
Пример #17
0
        private void page_PreRender(object sender, EventArgs e)
        {
            var page = sender as Page;
            var ctx = HttpContext.Current;

            if (page != null && page.Form != null)
            {
                var csrfToken = string.Empty;

                if (
                    ctx.Request != null ||
                    ctx.Request.Cookies != null ||
                    ctx.Request.Cookies[cookieName] == null ||
                    string.IsNullOrWhiteSpace(ctx.Request.Cookies[cookieName].Value))
                {
                    csrfToken = Guid.NewGuid().ToString("D", CultureInfo.InvariantCulture);
                    ctx.Items[csrfCtx] = csrfToken;
                }
                else
                {
                    csrfToken = page.Request.Cookies[cookieName].Value;
                }

                var osf = new ObjectStateFormatter();

                page.ClientScript.RegisterHiddenField(hiddenField, osf.Serialize(csrfToken));
                //page.ClientScript.RegisterHiddenField(hiddenField, csrfToken);
            }
        }
            private static SessionStateItem LoadItem(MemoryStream ms)
            {
                var graph = new ObjectStateFormatter().Deserialize(ms) as Pair;
                if (graph == null) return null;

                if (((byte)graph.First) != 1) return null;

                var t = (Triplet)graph.Second;
                var retval = new SessionStateItem();

                retval.Flag = (SessionStateActions)((byte)t.First);
                retval.Timeout = (int)t.Second;

                var lockInfo = (Pair)t.Third;

                retval.LockId = (ulong)lockInfo.First;
                retval.LockTime = DateTime.FromBinary((long)lockInfo.Second);

                return retval;
            }
Пример #19
0
 public static string StringSerialize(object source)
 {
     ObjectStateFormatter osf = new ObjectStateFormatter();
     return osf.Serialize(source);
 }
Пример #20
0
        /// <summary>
        /// Returns this <see cref="UploadSession" /> instance serialized into a string.
        /// </summary>
        /// <returns>The serialized string.</returns>
        public string Serialize()
        {
            ObjectStateFormatter formatter = new ObjectStateFormatter();

            return formatter.Serialize(ToObjectArray());
        }
Пример #21
0
		public void SerializeOverloads ()
		{
			ObjectStateFormatter osf = new ObjectStateFormatter ();
			string s1 = osf.Serialize (String.Empty);
			string s2;
			using (MemoryStream ms = new MemoryStream ()) {
				osf.Serialize (ms, String.Empty);
				s2 = Convert.ToBase64String (ms.ToArray ());
			}
			Assert.AreEqual (s1, s2, "identical");
		}
Пример #22
0
		public LosFormatter ()
		{
			osf = new ObjectStateFormatter ();
		}
        /// <devdoc>
        /// Deserializes personalization data packed as a blob of binary data
        /// into a dictionary with personalization IDs mapped to
        /// PersonalizationInfo objects.
        /// </devdoc>
        private static IDictionary DeserializeData(byte[] data) {
            IDictionary deserializedData = null;

            if ((data != null) && (data.Length > 0)) {
                Exception deserializationException = null;
                int version = -1;

                object[] items = null;
                int offset = 0;

                // Deserialize the data
                try {
                    ObjectStateFormatter formatter =
                        new ObjectStateFormatter(null /* Page(used to determine encryption mode) */, false /*throwOnErrorDeserializing*/);

                    if (!HttpRuntime.DisableProcessRequestInApplicationTrust) {
                        // This is more of a consistency and defense-in-depth fix.  Currently we believe
                        // only user code or code with restricted permissions will be running on the stack.
                        // However, to mirror the fix for Session State, and also to hedge against future
                        // scenarios where our current assumptions may change, we should restrict the running
                        // thread to only the permission set currently defined for the app domain.
                        // VSWhidbey 427533
                        if (HttpRuntime.NamedPermissionSet != null && HttpRuntime.ProcessRequestInApplicationTrust) {
                            HttpRuntime.NamedPermissionSet.PermitOnly();
                        }
                    }

                    items = (object[])formatter.DeserializeWithAssert(new MemoryStream(data));
                    if (items != null && items.Length != 0) {
                        version = (int)items[offset++];
                    }
                }
                catch (Exception e) {
                    deserializationException = e;
                }

                if (version == (int)PersonalizationVersions.WhidbeyBeta2 || version == (int)PersonalizationVersions.WhidbeyRTM) {
                    try {
                        // Build up the dictionary of PersonalizationInfo objects
                        int infoListCount = (int)items[offset++];

                        if (infoListCount > 0) {
                            deserializedData = new HybridDictionary(infoListCount, /* caseInsensitive */ false);
                        }

                        for (int i = 0; i < infoListCount; i++) {
                            string controlID;
                            bool isStatic;
                            Type controlType = null;
                            VirtualPath controlVPath = null;

                            // If this is a dynamic WebPart or control, the Type is not saved in personalization,
                            // so the first item is the controlID.  If this is a static WebPart or control, the
                            // first item is the control Type.
                            object item = items[offset++];
                            if (item is string) {
                                controlID = (string)item;
                                isStatic = false;
                            }
                            else {
                                controlType = (Type)item;
                                if (controlType == typeof(UserControl)) {
                                    controlVPath = VirtualPath.CreateNonRelativeAllowNull((string)items[offset++]);
                                }
                                controlID = (string)items[offset++];
                                isStatic = true;
                            }

                            IDictionary properties = null;
                            int propertyCount = (int)items[offset++];
                            if (propertyCount > 0) {
                                properties = new HybridDictionary(propertyCount, /* caseInsensitive */ false);
                                for (int j = 0; j < propertyCount; j++) {
                                    string propertyName = ((IndexedString)items[offset++]).Value;
                                    object propertyValue = items[offset++];

                                    properties[propertyName] = propertyValue;
                                }
                            }

                            PersonalizationDictionary customProperties = null;
                            int customPropertyCount = (int)items[offset++];
                            if (customPropertyCount > 0) {
                                customProperties = new PersonalizationDictionary(customPropertyCount);
                                for (int j = 0; j < customPropertyCount; j++) {
                                    string propertyName = ((IndexedString)items[offset++]).Value;
                                    object propertyValue = items[offset++];
                                    PersonalizationScope propertyScope =
                                        (bool)items[offset++] ? PersonalizationScope.Shared : PersonalizationScope.User;
                                    bool isSensitive = false;
                                    if (version == (int)PersonalizationVersions.WhidbeyRTM) {
                                        isSensitive = (bool)items[offset++];
                                    }

                                    customProperties[propertyName] =
                                        new PersonalizationEntry(propertyValue, propertyScope, isSensitive);
                                }
                            }

                            PersonalizationInfo info = new PersonalizationInfo();
                            info._controlID = controlID;
                            info._controlType = controlType;
                            info._controlVPath = controlVPath;
                            info._isStatic = isStatic;
                            info._properties = properties;
                            info._customProperties = customProperties;

                            deserializedData[controlID] = info;
                        }
                    }
                    catch (Exception e) {
                        deserializationException = e;
                    }
                }

                // Check that there was no deserialization error, and that
                // the data conforms to our known version
                if ((deserializationException != null) ||
                    (version != (int)PersonalizationVersions.WhidbeyBeta2 && version != (int)PersonalizationVersions.WhidbeyRTM)) {
                    throw new ArgumentException(SR.GetString(SR.BlobPersonalizationState_DeserializeError),
                                                "data", deserializationException);
                }
            }

            if (deserializedData == null) {
                deserializedData = new HybridDictionary(/* caseInsensitive */ false);
            }

            return deserializedData;
        }
        /// <devdoc>
        /// Serializes a dictionary of IDs mapped to PersonalizationInfo
        /// objects into a binary blob.
        /// </devdoc>
        private static byte[] SerializeData(IDictionary data) {
            byte[] serializedData = null;

            if ((data == null) || (data.Count == 0)) {
                return serializedData;
            }

            ArrayList infoList = new ArrayList();
            foreach (DictionaryEntry entry in data) {
                PersonalizationInfo info = (PersonalizationInfo)entry.Value;

                if (((info._properties != null) && (info._properties.Count != 0)) ||
                    ((info._customProperties != null) && (info._customProperties.Count != 0))){
                    infoList.Add(info);
                }
            }

            if (infoList.Count != 0) {
                ArrayList items = new ArrayList();

                items.Add(PersonalizationVersion);
                items.Add(infoList.Count);

                foreach (PersonalizationInfo info in infoList) {
                    // Only need to save the type information for static WebParts
                    if (info._isStatic) {
                        items.Add(info._controlType);
                        if (info._controlVPath != null) {
                            items.Add(info._controlVPath.AppRelativeVirtualPathString);
                        }
                    }

                    items.Add(info._controlID);

                    int propertyCount = 0;
                    if (info._properties != null) {
                        propertyCount = info._properties.Count;
                    }
                    items.Add(propertyCount);
                    if (propertyCount != 0) {
                        foreach (DictionaryEntry propertyEntry in info._properties) {
                            items.Add(new IndexedString((string)propertyEntry.Key));
                            items.Add(propertyEntry.Value);
                        }
                    }

                    int customPropertyCount = 0;
                    if (info._customProperties != null) {
                        customPropertyCount = info._customProperties.Count;
                    }
                    items.Add(customPropertyCount);
                    if (customPropertyCount != 0) {
                        foreach (DictionaryEntry customPropertyEntry in info._customProperties) {
                            items.Add(new IndexedString((string)customPropertyEntry.Key));
                            PersonalizationEntry personalizationEntry = (PersonalizationEntry)customPropertyEntry.Value;
                            items.Add(personalizationEntry.Value);
                            // PERF: Add a boolean instead of the Enum value
                            items.Add(personalizationEntry.Scope == PersonalizationScope.Shared);
                            // The IsSensitive property was added between Whidbey Beta2 and Whidbey RTM.
                            // VSWhidbey 502554 and 536907
                            items.Add(personalizationEntry.IsSensitive);
                        }
                    }
                }

                if (items.Count != 0) {
                    ObjectStateFormatter formatter = new ObjectStateFormatter(null, false);
                    MemoryStream ms = new MemoryStream(1024);
                    object[] state = items.ToArray();

                    if (!HttpRuntime.DisableProcessRequestInApplicationTrust){ 
                        // This is more of a consistency and defense-in-depth fix.  Currently we believe
                        // only user code or code with restricted permissions will be running on the stack.
                        // However, to mirror the fix for Session State, and also to hedge against future
                        // scenarios where our current assumptions may change, we should restrict the running
                        // thread to only the permission set currently defined for the app domain.
                        // VSWhidbey 491449
                        if (HttpRuntime.NamedPermissionSet != null && HttpRuntime.ProcessRequestInApplicationTrust) {
                            HttpRuntime.NamedPermissionSet.PermitOnly();
                        }
                    }

                    formatter.SerializeWithAssert(ms, state);

                    serializedData = ms.ToArray();
                }
            }

            return serializedData;
        }
Пример #25
0
        internal static string GetSerializedString(object data)
        {
            string dataString;

            ObjectStateFormatter formatter = new ObjectStateFormatter();

            if (data is UploadSession)
                dataString = "session-" + ((UploadSession)data).Serialize();
            else if (data is UploadRequest)
                dataString = "request-" + ((UploadRequest)data).Serialize();
            else if (data is IEnumerable<UploadSession>)
            {
                List<string> serializedStrings = new List<string>();

                foreach (UploadSession session in (IEnumerable<UploadSession>)data)
                    serializedStrings.Add(session.Serialize());

                dataString = "sessionlist-" + formatter.Serialize(serializedStrings.ToArray());
            }
            else if (data is IEnumerable<UploadRequest>)
            {
                List<string> serializedStrings = new List<string>();

                foreach (UploadRequest request in (IEnumerable<UploadRequest>)data)
                    serializedStrings.Add(request.Serialize());

                dataString = "requestlist-" + formatter.Serialize(serializedStrings.ToArray());
            }
            else
                dataString = formatter.Serialize(data);

            // TODO: encrypt
            return dataString;
        }
Пример #26
0
        /// <summary>
        /// Deserializes a string generated by <see cref="UploadSession.Serialize" /> into an <see cref="UploadSession" /> instance.
        /// </summary>
        /// <param name="value">The string to deserialize.</param>
        /// <returns>An <see cref="UploadSession" /> instance.</returns>
        public static UploadSession Deserialize(string value)
        {
            ObjectStateFormatter formatter = new ObjectStateFormatter();

            object[] values = formatter.Deserialize(value) as object[];

            if (values != null && values.Length > 0)
                return new UploadSession(values);
            else
                return null;
        }       
Пример #27
0
 public static object StringDeserialize(string objString)
 {
     ObjectStateFormatter osf = new ObjectStateFormatter();
     return osf.Deserialize(objString);
 }
Пример #28
0
        internal static object GetStringDeserialized(string value)
        {
            value = value.Replace(' ', '+');

            // TODO: decrypt

            ObjectStateFormatter formatter = new ObjectStateFormatter();

            if (string.IsNullOrEmpty(value))
                return null;
            else if (value.StartsWith("session-"))
                return UploadSession.Deserialize(value.Substring("session-".Length));
            else if (value.StartsWith("request-"))
                return UploadRequest.Deserialize(value.Substring("request-".Length));
            else if (value.StartsWith("sessionlist-"))
            {
                string[] uploadSessionStrings = (string[])formatter.Deserialize(value.Substring("sessionlist-".Length));

                List<UploadSession> sessions = new List<UploadSession>();

                foreach (string sessionString in uploadSessionStrings)
                    sessions.Add(UploadSession.Deserialize(sessionString));

                return sessions;
            }
            else if (value.StartsWith("requestlist-"))
            {
                string[] uploadRequestStrings = (string[])formatter.Deserialize(value.Substring("requestlist-".Length));

                List<UploadRequest> requests = new List<UploadRequest>();

                foreach (string requestString in uploadRequestStrings)
                    requests.Add(UploadRequest.Deserialize(requestString));

                return requests;
            }
            else
                return formatter.Deserialize(value);
        }
Пример #29
0
			public void writeExternal (java.io.ObjectOutput __p1)
			{
				Page page = CurrentPage;
				ObjectStateFormatter osf = new ObjectStateFormatter (page);
				ObjectOutputStream outputStream = new ObjectOutputStream (__p1);

				if (page.NeedViewStateEncryption || page.EnableViewStateMac)
					outputStream.writeObject (osf.Serialize (_state));
				else
					osf.Serialize (outputStream, _state);
			}
Пример #30
0
 protected override void SavePageStateToPersistenceMedium(object state)
 {
     string value = new ObjectStateFormatter().Serialize(state);
     string viewStateID = (DateTime.Now.Ticks + (long)this.GetHashCode()).ToString(); //产生离散的id号码
     string fn = Path.Combine(Dir.FullName, viewStateID);
     ThreadPool.QueueUserWorkItem((obj) => File.WriteAllText(fn, value)); //或者只写 File.WriteAllText(fn, value)
     Cache.Insert(viewStateID, value);
     base.SavePageStateToPersistenceMedium(viewStateID);
 }
Пример #31
0
			public void readExternal (java.io.ObjectInput __p1)
			{
				Page page = CurrentPage;
				ObjectStateFormatter osf = new ObjectStateFormatter (page);
				ObjectInputStream inputStream = new ObjectInputStream (__p1);

				if (page.NeedViewStateEncryption || page.EnableViewStateMac)
					_state = osf.Deserialize ((string) inputStream.readObject ());
				else
					_state = osf.Deserialize (inputStream);
			}