byte[] Write(IList<SecurityAttribute> secAttrs) { if (secAttrs == null) secAttrs = new SecurityAttribute[0]; var xml = GetNet1xXmlString(secAttrs); if (xml != null) return WriteFormat1(xml); return WriteFormat2(secAttrs); }
public SecurityAttributeVM(SecurityAttribute sa, ModuleDef ownerModule, Language language, TypeDef ownerType, MethodDef ownerMethod) { this.origSa = sa; this.ownerModule = ownerModule; this.caNamedArgumentsVM = new CANamedArgumentsVM(ownerModule, language, ownerType, ownerMethod, a => { // The named args blob length must also be at most 0x1FFFFFFF bytes but we can't verify it here return(a.Collection.Count < ModelUtils.COMPRESSED_UINT32_MAX); }); CANamedArgumentsVM.Collection.CollectionChanged += Args_CollectionChanged; Reinitialize(); }
protected void MarkSecurityAttributeFields(SecurityAttribute sa, TypeDefinition attribute) { if (!sa.HasFields) { return; } foreach (var named_argument in sa.Fields) { MarkCustomAttributeField(named_argument, attribute); } }
protected void MarkSecurityAttributeProperties(SecurityAttribute sa, TypeDefinition attribute) { if (!sa.HasProperties) { return; } foreach (var named_argument in sa.Properties) { MarkCustomAttributeProperty(named_argument, attribute); } }
public void OnActionExecutingWithSecurityTest() { MockRepository mockRepo = new MockRepository(); ActionExecutingContext context = mockRepo.DynamicMock <ActionExecutingContext>(); SecurityAttribute attribute = mockRepo.PartialMock <SecurityAttribute>(); Expect.Call(attribute.HasPermission(context)).Return(true); mockRepo.ReplayAll(); attribute.OnActionExecuting(context); mockRepo.VerifyAll(); Assert.IsFalse(context.Result is RedirectToLoginResult); }
public static SecurityDeclaration Permission2XmlSet(SecurityDeclaration declaration, ModuleDefinition targetModule) { if (!declaration.HasSecurityAttributes || declaration.SecurityAttributes.Count == 0) { // nothing to convert return(declaration); } if (declaration.SecurityAttributes.Count > 1) { throw new Exception("Cannot convert SecurityDeclaration with more than one attribute"); } SecurityAttribute sa = declaration.SecurityAttributes[0]; if (sa.HasFields) { throw new NotSupportedException("Cannot convert SecurityDeclaration with fields"); } TypeReference attrType = sa.AttributeType; AssemblyNameReference attrAsm = (AssemblyNameReference)attrType.Scope; string className = attrType.FullName + ", " + attrAsm.FullName; XmlDocument xmlDoc = new XmlDocument(); XmlElement permissionSet = xmlDoc.CreateElement("PermissionSet"); permissionSet.SetAttribute("class", "System.Security.PermissionSet"); permissionSet.SetAttribute("version", "1"); XmlElement iPermission = xmlDoc.CreateElement("IPermission"); iPermission.SetAttribute("class", className); iPermission.SetAttribute("version", "1"); foreach (var arg in sa.Properties) { iPermission.SetAttribute(arg.Name, arg.Argument.Value.ToString()); } permissionSet.AppendChild(iPermission); xmlDoc.AppendChild(permissionSet); SecurityDeclaration xmlDeclaration = new SecurityDeclaration(declaration.Action); SecurityAttribute attribute = new SecurityAttribute(GetTypeRef("System.Security.Permissions", "PermissionSetAttribute", "mscorlib", targetModule)); attribute.Properties.Add(new CustomAttributeNamedArgument("XML", new CustomAttributeArgument(targetModule.TypeSystem.String, xmlDoc.InnerXml))); xmlDeclaration.SecurityAttributes.Add(attribute); return(xmlDeclaration); }
static IPermission CreatePermission (SecurityDeclaration declaration, SecurityAttribute attribute) { var attribute_type = Type.GetType (attribute.AttributeType.FullName); if (attribute_type == null) throw new ArgumentException (); var security_attribute = CreateSecurityAttribute (attribute_type, declaration); if (security_attribute == null) throw new InvalidOperationException (); CompleteSecurityAttribute (security_attribute, attribute); return security_attribute.CreatePermission (); }
protected virtual void MarkSecurityAttribute(SecurityAttribute sa) { TypeReference security_type = sa.AttributeType; TypeDefinition type = security_type.Resolve(); if (type == null) { throw new ResolutionException(security_type); } MarkType(security_type); MarkSecurityAttributeProperties(sa, type); MarkSecurityAttributeFields(sa, type); }
byte[] Write(IList <SecurityAttribute> secAttrs) { if (secAttrs == null) { secAttrs = new SecurityAttribute[0]; } var xml = DeclSecurity.GetNet1xXmlStringInternal(secAttrs); if (xml != null) { return(WriteFormat1(xml)); } return(WriteFormat2(secAttrs)); }
/// <summary> /// Returns whether the user is authorized based on their claims. /// </summary> /// <param name="identity">User claims identity.</param> /// <returns>true if the user is authorized; otherwise, false.</returns> public bool IsAuthorized(ClaimsIdentity identity) { var security = new SecurityAttribute { AllowAny = AllowAny, AllowInProduction = AllowInProduction, AllowWindowsAuthentication = AllowWindowsAuthentication, Contracts = Contracts, OrganisationCodes = OrganisationCodes, Roles = Roles, Users = Users }; return(security.IsAuthorized(identity)); }
public DeclSecurity CopyTo(ModuleDef module, DeclSecurity ds) { ds.Action = Action; ds.CustomAttributes.Clear(); ds.CustomAttributes.AddRange(CustomAttributes); ds.SecurityAttributes.Clear(); if (V1XMLString == null) { ds.SecurityAttributes.AddRange(SecurityAttributes); } else { ds.SecurityAttributes.Add(SecurityAttribute.CreateFromXml(module, V1XMLString)); } return(ds); }
private void ToXml(ref StringBuilder s, int level) { s.Append("<"); s.Append(tag); if (attributes != null) { s.Append(" "); for (int i = 0; i < attributes.Count; i++) { SecurityAttribute sa = (SecurityAttribute)attributes [i]; s.Append(sa.Name) .Append("=\"") .Append(Escape(sa.Value)) .Append("\""); if (i != attributes.Count - 1) { s.Append(Environment.NewLine); } } } if ((text == null || text == String.Empty) && (children == null || children.Count == 0)) { s.Append("/>").Append(Environment.NewLine); } else { s.Append(">").Append(Escape(text)); if (children != null) { s.Append(Environment.NewLine); foreach (SecurityElement child in children) { child.ToXml(ref s, level + 1); } #if !NET_2_0 s.Append(' ', level * 3); #endif } s.Append("</") .Append(tag) .Append(">") .Append(Environment.NewLine); } }
private void WriteSingleSecurityAttributes(SecurityAttribute attribute) { WriteType(attribute.AttributeType, ILNameSyntax.TypeName); if (attribute.HasProperties) { WriteSpace(); Write("="); WriteLine(); WriteOpenBreckets(); WriteLine(); Indent(); foreach (CustomAttributeNamedArgument property in attribute.Properties) { WriteKeyword("property"); WriteSpace(); WriteType(property.Argument.Type, ILNameSyntax.TypeName); WriteSpace(); WriteLiteral("'"); WriteLiteral(property.Name); WriteLiteral("'"); WriteSpace(); Write("="); WriteSpace(); WriteType(property.Argument.Type, ILNameSyntax.TypeName); WriteSpace(); Write("("); if (property.Argument.Value is bool) { WriteBooleanLiteral((bool)property.Argument.Value); } else if (property.Argument.Value is string) { WriteStringLiteral((string)property.Argument.Value); } else { WriteLiteral(property.Argument.Value.ToString()); } Write(")"); WriteLine(); } Outdent(); WriteEndBreckets(); } }
/// <summary> /// Convert to the security model. /// </summary> /// <param name="source">The source.</param> /// <returns></returns> public static SecurityModel ToSecurityModel(SecurityAttribute source) { SecurityModel dest = new SecurityModel(); if (source == null) { return(null); } dest.AllowAny = source.AllowAny; dest.AllowInProduction = source.AllowInProduction; dest.AllowWindowsAuthentication = source.AllowWindowsAuthentication; dest.Contracts = source.Contracts; dest.OrganisationCodes = source.OrganisationCodes; dest.Roles = source.Roles; dest.Users = source.Users; return(dest); }
void WalkForwardedTypesScope(SecurityAttribute attribute) { if (attribute.HasFields) { foreach (var field in attribute.Fields) { WalkForwardedTypesScope(field.Argument); } } if (attribute.HasProperties) { foreach (var property in attribute.Properties) { WalkForwardedTypesScope(property.Argument); } } }
private void MapSecurityAttribute(SecurityAttribute securityAttribute) { var arguments = securityAttribute.NamedArguments; if (arguments.Count == 0) return; var typeSig = securityAttribute.Type; if (typeSig == null) return; var type = typeSig.Resolve(_module); if (type == null) return; var buildType = type.DeclaringType as BuildType; if (buildType == null) return; MapCustomAttributeArguments(arguments, buildType); }
static IPermission CreatePermission(SecurityDeclaration declaration, SecurityAttribute attribute) { var attribute_type = Type.GetType(attribute.AttributeType.FullName); if (attribute_type == null) { throw new ArgumentException("attribute"); } var security_attribute = CreateSecurityAttribute(attribute_type, declaration); if (security_attribute == null) { throw new InvalidOperationException(); } CompleteSecurityAttribute(security_attribute, attribute); return(security_attribute.CreatePermission()); }
public void OnActionExecutingWithoutSecurityTest() { MockRepository mockRepo = new MockRepository(); ActionExecutingContext context = mockRepo.PartialMock <ActionExecutingContext>(); SecurityAttribute attribute = mockRepo.PartialMock <SecurityAttribute>(); HttpContextBase httpContext = mockRepo.PartialMock <HttpContextBase>(); HttpRequestBase httpRequest = mockRepo.PartialMock <HttpRequestBase>(); Expect.Call(httpRequest.RawUrl).Return("TestUrl").Repeat.Any(); Expect.Call(httpContext.Request).Return(httpRequest).Repeat.Any(); Expect.Call(context.HttpContext).Return(httpContext).Repeat.Any(); Expect.Call(attribute.HasPermission(context)).Return(false); attribute.Expect(x => x.ProccessNoPermissionResult(context)).Do( (Action <ActionExecutingContext>)(filterContext => filterContext.Result = new RedirectToLoginResult())); mockRepo.ReplayAll(); attribute.OnActionExecuting(context); mockRepo.VerifyAll(); Assert.IsTrue(context.Result is RedirectToLoginResult); }
private static ICollection <TypeReference> GetSecurityAttributeUsedTypes(SecurityAttribute attribute) { List <TypeReference> typesDependingOn = new List <TypeReference>(); typesDependingOn.Add(attribute.AttributeType); if (attribute.HasFields || attribute.HasProperties) { var attributeType = attribute.AttributeType.Resolve(); if (attribute.HasProperties) { typesDependingOn.AddRange(GetAttributeNamedArgsUsedTypes(attributeType, attribute.Properties, false)); } if (attribute.HasFields) { typesDependingOn.AddRange(GetAttributeNamedArgsUsedTypes(attributeType, attribute.Fields, true)); } } return(typesDependingOn); }
private void MergeSecurityAttributes() { var secAttrs = this.result.SecurityAttributes; if (secAttrs == null) { return; } for (int i = 0; i < secAttrs.Count; i++) { var attr = secAttrs[i]; Contract.Assume(attr != null); var mutableSecAttr = attr as SecurityAttribute; for (int j = i + 1; j < secAttrs.Count; j++) { var laterAttr = secAttrs[j]; Contract.Assume(laterAttr != null); if (attr.Action == laterAttr.Action) { if (mutableSecAttr == null) { mutableSecAttr = new SecurityAttribute() { Action = attr.Action, Attributes = new List <ICustomAttribute>(attr.Attributes) }; secAttrs[i] = mutableSecAttr; } Contract.Assume(mutableSecAttr.Attributes != null); if (laterAttr.Attributes != null) { mutableSecAttr.Attributes.AddRange(laterAttr.Attributes); } secAttrs.RemoveAt(j); } } if (mutableSecAttr != null) { this.MergeAttributes(mutableSecAttr.Attributes); } } }
public override SecurityAttribute VisitSecurityAttribute(SecurityAttribute attribute) { if (attribute == null) return null; return base.VisitSecurityAttribute((SecurityAttribute)attribute.Clone()); ; }
public static extern uint CreateSemaphore(SecurityAttribute auth, int initialCount, int maximumCount, string name);
static IPermission CreatePermission (SecurityDeclaration declaration, SecurityAttribute attribute) { TypeReference atype = attribute.AttributeType; string name = atype.FullName; // most of the permissions resides inside mscorlib.dll Type attribute_type = Type.GetType (name); if (attribute_type == null) { // but not all of them, so we need to try harder :-) TypeDefinition rtype = atype.Resolve (); AssemblyDefinition ad = rtype == null ? atype.Module.Assembly : rtype.Module.Assembly; attribute_type = Type.GetType (name + ", " + ad.FullName); } if (attribute_type == null) throw new ArgumentException ("attribute"); var security_attribute = CreateSecurityAttribute (attribute_type, declaration); if (security_attribute == null) throw new InvalidOperationException (); CompleteSecurityAttribute (security_attribute, attribute); return security_attribute.CreatePermission (); }
private SecurityAttribute GetSecurityAttribute(int i) { DeclSecurityRow dsr = this.tables.DeclSecurityTable[i]; SecurityAttribute attr = new SecurityAttribute(); attr.Action = (System.Security.Permissions.SecurityAction)dsr.Action; if (this.module.MetadataFormatMajorVersion > 1 || this.module.MetadataFormatMinorVersion > 0) { attr.PermissionAttributes = this.GetPermissionAttributes(dsr.PermissionSet, attr.Action); if (attr.PermissionAttributes != null) return attr; } attr.SerializedPermissions = (string)this.tables.GetBlobString(dsr.PermissionSet); return attr; }
void InitializeFrom(SecurityAttribute sa) { AttributeType = sa.AttributeType; CANamedArgumentsVM.InitializeFrom(sa.NamedArguments); }
static void CompleteSecurityAttributeFields(SSP.SecurityAttribute security_attribute, SecurityAttribute attribute) { var type = security_attribute.GetType(); foreach (var named_argument in attribute.Fields) { type.GetField(named_argument.Name).SetValue(security_attribute, named_argument.Argument.Value); } }
public virtual Differences VisitSecurityAttribute(SecurityAttribute attribute1, SecurityAttribute attribute2){ Differences differences = new Differences(attribute1, attribute2); if (attribute1 == null || attribute2 == null){ if (attribute1 != attribute2) differences.NumberOfDifferences++; else differences.NumberOfSimilarities++; return differences; } SecurityAttribute changes = (SecurityAttribute)attribute2.Clone(); SecurityAttribute deletions = (SecurityAttribute)attribute2.Clone(); SecurityAttribute insertions = (SecurityAttribute)attribute2.Clone(); if (attribute1.Action == attribute2.Action) differences.NumberOfSimilarities++; else differences.NumberOfDifferences++; AttributeList attrChanges, attrDeletions, attrInsertions; Differences diff = this.VisitAttributeList(attribute1.PermissionAttributes, attribute2.PermissionAttributes, out attrChanges, out attrDeletions, out attrInsertions); if (diff == null){Debug.Assert(false); return differences;} changes.PermissionAttributes = attrChanges; deletions.PermissionAttributes = attrDeletions; insertions.PermissionAttributes = attrInsertions; differences.NumberOfDifferences += diff.NumberOfDifferences; differences.NumberOfSimilarities += diff.NumberOfSimilarities; if (attribute1.PermissionAttributes == null && attribute2.PermissionAttributes == null && attribute1.SerializedPermissions == attribute2.SerializedPermissions) differences.NumberOfSimilarities++; else differences.NumberOfDifferences++; if (differences.NumberOfDifferences == 0){ differences.Changes = null; differences.Deletions = null; differences.Insertions = null; }else{ differences.Changes = changes; differences.Deletions = deletions; differences.Insertions = insertions; } return differences; }
internal SecurityAttributeDecoder20(PEFileToObjectModel peFileToObjectModel, MemoryReader signatureMemoryReader, SecurityAttribute securityAttribute) : base(peFileToObjectModel, signatureMemoryReader) { this.SecurityAttributes = Enumerable<ICustomAttribute>.Empty; byte prolog = this.SignatureMemoryReader.ReadByte(); if (prolog != SerializationType.SecurityAttribute20Start) return; int numberOfAttributes = this.SignatureMemoryReader.ReadCompressedUInt32(); var securityCustomAttributes = new ICustomAttribute[numberOfAttributes]; for (int i = 0; i < numberOfAttributes; ++i) { var secAttr = this.ReadSecurityAttribute(securityAttribute); if (secAttr == null) { // MDError... return; } securityCustomAttributes[i] = secAttr; } this.SecurityAttributes = IteratorHelper.GetReadonly(securityCustomAttributes); }
private bool WriteSecurityAttribute(ModuleDefinition module, bool isAssemblyDeclaration, SecurityAttribute attribute, SecurityDeclaration securityDeclaration, out bool wroteArgument) { genericWriter.WriteToken(OpeningBracket); if (isAssemblyDeclaration) { genericWriter.WriteKeyword(genericWriter.KeyWordWriter.Assembly); genericWriter.Write(":"); genericWriter.WriteSpace(); } string attributeName = attribute.AttributeType.Name.EndsWith("Attribute") ? attribute.AttributeType.Name.Remove(attribute.AttributeType.Name.LastIndexOf("Attribute")) : attribute.AttributeType.Name; genericWriter.WriteNamespaceIfTypeInCollision(attribute.AttributeType); genericWriter.WriteReference(attributeName, attribute.AttributeType); genericWriter.WriteToken("("); TypeReference securityActionTypeReference = securityDeclaration.GetSecurityActionTypeReference(module); TypeDefinition argumentTypeDefinition = securityActionTypeReference.IsDefinition ? securityActionTypeReference as TypeDefinition : securityActionTypeReference.Resolve(); if (argumentTypeDefinition != null && argumentTypeDefinition.IsEnum) { List <FieldDefinition> fields = EnumValueToFieldCombinationMatcher.GetEnumFieldDefinitionByValue(argumentTypeDefinition.Fields, (int)securityDeclaration.Action, argumentTypeDefinition.CustomAttributes); if (fields.Count != 0) { for (int i = 0; i < fields.Count; i++) { genericWriter.WriteReferenceAndNamespaceIfInCollision(fields[i].DeclaringType); genericWriter.WriteToken("."); genericWriter.WriteEnumValueField(fields[i]); if (i + 1 < fields.Count) { genericWriter.WriteSpace(); genericWriter.WriteBitwiseOr(); genericWriter.WriteSpace(); } } } else { WriteSecurityAttributeAction(securityDeclaration.Action); } } wroteArgument = true; if (attribute.HasFields || attribute.HasProperties) { var attributeType = attribute.AttributeType.Resolve(); if (attribute.HasProperties) { wroteArgument = WriteAttributeNamedArgs(attributeType, attribute.Properties, false, wroteArgument); } if (attribute.HasFields) { WriteAttributeNamedArgs(attributeType, attribute.Fields, true, wroteArgument); } } genericWriter.WriteToken(")"); genericWriter.WriteToken(ClosingBracket); genericWriter.WriteLine(); return(wroteArgument); }
public virtual SecurityAttribute VisitSecurityAttribute(SecurityAttribute attribute){ return attribute; }
public virtual void VisitSecurityAttribute(SecurityAttribute attribute) { }
static extern bool CreateDirectory(string name, SecurityAttribute sa);
private void WriteSingleSecurityAttributes(SecurityAttribute attribute) { this.WriteType(attribute.get_AttributeType(), 2); if (attribute.get_HasProperties()) { this.WriteSpace(); this.Write("="); this.WriteLine(); this.WriteOpenBreckets(); this.WriteLine(); this.Indent(); V_0 = attribute.get_Properties().GetEnumerator(); try { while (V_0.MoveNext()) { V_1 = V_0.get_Current(); this.WriteKeyword("property"); this.WriteSpace(); V_2 = V_1.get_Argument(); this.WriteType(V_2.get_Type(), 2); this.WriteSpace(); this.WriteLiteral("'"); this.WriteLiteral(V_1.get_Name()); this.WriteLiteral("'"); this.WriteSpace(); this.Write("="); this.WriteSpace(); V_2 = V_1.get_Argument(); this.WriteType(V_2.get_Type(), 2); this.WriteSpace(); this.Write("("); if (V_1.get_Argument().get_Value() as Boolean == false) { if (V_1.get_Argument().get_Value() as String == null) { V_2 = V_1.get_Argument(); this.WriteLiteral(V_2.get_Value().ToString()); } else { V_2 = V_1.get_Argument(); this.WriteStringLiteral((String)V_2.get_Value()); } } else { V_2 = V_1.get_Argument(); this.WriteBooleanLiteral((Boolean)V_2.get_Value()); } this.Write(")"); this.WriteLine(); } } finally { V_0.Dispose(); } this.Outdent(); this.WriteEndBreckets(); } return; }
public static int CompareToSecurityAttribute(this SecurityAttribute first, SecurityAttribute second, SecurityDeclaration firstDeclaration, SecurityDeclaration secondDeclaration) { if (first == second) { return(0); } string firstActionAsString = firstDeclaration.Action.ToString(); string secondActionAsString = secondDeclaration.Action.ToString(); if (firstActionAsString != secondActionAsString) { return(firstActionAsString.CompareTo(secondActionAsString)); } #region Compare Properties int maxProperties = Math.Max(first.Properties.Count, second.Properties.Count); for (int i = 0; i < maxProperties; i++) { if (i >= first.Properties.Count) { return(1); } if (i >= second.Properties.Count) { return(-1); } CustomAttributeNamedArgument firstProperty = first.Properties[i]; CustomAttributeNamedArgument secondProperty = second.Properties[i]; if (firstProperty.Name == secondProperty.Name) { string firstValue = firstProperty.Argument.Value.ToString(); string secondValue = secondProperty.Argument.Value.ToString(); if (firstValue != secondValue) { return(firstValue.CompareTo(secondValue)); } } else { return(firstProperty.Name.CompareTo(secondProperty.Name)); } } #endregion #region Compare Fiels int maxFields = Math.Max(first.Fields.Count, second.Fields.Count); for (int i = 0; i < maxFields; i++) { if (i >= first.Fields.Count) { return(1); } if (i >= second.Fields.Count) { return(-1); } CustomAttributeNamedArgument firstField = first.Fields[i]; CustomAttributeNamedArgument secondField = second.Fields[i]; if (firstField.Name == secondField.Name) { string firstValue = firstField.Argument.Value.ToString(); string secondValue = secondField.Argument.Value.ToString(); if (firstValue != secondValue) { return(firstValue.CompareTo(secondValue)); } } else { return(firstField.Name.CompareTo(secondField.Name)); } } #endregion return(0); }
static void CompleteSecurityAttribute (SSP.SecurityAttribute security_attribute, SecurityAttribute attribute) { if (attribute.HasFields) CompleteSecurityAttributeFields (security_attribute, attribute); if (attribute.HasProperties) CompleteSecurityAttributeProperties (security_attribute, attribute); }
public override void Visit(SecurityAttribute securityAttribute) { this.Visit(securityAttribute.Attribute); }
public virtual SecurityAttribute VisitSecurityAttribute(SecurityAttribute attribute1, SecurityAttribute attribute2) { return attribute1; }
public virtual SecurityAttribute GetClosestMatch(SecurityAttribute/*!*/ nd1, SecurityAttributeList/*!*/ list1, SecurityAttributeList list2, int list1pos, ref int list2start, TrivialHashtable/*!*/ matchedNodes, out Differences closestDifferences, out int list2pos) { closestDifferences = null; list2pos = -1; if (list2 == null) return null; if (nd1 == null || list1 == null || matchedNodes == null || list1pos < 0 || list1pos >= list1.Count || list2start < 0 || list2start >= list2.Count) { Debug.Assert(false); return null; } SecurityAttribute closest = null; Differences winnerSoFar = null; for (int j = list2start, m = list2.Count; j < m; j++){ SecurityAttribute nd2 = list2[j]; if (list2start == j) list2start++; if (nd2 == null) continue; if (matchedNodes[nd2.UniqueKey] != null) continue; Differences diff = this.GetDifferences(nd1, nd2); if (diff == null){Debug.Assert(false); continue;} if (diff.Similarity <= 0.5){ //Not a good enough match if (list2start == j+1) list2start--; //The next call to GetClosestMatch will start looking at list2start, so this node will be considered then continue; //ignore it for the rest of this call } if (winnerSoFar != null && winnerSoFar.Similarity >= diff.Similarity) continue; winnerSoFar = closestDifferences = diff; closest = nd2; list2pos = j; if (diff.NumberOfDifferences == 0) return closest; //Perfect match, no need to look for other matches } if (closest != null){ //^ assert winnerSoFar != null; //closest is closer to nd1 than any other node in list2, but this is no good if some other node in list1 has a better claim on closest for (int i = list1pos+1, n = list1.Count; i < n; i++){ SecurityAttribute nd1alt = list1[i]; if (nd1alt == null) continue; if (matchedNodes[nd1alt.UniqueKey] != null) continue; Differences diff = this.GetDifferences(nd1alt, closest); if (diff == null){Debug.Assert(false); continue;} if (diff.Similarity <= winnerSoFar.Similarity) continue; //nd1alt has a better claim on closest. See if it wants closest. Differences diff2; int j, k = list2start; SecurityAttribute nd2alt = this.GetClosestMatch(nd1alt, list1, list2, i, ref k, matchedNodes, out diff2, out j); if (nd2alt != closest){ Debug.Assert(nd2alt != null && diff2 != null && diff2.Similarity >= diff.Similarity); continue; //nd1alt prefers nd2alt to closest, so closest is still available } //nd1alt wants closest, take it out of the running matchedNodes[closest.UniqueKey] = nd1alt; //Now that closest is out of the running, try again k = list2start; SecurityAttribute newClosest = this.GetClosestMatch(nd1, list1, list2, i, ref k, matchedNodes, out winnerSoFar, out list2pos); //put closest back in the running so that the next call to this routine will pick it up matchedNodes[closest.UniqueKey] = closest; closest = newClosest; break; } } closestDifferences = winnerSoFar; return closest; }
// TODO: add support for arrays and enums (2.0) internal static IPermission ProcessAttribute(byte[] data, ref int position) { int clen = ReadEncodedInt(data, ref position); string cnam = Encoding.UTF8.GetString(data, position, clen); position += clen; Type secattr = Type.GetType(cnam); SecurityAttribute sa = (Activator.CreateInstance(secattr, action) as SecurityAttribute); if (sa == null) { return(null); } /*int optionalParametersLength =*/ ReadEncodedInt(data, ref position); int numberOfParameters = ReadEncodedInt(data, ref position); for (int j = 0; j < numberOfParameters; j++) { bool property = false; switch (data [position++]) { case 0x53: // field (technically possible and working) property = false; break; case 0x54: // property (common case) property = true; break; default: return(null); } bool array = false; byte type = data [position++]; if (type == 0x1D) { array = true; type = data [position++]; } int plen = ReadEncodedInt(data, ref position); string pnam = Encoding.UTF8.GetString(data, position, plen); position += plen; int arrayLength = 1; if (array) { arrayLength = BitConverter.ToInt32(data, position); position += 4; } object obj = null; object[] arrayIndex = null; for (int i = 0; i < arrayLength; i++) { if (array) { // TODO - setup index (2.0) } // sadly type values doesn't match ther TypeCode enum :( switch (type) { case 0x02: // MONO_TYPE_BOOLEAN obj = (object)Convert.ToBoolean(data [position++]); break; case 0x03: // MONO_TYPE_CHAR obj = (object)Convert.ToChar(data [position]); position += 2; break; case 0x04: // MONO_TYPE_I1 obj = (object)Convert.ToSByte(data [position++]); break; case 0x05: // MONO_TYPE_U1 obj = (object)Convert.ToByte(data [position++]); break; case 0x06: // MONO_TYPE_I2 obj = (object)Convert.ToInt16(data [position]); position += 2; break; case 0x07: // MONO_TYPE_U2 obj = (object)Convert.ToUInt16(data [position]); position += 2; break; case 0x08: // MONO_TYPE_I4 obj = (object)Convert.ToInt32(data [position]); position += 4; break; case 0x09: // MONO_TYPE_U4 obj = (object)Convert.ToUInt32(data [position]); position += 4; break; case 0x0A: // MONO_TYPE_I8 obj = (object)Convert.ToInt64(data [position]); position += 8; break; case 0x0B: // MONO_TYPE_U8 obj = (object)Convert.ToUInt64(data [position]); position += 8; break; case 0x0C: // MONO_TYPE_R4 obj = (object)Convert.ToSingle(data [position]); position += 4; break; case 0x0D: // MONO_TYPE_R8 obj = (object)Convert.ToDouble(data [position]); position += 8; break; case 0x0E: // MONO_TYPE_STRING string s = null; if (data [position] != 0xFF) { int slen = ReadEncodedInt(data, ref position); s = Encoding.UTF8.GetString(data, position, slen); position += slen; } else { position++; } obj = (object)s; break; case 0x50: // special for TYPE int tlen = ReadEncodedInt(data, ref position); obj = (object)Type.GetType(Encoding.UTF8.GetString(data, position, tlen)); position += tlen; break; default: return(null); // unsupported } if (property) { PropertyInfo pi = secattr.GetProperty(pnam); pi.SetValue(sa, obj, arrayIndex); } else { FieldInfo fi = secattr.GetField(pnam); fi.SetValue(sa, obj); } } } return(sa.CreatePermission()); }
public static SecurityDeclaration Xml2PermissionSet(SecurityDeclaration xmlDeclaration, ModuleDefinition targetModule) { if (!xmlDeclaration.HasSecurityAttributes || xmlDeclaration.SecurityAttributes.Count == 0) { // nothing to convert return(xmlDeclaration); } if (xmlDeclaration.SecurityAttributes.Count > 1) { throw new Exception("Cannot convert SecurityDeclaration with more than one attribute"); } SecurityAttribute sa = xmlDeclaration.SecurityAttributes[0]; if (sa.HasFields) { throw new NotSupportedException("Cannot convert SecurityDeclaration with fields"); } if (!sa.HasProperties || sa.Properties.Count > 1) { throw new NotSupportedException("Invalid XML SecurityDeclaration (only 1 property supported)"); } CustomAttributeNamedArgument arg = sa.Properties[0]; if (arg.Name != "XML" || arg.Argument.Type.FullName != "System.String") { throw new ArgumentException("Property \"XML\" expected"); } XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(arg.Argument.Value as string); XmlNode permissionSet = xmlDoc.SelectSingleNode("/PermissionSet"); if (permissionSet == null) { return(null); } XmlNode permissionSetClass = permissionSet.SelectSingleNode("@class"); // check version? if (permissionSetClass == null) { return(null); } if (permissionSetClass.Value != "System.Security.PermissionSet") { return(null); } XmlNode iPermission = permissionSet.SelectSingleNode("IPermission"); if (iPermission == null) { return(null); } XmlNode iPermissionClass = iPermission.SelectSingleNode("@class"); // check version? if (iPermissionClass == null) { return(null); } // Create Namespace & Name from FullName, AssemblyName can be ignored since we look it up. string[] valueParts = iPermissionClass.Value.Split(','); Collection <string> classNamespace = new Collection <string>(valueParts[0].Split('.')); string assemblyName = valueParts[1].Trim(); string className = classNamespace[classNamespace.Count - 1]; classNamespace.RemoveAt(classNamespace.Count - 1); SecurityAttribute attribute = new SecurityAttribute(GetTypeRef(string.Join(".", classNamespace.ToArray()), className, assemblyName, targetModule)); foreach (XmlAttribute xmlAttr in iPermission.Attributes) { if ((xmlAttr.Name != "class") && (xmlAttr.Name != "version")) { attribute.Properties.Add(new CustomAttributeNamedArgument(xmlAttr.Name, new CustomAttributeArgument(targetModule.TypeSystem.String, xmlAttr.Value))); } } SecurityDeclaration newSd = new SecurityDeclaration(xmlDeclaration.Action); newSd.SecurityAttributes.Add(attribute); return(newSd); }
//^ [NotDelayed] internal SecurityAttributeDecoder20( PEFileToObjectModel peFileToObjectModel, MemoryReader signatureMemoryReader, SecurityAttribute securityAttribute ) : base(peFileToObjectModel, signatureMemoryReader) { //^ this.SignatureMemoryReader = signatureMemoryReader; //TODO: Spec# bug. This assignment should not be necessary. this.SecurityAttributes = TypeCache.EmptySecurityAttributes; //^ base; byte prolog = this.SignatureMemoryReader.ReadByte(); if (prolog != SerializationType.SecurityAttribute20Start) { return; } int numberOfAttributes = this.SignatureMemoryReader.ReadCompressedUInt32(); SecurityCustomAttribute[] securityCustomAttributes = new SecurityCustomAttribute[numberOfAttributes]; for (int i = 0; i < numberOfAttributes; ++i) { SecurityCustomAttribute/*?*/ secAttr = this.ReadSecurityAttribute(securityAttribute); if (secAttr == null) { // MDError... return; } securityCustomAttributes[i] = secAttr; } //^ NonNullType.AssertInitialized(securityCustomAttributes); this.SecurityAttributes = new EnumerableArrayWrapper<SecurityCustomAttribute, ICustomAttribute>(securityCustomAttributes, Dummy.CustomAttribute); }
public void ExtractSecurityAttributes(AttributeList attributes, ref SecurityAttributeList securityAttributes){ if (attributes == null){Debug.Assert(false); return;} TrivialHashtable attributeListFor = null; for (int i = 0, n = attributes.Count; i < n; i++){ AttributeNode attr = attributes[i]; if (attr == null) continue; if (attr.Type == null) continue; if (!this.GetTypeView(attr.Type).IsAssignableTo(SystemTypes.SecurityAttribute)) continue; attributes[i] = null; ExpressionList args = attr.Expressions; if (args == null || args.Count < 1) return; Literal lit = args[0] as Literal; if (lit == null || !(lit.Value is int)) return; int action = (int)lit.Value; if (attributeListFor == null) attributeListFor = new TrivialHashtable(); AttributeList attrsForAction = (AttributeList)attributeListFor[action+1]; if (attrsForAction == null){ attributeListFor[action+1] = attrsForAction = new AttributeList(); SecurityAttribute secAttr = new SecurityAttribute(); secAttr.Action = (System.Security.Permissions.SecurityAction)action; secAttr.PermissionAttributes = attrsForAction; if (securityAttributes == null) securityAttributes = new SecurityAttributeList(); securityAttributes.Add(secAttr); } attrsForAction.Add(attr); } }
/*?*/ SecurityCustomAttribute ReadSecurityAttribute(SecurityAttribute securityAttribute) { string/*?*/ typeNameStr = this.GetSerializedString(); if (typeNameStr == null) return null; IModuleTypeReference/*?*/ moduleTypeReference = this.PEFileToObjectModel.GetSerializedTypeNameAsTypeReference(typeNameStr); if (moduleTypeReference == null) return null; IMethodReference ctorReference = Dummy.MethodReference; ITypeDefinition attributeType = moduleTypeReference.ResolvedType; if (attributeType != Dummy.Type) { foreach (ITypeDefinitionMember member in attributeType.GetMembersNamed(this.PEFileToObjectModel.NameTable.Ctor, false)) { IMethodDefinition/*?*/ method = member as IMethodDefinition; if (method == null) continue; if (!IteratorHelper.EnumerableHasLength(method.Parameters, 1)) continue; //TODO: check that parameter has the right type ctorReference = method; break; } } else { int ctorKey = this.PEFileToObjectModel.NameTable.Ctor.UniqueKey; foreach (ITypeMemberReference mref in this.PEFileToObjectModel.GetMemberReferences()) { IMethodReference/*?*/ methRef = mref as IMethodReference; if (methRef == null) continue; if (methRef.ContainingType.InternedKey != moduleTypeReference.InternedKey) continue; if (methRef.Name.UniqueKey != ctorKey) continue; if (!IteratorHelper.EnumerableHasLength(methRef.Parameters, 1)) continue; //TODO: check that parameter has the right type ctorReference = methRef; break; } } if (ctorReference == Dummy.MethodReference) { ctorReference = new MethodReference(this.PEFileToObjectModel.ModuleReader.metadataReaderHost, moduleTypeReference, CallingConvention.Default|CallingConvention.HasThis, this.PEFileToObjectModel.PlatformType.SystemVoid, this.PEFileToObjectModel.NameTable.Ctor, 0, this.PEFileToObjectModel.PlatformType.SystemSecurityPermissionsSecurityAction); } this.SignatureMemoryReader.ReadCompressedUInt32(); // BlobSize... int numOfNamedArgs = this.SignatureMemoryReader.ReadCompressedUInt32(); FieldOrPropertyNamedArgumentExpression[]/*?*/ namedArgumentArray = null; if (numOfNamedArgs > 0) { namedArgumentArray = new FieldOrPropertyNamedArgumentExpression[numOfNamedArgs]; for (int i = 0; i < numOfNamedArgs; ++i) { bool isField = this.SignatureMemoryReader.ReadByte() == SerializationType.Field; IModuleTypeReference/*?*/ memberType = this.GetFieldOrPropType(); if (memberType == null) return null; string/*?*/ memberStr = this.GetSerializedString(); if (memberStr == null) return null; IName memberName = this.PEFileToObjectModel.NameTable.GetNameFor(memberStr); ExpressionBase/*?*/ value = this.ReadSerializedValue(memberType); if (value == null) return null; namedArgumentArray[i] = new FieldOrPropertyNamedArgumentExpression(memberName, moduleTypeReference, isField, memberType, value); } } EnumerableArrayWrapper<FieldOrPropertyNamedArgumentExpression, IMetadataNamedArgument> namedArguments = TypeCache.EmptyNamedArgumentList; if (namedArgumentArray != null) namedArguments = new EnumerableArrayWrapper<FieldOrPropertyNamedArgumentExpression, IMetadataNamedArgument>(namedArgumentArray, Dummy.NamedArgument); return new SecurityCustomAttribute(securityAttribute, ctorReference, TypeCache.EmptyExpressionList, namedArguments); }
static void CompleteSecurityAttribute(SSP.SecurityAttribute security_attribute, SecurityAttribute attribute) { if (attribute.HasFields) { CompleteSecurityAttributeFields(security_attribute, attribute); } if (attribute.HasProperties) { CompleteSecurityAttributeProperties(security_attribute, attribute); } }
static void CompleteSecurityAttributeFields (SSP.SecurityAttribute security_attribute, SecurityAttribute attribute) { var type = security_attribute.GetType (); foreach (var named_argument in attribute.Fields) type.GetField (named_argument.Name).SetValue (security_attribute, named_argument.Argument.Value); }
static void CompleteSecurityAttributeProperties(SSP.SecurityAttribute security_attribute, SecurityAttribute attribute) { var type = security_attribute.GetType(); foreach (var named_argument in attribute.Properties) { type.GetProperty(named_argument.Name).SetValue(security_attribute, named_argument.Argument.Value, null); } }
public virtual void Visit(SecurityAttribute securityAttribute) { this.Visit(securityAttribute.Attribute); }
public virtual SecurityAttribute VisitSecurityAttribute(SecurityAttribute attribute, SecurityAttribute changes, SecurityAttribute deletions, SecurityAttribute insertions){ this.UpdateSourceContext(attribute, changes); if (attribute == null) return changes; if (changes != null){ if (deletions == null || insertions == null) Debug.Assert(false); else{ } }else if (deletions != null) return null; return attribute; }
static void CompleteSecurityAttributeProperties (SSP.SecurityAttribute security_attribute, SecurityAttribute attribute) { var type = security_attribute.GetType (); foreach (var named_argument in attribute.Properties) type.GetProperty (named_argument.Name).SetValue (security_attribute, named_argument.Argument.Value, null); }
public static int CompareToSecurityAttribute(this SecurityAttribute first, SecurityAttribute second, SecurityDeclaration firstDeclaration, SecurityDeclaration secondDeclaration) { if (first == second) { return 0; } string firstActionAsString = firstDeclaration.Action.ToString(); string secondActionAsString = secondDeclaration.Action.ToString(); if (firstActionAsString != secondActionAsString) { return firstActionAsString.CompareTo(secondActionAsString); } #region Compare Properties int maxProperties = Math.Max(first.Properties.Count, second.Properties.Count); for (int i = 0; i < maxProperties; i++) { if (i >= first.Properties.Count) { return 1; } if (i >= second.Properties.Count) { return -1; } CustomAttributeNamedArgument firstProperty = first.Properties[i]; CustomAttributeNamedArgument secondProperty = second.Properties[i]; if (firstProperty.Name == secondProperty.Name) { string firstValue = firstProperty.Argument.Value.ToString(); string secondValue = secondProperty.Argument.Value.ToString(); if (firstValue != secondValue) { return firstValue.CompareTo(secondValue); } } else { return firstProperty.Name.CompareTo(secondProperty.Name); } } #endregion #region Compare Fiels int maxFields = Math.Max(first.Fields.Count, second.Fields.Count); for (int i = 0; i < maxFields; i++) { if (i >= first.Fields.Count) { return 1; } if (i >= second.Fields.Count) { return -1; } CustomAttributeNamedArgument firstField = first.Fields[i]; CustomAttributeNamedArgument secondField = second.Fields[i]; if (firstField.Name == secondField.Name) { string firstValue = firstField.Argument.Value.ToString(); string secondValue = secondField.Argument.Value.ToString(); if (firstValue != secondValue) { return firstValue.CompareTo(secondValue); } } else { return firstField.Name.CompareTo(secondField.Name); } } #endregion return 0; }
public bool Equal(SecurityElement other) { if (other == null) { return(false); } if (this == other) { return(true); } if (this.text != other.text) { return(false); } if (this.tag != other.tag) { return(false); } if (this.attributes == null && other.attributes != null && other.attributes.Count != 0) { return(false); } if (other.attributes == null && this.attributes != null && this.attributes.Count != 0) { return(false); } if (this.attributes != null && other.attributes != null) { if (this.attributes.Count != other.attributes.Count) { return(false); } foreach (SecurityAttribute sa1 in attributes) { SecurityAttribute sa2 = other.GetAttribute(sa1.Name); if ((sa2 == null) || (sa1.Value != sa2.Value)) { return(false); } } } if (this.children == null && other.children != null && other.children.Count != 0) { return(false); } if (other.children == null && this.children != null && this.children.Count != 0) { return(false); } if (this.children != null && other.children != null) { if (this.children.Count != other.children.Count) { return(false); } for (int i = 0; i < this.children.Count; i++) { if (!((SecurityElement)this.children [i]).Equal((SecurityElement)other.children [i])) { return(false); } } } return(true); }