1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
|
//
// System.Security.PermissionSet.cs
//
// Authors:
// Nick Drochak(ndrochak@gol.com)
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) Nick Drochak
// Portions (C) 2003, 2004 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Permissions;
using System.Security.Policy;
using System.Text;
using System.Threading;
namespace System.Security {
[Serializable]
// Microsoft public key - i.e. only MS signed assembly can inherit from PermissionSet (1.x) or (2.0) FullTrust assemblies
[StrongNameIdentityPermission (SecurityAction.InheritanceDemand, PublicKey="002400000480000094000000060200000024000052534131000400000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8A12436518206DC093344D5AD293")]
#if NET_2_0
[ComVisible (true)]
#endif
public class PermissionSet: ISecurityEncodable, ICollection, IEnumerable, IStackWalk, IDeserializationCallback {
private const string tagName = "PermissionSet";
private const int version = 1;
private static object[] psUnrestricted = new object [1] { PermissionState.Unrestricted };
private PermissionState state;
private ArrayList list;
private int _hashcode;
private PolicyLevel _policyLevel;
private bool _declsec;
private bool _readOnly;
private bool[] _ignored; // for asserts and non-CAS permissions
// constructors
// for PolicyLevel (to avoid validation duplication)
internal PermissionSet ()
{
list = new ArrayList ();
}
public PermissionSet (PermissionState state) : this ()
{
this.state = CodeAccessPermission.CheckPermissionState (state, true);
}
public PermissionSet (PermissionSet permSet) : this ()
{
// LAMESPEC: This would be handled by the compiler. No way permSet is not a PermissionSet.
//if (!(permSet is PermissionSet))
// throw new System.ArgumentException(); // permSet is not an instance of System.Security.PermissionSet.
if (permSet != null) {
state = permSet.state;
foreach (IPermission p in permSet.list)
list.Add (p);
}
#if !NET_2_0
else {
state = PermissionState.Unrestricted;
}
#endif
}
internal PermissionSet (string xml)
: this ()
{
state = PermissionState.None;
if (xml != null) {
SecurityElement se = SecurityElement.FromString (xml);
FromXml (se);
}
}
// Light version for creating a (non unrestricted) PermissionSet with
// a single permission. This allows to relax most validations.
internal PermissionSet (IPermission perm)
: this ()
{
if (perm != null) {
// note: we do not copy IPermission like AddPermission
list.Add (perm);
}
}
// methods
#if NET_2_0
public IPermission AddPermission (IPermission perm)
#else
public virtual IPermission AddPermission (IPermission perm)
#endif
{
if ((perm == null) || _readOnly)
return perm;
// we don't add to an unrestricted permission set unless...
if (state == PermissionState.Unrestricted) {
#if NET_2_0
// identity permissions can be unrestricted under 2.x
{
#else
// we're adding identity permission as they don't support unrestricted
if (perm is IUnrestrictedPermission) {
#endif
// we return the union of the permission with unrestricted
// which results in a permission of the same type initialized
// with PermissionState.Unrestricted
return (IPermission) Activator.CreateInstance (perm.GetType (), psUnrestricted);
}
}
// we can't add two permissions of the same type in a set
// so we remove an existing one, union with it and add it back
IPermission existing = RemovePermission (perm.GetType ());
if (existing != null) {
perm = perm.Union (existing);
}
// note: Add doesn't copy
list.Add (perm);
return perm;
}
[MonoTODO ("Imperative mode isn't supported")]
[SecurityPermission (SecurityAction.Demand, Assertion = true)]
#if NET_2_0
public void Assert ()
#else
public virtual void Assert ()
#endif
{
int count = this.Count;
// we (current frame) must have the permission to assert it to others
// otherwise we don't assert (but we don't throw an exception)
foreach (IPermission p in list) {
// note: we ignore non-CAS permissions
if (p is IStackWalk) {
if (!SecurityManager.IsGranted (p)) {
return;
}
} else
count--;
}
// note: we must ignore the stack modifiers for the non-CAS permissions
if (SecurityManager.SecurityEnabled && (count > 0))
throw new NotSupportedException ("Currently only declarative Assert are supported.");
}
internal void Clear ()
{
list.Clear ();
}
public virtual PermissionSet Copy ()
{
return new PermissionSet (this);
}
public virtual void CopyTo (Array array, int index)
{
if (null == array)
throw new ArgumentNullException ("array");
if (list.Count > 0) {
if (array.Rank > 1) {
throw new ArgumentException (Locale.GetText (
"Array has more than one dimension"));
}
if (index < 0 || index >= array.Length) {
throw new IndexOutOfRangeException ("index");
}
list.CopyTo (array, index);
}
}
#if NET_2_0
public void Demand ()
#else
public virtual void Demand ()
#endif
{
// Note: SecurityEnabled only applies to CAS permissions
// so we're not checking for it (yet)
if (IsEmpty ())
return;
int n = list.Count;
if ((_ignored == null) || (_ignored.Length != n)) {
_ignored = new bool [n];
}
bool call_cas_only = this.IsUnrestricted ();
// non CAS permissions (e.g. PrincipalPermission) do not requires a stack walk
for (int i = 0; i < n; i++) {
IPermission p = (IPermission) list [i];
Type t = p.GetType ();
if (t.IsSubclassOf (typeof (CodeAccessPermission))) {
_ignored [i] = false;
call_cas_only = true;
} else {
_ignored [i] = true;
p.Demand ();
}
}
// don't start the stack walk if
// - the permission set only contains non CAS permissions; or
// - security isn't enabled (applis only to CAS!)
if (call_cas_only && SecurityManager.SecurityEnabled)
CasOnlyDemand (_declsec ? 5 : 3);
}
// The number of frames to skip depends on who's calling
// - CodeAccessPermission.Demand (imperative)
// - PermissionSet.Demand (imperative)
// - SecurityManager.InternalDemand (declarative)
internal void CasOnlyDemand (int skip)
{
Assembly current = null;
AppDomain domain = null;
if (_ignored == null) {
// special case when directly called from CodeAccessPermission.Demand
_ignored = new bool [list.Count];
}
ArrayList frames = SecurityFrame.GetStack (skip);
if ((frames != null) && (frames.Count > 0)) {
SecurityFrame first = ((SecurityFrame) frames [0]);
current = first.Assembly;
domain = first.Domain;
// skip ourself, Demand and other security runtime methods
foreach (SecurityFrame sf in frames) {
if (ProcessFrame (sf, ref current, ref domain)) {
if (AllIgnored ())
return; // reached Assert
}
}
SecurityFrame last = ((SecurityFrame) frames [frames.Count - 1]);
CheckAssembly (current, last);
CheckAppDomain (domain, last);
}
// Is there a CompressedStack to handle ?
CompressedStack stack = Thread.CurrentThread.GetCompressedStack ();
if ((stack != null) && !stack.IsEmpty ()) {
foreach (SecurityFrame frame in stack.List) {
if (ProcessFrame (frame, ref current, ref domain)) {
if (AllIgnored ())
return; // reached Assert
}
}
}
}
[MonoTODO ("Imperative mode isn't supported")]
#if NET_2_0
public void Deny ()
#else
public virtual void Deny ()
#endif
{
if (!SecurityManager.SecurityEnabled)
return;
foreach (IPermission p in list) {
// note: we ignore non-CAS permissions
if (p is IStackWalk) {
throw new NotSupportedException ("Currently only declarative Deny are supported.");
}
}
}
public virtual void FromXml (SecurityElement et)
{
if (et == null)
throw new ArgumentNullException ("et");
if (et.Tag != tagName) {
string msg = String.Format ("Invalid tag {0} expected {1}", et.Tag, tagName);
throw new ArgumentException (msg, "et");
}
list.Clear ();
if (CodeAccessPermission.IsUnrestricted (et)) {
state = PermissionState.Unrestricted;
#if NET_2_0
// no need to continue for an unrestricted permission
// because identity permissions now "supports" unrestricted
return;
#endif
} else {
state = PermissionState.None;
}
if (et.Children != null) {
foreach (SecurityElement se in et.Children) {
string className = se.Attribute ("class");
if (className == null) {
throw new ArgumentException (Locale.GetText (
"No permission class is specified."));
}
if (Resolver != null) {
// policy class names do not have to be fully qualified
className = Resolver.ResolveClassName (className);
}
list.Add (PermissionBuilder.Create (className, se));
}
}
}
#if NET_2_0
public IEnumerator GetEnumerator ()
#else
public virtual IEnumerator GetEnumerator ()
#endif
{
return list.GetEnumerator ();
}
#if NET_2_0
public bool IsSubsetOf (PermissionSet target)
{
// if target is empty we must be empty too
if ((target == null) || (target.IsEmpty ()))
return this.IsEmpty ();
// all permissions support unrestricted in 2.0
if (target.IsUnrestricted ())
return true;
if (this.IsUnrestricted ())
return false;
#else
public virtual bool IsSubsetOf (PermissionSet target)
{
#endif
if (this.IsUnrestricted () && ((target == null) || !target.IsUnrestricted ()))
return false;
// if each of our permission is (a) present and (b) a subset of target
foreach (IPermission p in list) {
#if !NET_2_0
if (target == null) {
if (!p.IsSubsetOf (null))
return false;
} else
#endif
{
// non CAS permissions must be evaluated for unrestricted
Type t = p.GetType ();
IPermission i = null;
if (target.IsUnrestricted () && (p is CodeAccessPermission) && (p is IUnrestrictedPermission)) {
i = (IPermission) Activator.CreateInstance (t, psUnrestricted);
} else {
i = target.GetPermission (t);
}
if (!p.IsSubsetOf (i))
return false; // not a subset (condition b)
}
}
return true;
}
[MonoTODO ("Imperative mode isn't supported")]
#if NET_2_0
public void PermitOnly ()
#else
public virtual void PermitOnly ()
#endif
{
if (!SecurityManager.SecurityEnabled)
return;
foreach (IPermission p in list) {
// note: we ignore non-CAS permissions
if (p is IStackWalk) {
throw new NotSupportedException ("Currently only declarative Deny are supported.");
}
}
}
public bool ContainsNonCodeAccessPermissions ()
{
if (list.Count > 0) {
foreach (IPermission p in list) {
if (! p.GetType ().IsSubclassOf (typeof (CodeAccessPermission)))
return true;
}
}
return false;
}
[MonoTODO ("little documentation in Fx 2.0 beta 1")]
public static byte[] ConvertPermissionSet (string inFormat, byte[] inData, string outFormat)
{
if (inFormat == null)
throw new ArgumentNullException ("inFormat");
if (outFormat == null)
throw new ArgumentNullException ("outFormat");
if (inData == null)
return null;
if (inFormat == outFormat)
return inData;
PermissionSet ps = null;
if (inFormat == "BINARY") {
if (outFormat.StartsWith ("XML")) {
using (MemoryStream ms = new MemoryStream (inData)) {
BinaryFormatter formatter = new BinaryFormatter ();
ps = (PermissionSet) formatter.Deserialize (ms);
ms.Close ();
}
string xml = ps.ToString ();
switch (outFormat) {
case "XML":
case "XMLASCII":
return Encoding.ASCII.GetBytes (xml);
case "XMLUNICODE":
return Encoding.Unicode.GetBytes (xml);
}
}
}
else if (inFormat.StartsWith ("XML")) {
if (outFormat == "BINARY") {
string xml = null;
switch (inFormat) {
case "XML":
case "XMLASCII":
xml = Encoding.ASCII.GetString (inData);
break;
case "XMLUNICODE":
xml = Encoding.Unicode.GetString (inData);
break;
}
if (xml != null) {
ps = new PermissionSet (PermissionState.None);
ps.FromXml (SecurityElement.FromString (xml));
MemoryStream ms = new MemoryStream ();
BinaryFormatter formatter = new BinaryFormatter ();
formatter.Serialize (ms, ps);
ms.Close ();
return ms.ToArray ();
}
}
else if (outFormat.StartsWith ("XML")) {
string msg = String.Format (Locale.GetText ("Can't convert from {0} to {1}"), inFormat, outFormat);
#if NET_2_0
throw new XmlSyntaxException (msg);
#else
throw new ArgumentException (msg);
#endif
}
}
else {
// unknown inFormat, returns null
return null;
}
// unknown outFormat, throw
throw new SerializationException (String.Format (Locale.GetText ("Unknown output format {0}."), outFormat));
}
#if NET_2_0
public IPermission GetPermission (Type permClass)
#else
public virtual IPermission GetPermission (Type permClass)
#endif
{
if ((permClass == null) || (list.Count == 0))
return null;
foreach (object o in list) {
if ((o != null) && o.GetType ().Equals (permClass))
return (IPermission) o;
}
// it's normal to return null for unrestricted sets
return null;
}
#if NET_2_0
public PermissionSet Intersect (PermissionSet other)
#else
public virtual PermissionSet Intersect (PermissionSet other)
#endif
{
// no intersection possible
if ((other == null) || (other.IsEmpty ()) || (this.IsEmpty ()))
return null;
PermissionState state = PermissionState.None;
if (this.IsUnrestricted () && other.IsUnrestricted ())
state = PermissionState.Unrestricted;
PermissionSet interSet = null;
#if NET_2_0
// much simpler with 2.0
if (state == PermissionState.Unrestricted) {
interSet = new PermissionSet (state);
} else if (this.IsUnrestricted ()) {
interSet = other.Copy ();
} else if (other.IsUnrestricted ()) {
interSet = this.Copy ();
} else {
interSet = new PermissionSet (state);
InternalIntersect (interSet, this, other, false);
}
#else
interSet = new PermissionSet (state);
if (state == PermissionState.Unrestricted) {
InternalIntersect (interSet, this, other, true);
InternalIntersect (interSet, other, this, true);
} else if (this.IsUnrestricted ()) {
InternalIntersect (interSet, this, other, true);
} else if (other.IsUnrestricted ()) {
InternalIntersect (interSet, other, this, true);
} else {
InternalIntersect (interSet, this, other, false);
}
#endif
return interSet;
}
internal void InternalIntersect (PermissionSet intersect, PermissionSet a, PermissionSet b, bool unrestricted)
{
foreach (IPermission p in b.list) {
// for every type in both list
IPermission i = a.GetPermission (p.GetType ());
if (i != null) {
// add intersection for this type
intersect.AddPermission (p.Intersect (i));
}
#if NET_2_0
// unrestricted is possible for indentity permissions
else if (unrestricted) {
#else
else if (unrestricted && (p is IUnrestrictedPermission)) {
#endif
intersect.AddPermission (p);
}
// or reject!
}
}
#if NET_2_0
public bool IsEmpty ()
#else
public virtual bool IsEmpty ()
#endif
{
// note: Unrestricted isn't empty
if (state == PermissionState.Unrestricted)
return false;
if ((list == null) || (list.Count == 0))
return true;
// the set may include some empty permissions
foreach (IPermission p in list) {
// empty == fully restricted == IsSubsetOf(null) == true
if (!p.IsSubsetOf (null))
return false;
}
return true;
}
#if NET_2_0
public bool IsUnrestricted ()
#else
public virtual bool IsUnrestricted ()
#endif
{
return (state == PermissionState.Unrestricted);
}
#if NET_2_0
public IPermission RemovePermission (Type permClass)
#else
public virtual IPermission RemovePermission (Type permClass)
#endif
{
if ((permClass == null) || _readOnly)
return null;
foreach (object o in list) {
if (o.GetType ().Equals (permClass)) {
list.Remove (o);
return (IPermission) o;
}
}
return null;
}
#if NET_2_0
public IPermission SetPermission (IPermission perm)
#else
public virtual IPermission SetPermission (IPermission perm)
#endif
{
if ((perm == null) || _readOnly)
return perm;
#if NET_2_0
IUnrestrictedPermission u = (perm as IUnrestrictedPermission);
if (u == null) {
state = PermissionState.None;
} else {
state = u.IsUnrestricted () ? state : PermissionState.None;
}
#else
if (perm is IUnrestrictedPermission)
state = PermissionState.None;
#endif
RemovePermission (perm.GetType ());
list.Add (perm);
return perm;
}
public override string ToString ()
{
return ToXml ().ToString ();
}
public virtual SecurityElement ToXml ()
{
SecurityElement se = new SecurityElement (tagName);
se.AddAttribute ("class", GetType ().FullName);
se.AddAttribute ("version", version.ToString ());
if (state == PermissionState.Unrestricted)
se.AddAttribute ("Unrestricted", "true");
// required for permissions that do not implement IUnrestrictedPermission
foreach (IPermission p in list) {
se.AddChild (p.ToXml ());
}
return se;
}
#if NET_2_0
public PermissionSet Union (PermissionSet other)
#else
public virtual PermissionSet Union (PermissionSet other)
#endif
{
if (other == null)
return this.Copy ();
PermissionSet copy = null;
if (this.IsUnrestricted () || other.IsUnrestricted ()) {
#if NET_2_0
// there are no child elements in unrestricted permission sets
return new PermissionSet (PermissionState.Unrestricted);
#else
copy = this.Copy ();
// so we keep the "right" type (e.g. NamedPermissionSet)
copy.Clear ();
copy.state = PermissionState.Unrestricted;
// copy all permissions that do not implement IUnrestrictedPermission
foreach (IPermission p in this.list) {
if (!(p is IUnrestrictedPermission))
copy.AddPermission (p);
}
foreach (IPermission p in other.list) {
if (!(p is IUnrestrictedPermission))
copy.AddPermission (p);
}
#endif
} else {
copy = this.Copy ();
// PermissionState.None -> copy all permissions
foreach (IPermission p in other.list) {
copy.AddPermission (p);
}
}
return copy;
}
public virtual int Count {
get { return list.Count; }
}
public virtual bool IsSynchronized {
get { return list.IsSynchronized; }
}
public virtual bool IsReadOnly {
// always false (as documented) but the PermissionSet can be read-only
// e.g. in a PolicyStatement
get { return false; }
}
public virtual object SyncRoot {
get { return this; }
}
internal bool DeclarativeSecurity {
get { return _declsec; }
set { _declsec = value; }
}
[MonoTODO ("may not be required")]
void IDeserializationCallback.OnDeserialization (object sender)
{
}
#if NET_2_0
[ComVisible (false)]
public override bool Equals (object obj)
{
if (obj == null)
return false;
PermissionSet ps = (obj as PermissionSet);
if (ps == null)
return false;
if (state != ps.state)
return false;
if (list.Count != ps.Count)
return false;
for (int i=0; i < list.Count; i++) {
bool found = false;
for (int j=0; i < ps.list.Count; j++) {
if (list [i].Equals (ps.list [j])) {
found = true;
break;
}
}
if (!found)
return false;
}
return true;
}
[ComVisible (false)]
public override int GetHashCode ()
{
return (list.Count == 0) ? (int) state : base.GetHashCode ();
}
[MonoTODO ("(2.0) what's it doing here? There's probably a reason this was added here.")]
static public void RevertAssert ()
{
CodeAccessPermission.RevertAssert ();
}
#endif
// internal
internal PolicyLevel Resolver {
get { return _policyLevel; }
set { _policyLevel = value; }
}
internal void SetReadOnly (bool value)
{
_readOnly = value;
}
private bool AllIgnored ()
{
if (_ignored == null)
throw new NotSupportedException ("bad bad bad");
for (int i=0; i < _ignored.Length; i++) {
if (!_ignored [i])
return false;
}
// everything is ignored (i.e. non-CAS permission or asserted permission).
return true;
}
internal bool ProcessFrame (SecurityFrame frame, ref Assembly current, ref AppDomain domain)
{
if (IsUnrestricted ()) {
// we request unrestricted
if (frame.Deny != null) {
// but have restrictions (some denied permissions)
CodeAccessPermission.ThrowSecurityException (this, "Deny", frame, SecurityAction.Demand, null);
} else if ((frame.PermitOnly != null) && !frame.PermitOnly.IsUnrestricted ()) {
// but have restrictions (only some permitted permissions)
CodeAccessPermission.ThrowSecurityException (this, "PermitOnly", frame, SecurityAction.Demand, null);
}
}
// skip next steps if no Assert, Deny or PermitOnly are present
if (frame.HasStackModifiers) {
for (int i = 0; i < list.Count; i++) {
CodeAccessPermission cap = (CodeAccessPermission) list [i];
if (cap.ProcessFrame (frame)) {
_ignored [i] = true; // asserted
if (AllIgnored ())
return true; // no more, abort stack walk!
}
}
}
// however the "final" grant set is resolved by assembly, so
// there's no need to check it every time (just when we're
// changing assemblies between frames).
if (frame.Assembly != current) {
CheckAssembly (current, frame);
current = frame.Assembly;
}
if (frame.Domain != domain) {
CheckAppDomain (domain, frame);
domain = frame.Domain;
}
return false;
}
internal void CheckAssembly (Assembly a, SecurityFrame frame)
{
IPermission p = SecurityManager.CheckPermissionSet (a, this, false);
if (p != null) {
CodeAccessPermission.ThrowSecurityException (this, "Demand failed assembly permissions checks.",
frame, SecurityAction.Demand, p);
}
}
internal void CheckAppDomain (AppDomain domain, SecurityFrame frame)
{
IPermission p = SecurityManager.CheckPermissionSet (domain, this);
if (p != null) {
CodeAccessPermission.ThrowSecurityException (this, "Demand failed appdomain permissions checks.",
frame, SecurityAction.Demand, p);
}
}
// 2.0 metadata format
internal static PermissionSet CreateFromBinaryFormat (byte[] data)
{
if ((data == null) || (data [0] != 0x2E) || (data.Length < 2)) {
string msg = Locale.GetText ("Invalid data in 2.0 metadata format.");
throw new SecurityException (msg);
}
int pos = 1;
int numattr = ReadEncodedInt (data, ref pos);
PermissionSet ps = new PermissionSet (PermissionState.None);
for (int i = 0; i < numattr; i++) {
IPermission p = ProcessAttribute (data, ref pos);
if (p == null) {
string msg = Locale.GetText ("Unsupported data found in 2.0 metadata format.");
throw new SecurityException (msg);
}
ps.AddPermission (p);
}
return ps;
}
internal static int ReadEncodedInt (byte[] data, ref int position)
{
int len = 0;
if ((data [position] & 0x80) == 0) {
len = data [position];
position ++;
} else if ((data [position] & 0x40) == 0) {
len = ((data [position] & 0x3f) << 8 | data [position + 1]);
position += 2;
} else {
len = (((data [position] & 0x1f) << 24) | (data [position + 1] << 16) |
(data [position + 2] << 8) | (data [position + 3]));
position += 4;
}
return len;
}
static object[] action = new object [1] { (SecurityAction) 0 };
// 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 ();
}
}
}
|