示例#1
0
 public void TestBlankACLValidAccount()
 {
     ACL acl = new ACL();
     Account account = new Account();
     acl.Add(new ACLAccount(account, DataOperation.All));
     acl.Check(new ManagedSecurityContext(account), DataOperation.Create);
 }
        /// <exception cref="System.Exception"/>
        private void VerifyACL(CuratorFramework curatorFramework, string path, ACL expectedACL
                               )
        {
            IList <ACL> acls = curatorFramework.GetACL().ForPath(path);

            Assert.Equal(1, acls.Count);
            Assert.Equal(expectedACL, acls[0]);
        }
示例#3
0
        /// <summary>Add a new write access entry for all future write operations.</summary>
        /// <param name="id">ID to use</param>
        /// <param name="pass">password</param>
        /// <exception cref="System.IO.IOException">on any failure to build the digest</exception>
        public virtual bool AddWriteAccessor(string id, string pass)
        {
            RegistrySecurity security = GetRegistrySecurity();
            ACL digestACL             = new ACL(ZooDefs.Perms.All, security.ToDigestId(security.Digest(id
                                                                                                       , pass)));

            return(security.AddDigestACL(digestACL));
        }
示例#4
0
 private S3CannedACL GetS3Acl(ACL acl)
 {
     return(acl switch
     {
         ACL.Read => S3CannedACL.PublicRead,
         ACL.Private => S3CannedACL.Private,
         _ => S3CannedACL.PublicRead,
     });
示例#5
0
        public void TestBlankACLValidAccount()
        {
            ACL     acl     = new ACL();
            Account account = new Account();

            acl.Add(new ACLAccount(account, DataOperation.All));
            acl.Check(new ManagedSecurityContext(account), DataOperation.Create);
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    var roles = this.CustomerService.GetAllCustomerRoles();
                    if (roles.Count == 0)
                    {
                        lblMessage.Text = GetLocaleResourceString("Admin.ACL.NoRolesDefined");
                        return;
                    }
                    this.ACLService.Enabled = cbACLEnabled.Checked;

                    foreach (GridViewRow row in gvACL.Rows)
                    {
                        foreach (CustomerRole cr in roles)
                        {
                            CheckBox    cbAllow            = row.FindControl(string.Format("cbAllow_{0}", cr.CustomerRoleId)) as CheckBox;
                            HiddenField hfCustomerActionId = row.FindControl(string.Format("hfCustomerActionId_{0}", cr.CustomerRoleId)) as HiddenField;
                            if (cbAllow == null || hfCustomerActionId == null || String.IsNullOrEmpty(hfCustomerActionId.Value))
                            {
                                return;
                            }

                            bool allow            = cbAllow.Checked;
                            int  customerActionId = int.Parse(hfCustomerActionId.Value);

                            var acls = this.ACLService.GetAllAcl(customerActionId, cr.CustomerRoleId, null);
                            if (acls.Count > 0)
                            {
                                ACL acl = acls[0];
                                acl.CustomerActionId = customerActionId;
                                acl.CustomerRoleId   = cr.CustomerRoleId;
                                acl.Allow            = allow;
                                this.ACLService.UpdateAcl(acl);
                            }
                            else
                            {
                                ACL acl = new ACL()
                                {
                                    CustomerActionId = customerActionId,
                                    CustomerRoleId   = cr.CustomerRoleId,
                                    Allow            = allow
                                };
                                this.ACLService.InsertAcl(acl);
                            }
                        }
                    }

                    Response.Redirect("ACL.aspx");
                }
                catch (Exception exc)
                {
                    ProcessException(exc);
                }
            }
        }
示例#7
0
 public void ReadFromJson(JsonData in_jsonObj)
 {
     m_state      = EntityState.Ready;
     m_entityType = (string)in_jsonObj["entityType"];
     m_entityId   = (string)in_jsonObj["entityId"];
     m_acl        = ACL.CreateFromJson(in_jsonObj["acl"]);
     UpdateTimeStamps(in_jsonObj);
     m_data = JsonToDictionary(in_jsonObj["data"]);
 }
示例#8
0
        public Uri Save(string domain, string path, Stream stream, string contentType,
                        string contentDisposition, ACL acl, string contentEncoding = null, int cacheDays = 5)
        {
            var buffered = stream.GetBuffered();

            if (QuotaController != null)
            {
                QuotaController.QuotaUsedCheck(buffered.Length);
            }

            using (var client = GetClient())
                using (var uploader = new TransferUtility(client))
                {
                    var mime = string.IsNullOrEmpty(contentType)
                                  ? MimeMapping.GetMimeMapping(Path.GetFileName(path))
                                  : contentType;

                    var request = new TransferUtilityUploadRequest
                    {
                        BucketName  = _bucket,
                        Key         = MakePath(domain, path),
                        CannedACL   = acl == ACL.Auto ? GetDomainACL(domain) : GetS3Acl(acl),
                        ContentType = mime,
                        ServerSideEncryptionMethod = ServerSideEncryptionMethod.AES256,
                        InputStream     = buffered,
                        AutoCloseStream = false,
                        Headers         =
                        {
                            CacheControl = string.Format("public, maxage={0}", (int)TimeSpan.FromDays(cacheDays).TotalSeconds),
                            Expires      = DateTime.UtcNow.Add(TimeSpan.FromDays(cacheDays))
                        }
                    };


                    if (!string.IsNullOrEmpty(contentDisposition))
                    {
                        request.Headers.ContentDisposition = contentDisposition;
                    }
                    else if (mime == "application/octet-stream")
                    {
                        request.Headers.ContentDisposition = "attachment";
                    }

                    if (!string.IsNullOrEmpty(contentEncoding))
                    {
                        request.Headers.ContentEncoding = contentEncoding;
                    }

                    uploader.Upload(request);

                    InvalidateCloudFront(MakePath(domain, path));

                    QuotaUsedAdd(domain, buffered.Length);

                    return(GetUri(domain, path));
                }
        }
 private PredefinedObjectAcl GetGoogleCloudAcl(ACL acl)
 {
     return(PredefinedObjectAcl.PublicRead);
     //return acl switch
     //{
     //    ACL.Read => PredefinedObjectAcl.PublicRead,
     //    _ => PredefinedObjectAcl.PublicRead,
     //};
 }
示例#10
0
 protected unsafe static extern uint SetNamedSecurityInfoW(
     [MarshalAs(UnmanagedType.LPTStr)]
     string pObjectName,
     int ObjectType,
     uint SecurityInfo,
     IntPtr ppsidOwner,
     IntPtr ppsidGroup,
     [In] ref ACL pDacl,
     IntPtr ppSacl
     );
        private static S3CannedACL GetS3Acl(ACL acl)
        {
            switch (acl)
            {
            case ACL.Read:
                return(S3CannedACL.PublicRead);

            default:
                return(S3CannedACL.PublicRead);
            }
        }
        public void ReadFromJson(object jsonObj)
        {
            Dictionary <string, object> jsonDict = (Dictionary <string, object>)jsonObj;

            m_state      = EntityState.Ready;
            m_entityType = (string)jsonDict["entityType"];
            m_entityId   = (string)jsonDict["entityId"];
            m_acl        = ACL.CreateFromJson((Dictionary <string, object>)jsonDict["acl"]);
            UpdateTimeStamps(jsonDict);
            m_data = JsonToDictionary(jsonDict["data"]);
        }
示例#13
0
        private PredefinedObjectAcl GetGoogleCloudAcl(ACL acl)
        {
            switch (acl)
            {
            case ACL.Read:
                return(PredefinedObjectAcl.PublicRead);

            default:
                return(PredefinedObjectAcl.PublicRead);
            }
        }
示例#14
0
        public void Test()
        {
            ACL acl = new ACL(ACL.Access.ReadWrite);

            Dictionary <string, object> jsonObj = new Dictionary <string, object> {
                { "other", 1 }
            };

            acl = ACL.CreateFromJson(jsonObj);

            Assert.AreEqual(ACL.Access.ReadOnly, acl.Other);
        }
        public RackspaceCloudStorage(string tenant)
        {
            _tenant     = tenant;
            _modulename = string.Empty;
            _dataList   = null;

            _domainsExpires = new Dictionary <string, TimeSpan> {
                { string.Empty, TimeSpan.Zero }
            };
            _domainsAcl = new Dictionary <string, ACL>();
            _moduleAcl  = ACL.Auto;
        }
示例#16
0
        public override Uri UploadWithoutQuota(string domain, string path, Stream stream, string contentType, string contentDisposition)
        {
            ACL acl = ACL.Auto;

            using (AmazonS3 client = GetClient())
            {
                var util = new Amazon.S3.Transfer.TransferUtility(client);

                var request = new Amazon.S3.Transfer.TransferUtilityUploadRequest();

                string mime = string.IsNullOrEmpty(contentType)
                                  ? MimeMapping.GetMimeMapping(Path.GetFileName(path))
                                  : contentType;

                const int uploadTimeout = 10 * 60 * 1000;

                request.BucketName  = _bucket;
                request.Key         = MakePath(domain, path);
                request.CannedACL   = acl == ACL.Auto ? GetDomainACL(domain) : GetS3Acl(acl);
                request.ContentType = mime;
                request.Timeout     = uploadTimeout;

                var headers = new NameValueCollection();
                headers.Add("Cache-Control", string.Format("public, maxage={0}", (int)TimeSpan.FromDays(5).TotalSeconds));
                headers.Add("Etag", (DateTime.UtcNow.Ticks).ToString(CultureInfo.InvariantCulture));
                headers.Add("Last-Modified", DateTime.UtcNow.ToString("R"));
                headers.Add("Expires", DateTime.UtcNow.Add(TimeSpan.FromDays(5)).ToString("R"));
                if (!string.IsNullOrEmpty(contentDisposition))
                {
                    headers.Add("Content-Disposition", Uri.EscapeDataString(contentDisposition));
                }
                else if (mime == "application/octet-stream")
                {
                    headers.Add("Content-Disposition", "attachment");
                }

                request.AddHeaders(headers);

                //Send body
                var buffered = stream.GetBuffered();

                request.AutoCloseStream = false;

                request.InputStream = buffered;

                util.Upload(request);

                InvalidateCloudFront(MakePath(domain, path));

                return(GetUri(domain, path));
            }
        }
示例#17
0
        public Uri Save(string domain, string path, Stream stream, string contentType,
                        string contentDisposition, ACL acl, string contentEncoding = null, int cacheDays = 5)
        {
            var buffered = stream.GetBuffered();

            if (QuotaController != null)
            {
                QuotaController.QuotaUsedCheck(buffered.Length);
            }

            var mime = string.IsNullOrEmpty(contentType)
                        ? MimeMapping.GetMimeMapping(Path.GetFileName(path))
                        : contentType;

            var storage = GetStorage();

            UploadObjectOptions uploadObjectOptions = new UploadObjectOptions
            {
                PredefinedAcl = acl == ACL.Auto ? GetDomainACL(domain) : GetGoogleCloudAcl(acl)
            };

            buffered.Position = 0;

            var uploaded = storage.UploadObject(_bucket, MakePath(domain, path), mime, buffered, uploadObjectOptions, null);

            uploaded.ContentEncoding = contentEncoding;
            uploaded.CacheControl    = String.Format("public, maxage={0}", (int)TimeSpan.FromDays(cacheDays).TotalSeconds);

            if (uploaded.Metadata == null)
            {
                uploaded.Metadata = new Dictionary <String, String>();
            }

            uploaded.Metadata["Expires"] = DateTime.UtcNow.Add(TimeSpan.FromDays(cacheDays)).ToString("R");

            if (!string.IsNullOrEmpty(contentDisposition))
            {
                uploaded.ContentDisposition = contentDisposition;
            }
            else if (mime == "application/octet-stream")
            {
                uploaded.ContentDisposition = "attachment";
            }

            storage.UpdateObject(uploaded);

            //           InvalidateCloudFront(MakePath(domain, path));

            QuotaUsedAdd(domain, buffered.Length);

            return(GetUri(domain, path));
        }
示例#18
0
        /// <summary>Init operation sets up the system ACLs.</summary>
        /// <param name="conf">configuration of the service</param>
        /// <exception cref="System.Exception"/>
        protected override void ServiceInit(Configuration conf)
        {
            base.ServiceInit(conf);
            RegistrySecurity registrySecurity = GetRegistrySecurity();

            if (registrySecurity.IsSecureRegistry())
            {
                ACL sasl = registrySecurity.CreateSaslACLFromCurrentUser(ZooDefs.Perms.All);
                registrySecurity.AddSystemACL(sasl);
                Log.Info("Registry System ACLs:", RegistrySecurity.AclsToString(registrySecurity.
                                                                                GetSystemACLs()));
            }
        }
示例#19
0
        public void TestAdminACL()
        {
            // make sure that the administrative ACL is a cloned fresh copy
            // (so that more ACLs can be added)
            ACL acl    = ACL.GetAdministrativeACL(Session);
            int count1 = acl.Count;

            acl.Add(new ACLAuthenticatedAllowCreate());
            ACL acl2 = ACL.GetAdministrativeACL(Session);

            Assert.AreNotEqual(acl, acl2);
            Assert.AreEqual(count1, acl2.Count);
        }
示例#20
0
        public SelectelStorage(String tenant, HandlerConfigurationElement handlerConfig, ModuleConfigurationElement moduleConfig)
        {
            _tenant     = tenant;
            _modulename = moduleConfig.Name;
            _dataList   = new DataList(moduleConfig);

            _domainsExpires = moduleConfig.Domains.Cast <DomainConfigurationElement>()
                              .Where(x => x.Expires != TimeSpan.Zero)
                              .ToDictionary(x => x.Name, y => y.Expires);

            _domainsExpires.Add(String.Empty, moduleConfig.Expires);
            _domainsAcl = moduleConfig.Domains.Cast <DomainConfigurationElement>().ToDictionary(x => x.Name, y => y.Acl);
            _moduleAcl  = moduleConfig.Acl;
        }
示例#21
0
        public bool DataCreate(string Path, string data)
        {
            CreateMode cm = CreateMode.Persistent;

            ACL auth = new ACL();

            List <ACL> authList = new List <ACL>();

            byte[] utf8Bytes = System.Text.Encoding.UTF8.GetBytes(data);

            zk.Create(Path, utf8Bytes, authList, cm);

            return(true);
        }
示例#22
0
        public IChannelACLEntry CreateACLEntry(IChannelGroup targetGroup)
        {
            var x = new ChanACL
            {
                ApplyOnSubchannels = true,
                ApplyOnThisChannel = true,
                Allow       = (ChannelPermissions)0,
                Deny        = (ChannelPermissions)0,
                TargetGroup = targetGroup,
            };

            ACL.Add(x);
            return(x);
        }
示例#23
0
文件: Library.cs 项目: radtek/EMIP
        public virtual Library.Library CreateLibrary(HttpContext context)
        {
            YZRequest request          = new YZRequest(context);
            string    libType          = request.GetString("libType");
            string    FolderID         = request.GetString("FolderID", null);
            string    DocumentFolderID = request.GetString("DocumentFolderID", null);
            JObject   jPost            = request.GetPostData <JObject>();

            Library.Library libPost = jPost["data"].ToObject <Library.Library>();
            ACL             acl     = jPost["acl"].ToObject <ACL>();

            using (IYZDbProvider provider = YZDbProviderManager.DefaultProvider)
            {
                using (IDbConnection cn = provider.OpenConnection())
                {
                    Library.Library lib = new Library.Library();
                    lib.LibType = libType;
                    lib.Name    = libPost.Name;
                    lib.Desc    = libPost.Desc;

                    if (!String.IsNullOrEmpty(FolderID))
                    {
                        Folder folder = this.CreateLibFolder(provider, cn, libPost.Name, FolderID);
                        lib.FolderID = folder.FolderID;
                    }

                    if (!String.IsNullOrEmpty(DocumentFolderID))
                    {
                        Folder folder = this.CreateLibFolder(provider, cn, libPost.Name, DocumentFolderID);
                        lib.DocumentFolderID = folder.FolderID;
                    }

                    lib.Owner       = YZAuthHelper.LoginUserAccount;
                    lib.CreateAt    = DateTime.Now;
                    lib.ImageFileID = libPost.ImageFileID;
                    lib.OrderIndex  = LibraryManager.GetLibraryNextOrderIndex(provider, cn, libType);
                    lib.Deleted     = false;

                    LibraryManager.Insert(provider, cn, lib);

                    using (BPMConnection bpmcn = new BPMConnection())
                    {
                        bpmcn.WebOpen();
                        SecurityManager.SaveACL(bpmcn, SecurityResType.Library, lib.LibID.ToString(), null, acl);
                    }

                    return(lib);
                }
            }
        }
示例#24
0
        public virtual void SaveFolder(HttpContext context)
        {
            YZRequest       request         = new YZRequest(context);
            SecurityResType securityResType = request.GetEnum <SecurityResType>("securityResType");
            string          path            = request.GetString("path", "");
            JObject         post            = request.GetPostData <JObject>();
            ACL             acl             = post["acl"].ToObject <ACL>();

            using (BPMConnection cn = new BPMConnection())
            {
                cn.WebOpen();
                SecurityManager.SaveACL(cn, securityResType, path, null, acl);
            }
        }
示例#25
0
        /// <summary>Parse the IDs, adding a realm if needed, setting the permissions</summary>
        /// <param name="principalList">id string</param>
        /// <param name="realm">realm to add</param>
        /// <param name="perms">permissions</param>
        /// <returns>the relevant ACLs</returns>
        /// <exception cref="System.IO.IOException"/>
        public virtual IList <ACL> BuildACLs(string principalList, string realm, int perms
                                             )
        {
            IList <string> aclPairs = SplitAclPairs(principalList, realm);
            IList <ACL>    ids      = new AList <ACL>(aclPairs.Count);

            foreach (string aclPair in aclPairs)
            {
                ACL newAcl = new ACL();
                newAcl.SetId(Parse(aclPair, realm));
                newAcl.SetPerms(perms);
                ids.AddItem(newAcl);
            }
            return(ids);
        }
示例#26
0
        public string[] DumpToStringArray()
        {
            var list = new List <string>();

            list.Add($"AccountName={AccountName}");
            list.Add($"AccountKey={AccountKey}");
            list.Add($"FileSystem={FileSystem}");
            list.Add($"StartingPath={StartingPath}");
            list.Add($"ExitAfter={ExitAfter}");
            list.Add($"Parallelism={Parallelism}");
            list.Add($"ACL:");
            ACL?.ToList().ForEach(x => list.Add($" - {x}"));
            list.Add($"RemoveList:");
            RemoveList?.ToList().ForEach(x => list.Add($" - {x}"));
            return(list.ToArray());
        }
示例#27
0
        public virtual void TestDigestAccess()
        {
            RMRegistryOperationsService registryAdmin = StartRMRegistryOperations();
            string id   = "username";
            string pass = "******";

            registryAdmin.AddWriteAccessor(id, pass);
            IList <ACL> clientAcls = registryAdmin.GetClientAcls();

            Log.Info("Client ACLS=\n{}", RegistrySecurity.AclsToString(clientAcls));
            string @base = "/digested";

            registryAdmin.Mknode(@base, false);
            IList <ACL> baseACLs = registryAdmin.ZkGetACLS(@base);
            string      aclset   = RegistrySecurity.AclsToString(baseACLs);

            Log.Info("Base ACLs=\n{}", aclset);
            ACL found = null;

            foreach (ACL acl in baseACLs)
            {
                if (ZookeeperConfigOptions.SchemeDigest.Equals(acl.GetId().GetScheme()))
                {
                    found = acl;
                    break;
                }
            }
            NUnit.Framework.Assert.IsNotNull("Did not find digest entry in ACLs " + aclset, found
                                             );
            zkClientConf.Set(KeyRegistryUserAccounts, "sasl:[email protected], sasl:other"
                             );
            RegistryOperations operations = RegistryOperationsFactory.CreateAuthenticatedInstance
                                                (zkClientConf, id, pass);

            AddToTeardown(operations);
            operations.Start();
            RegistryOperationsClient operationsClient = (RegistryOperationsClient)operations;
            IList <ACL> digestClientACLs = operationsClient.GetClientAcls();

            Log.Info("digest client ACLs=\n{}", RegistrySecurity.AclsToString(digestClientACLs
                                                                              ));
            operations.Stat(@base);
            operations.Mknode(@base + "/subdir", false);
            ZKPathDumper pathDumper = registryAdmin.DumpPath(true);

            Log.Info(pathDumper.ToString());
        }
示例#28
0
        public virtual JObject GenInheriACL(HttpContext context)
        {
            YZRequest request = new YZRequest(context);
            string    rsid    = request.GetString("rsid");

            JObject rv = new JObject();

            using (BPMConnection cn = new BPMConnection())
            {
                cn.WebOpen();
                ACL acl = SecurityManager.GenInheriACL(cn, rsid);

                rv["acl"] = this.Serialize(cn, acl);
            }

            return(rv);
        }
示例#29
0
        public virtual void TestGoodACLs()
        {
            IList <ACL> result = ZKUtil.ParseACLs("sasl:hdfs/[email protected]:cdrwa, sasl:hdfs/[email protected]:ca"
                                                  );
            ACL acl0 = result[0];

            Assert.Equal(ZooDefs.Perms.Create | ZooDefs.Perms.Delete | ZooDefs.Perms
                         .Read | ZooDefs.Perms.Write | ZooDefs.Perms.Admin, acl0.GetPerms());
            Assert.Equal("sasl", acl0.GetId().GetScheme());
            Assert.Equal("hdfs/[email protected]", acl0.GetId().GetId());
            ACL acl1 = result[1];

            Assert.Equal(ZooDefs.Perms.Create | ZooDefs.Perms.Admin, acl1.
                         GetPerms());
            Assert.Equal("sasl", acl1.GetId().GetScheme());
            Assert.Equal("hdfs/[email protected]", acl1.GetId().GetId());
        }
示例#30
0
        public virtual JObject GetStoreObjectPerms(HttpContext context)
        {
            YZRequest               request  = new YZRequest(context);
            StoreZoneType           zone     = request.GetEnum <StoreZoneType>("zone");
            string                  path     = request.GetString("path", null);
            string                  strPerms = request.GetString("perms", null);
            BPMObjectNameCollection ids      = BPMObjectNameCollection.FromStringList(request.GetString("ids", ""), ',');;

            BPMPermision[] bpmPerms = YZSecurityHelper.ParsePermisions(strPerms);

            JObject rv    = new JObject();
            JObject perms = new JObject();

            rv["perms"] = perms;

            using (BPMConnection cn = new BPMConnection())
            {
                cn.WebOpen();

                foreach (string id in ids)
                {
                    string fullName;
                    if (String.IsNullOrEmpty(path))
                    {
                        fullName = id;
                    }
                    else
                    {
                        fullName = path + "/" + id;
                    }

                    ACL acl = SecurityManager.GetACL(cn, zone.ToString() + "://" + fullName);

                    JObject jPerm = new JObject();
                    perms[id] = jPerm;

                    foreach (BPMPermision perm in bpmPerms)
                    {
                        jPerm[perm.ToString()] = acl.HasPermision(cn.Token, perm);
                    }
                }
            }

            rv[YZJsonProperty.success] = true;
            return(rv);
        }
示例#31
0
        private S3CannedACL GetS3Acl(ACL acl)
        {
            switch (acl)
            {
            case ACL.Read:
                return(S3CannedACL.PublicRead);

            case ACL.Write:
                return(S3CannedACL.PublicReadWrite);

            case ACL.Private:
                return(S3CannedACL.AuthenticatedRead);

            default:
                return(S3CannedACL.PublicRead);
            }
        }
示例#32
0
        public void ACLTest01()
        {
            ACL acl = new ACL();

            Role Guests = new Role("Guests");
            acl.AddRole(Guests);

            Role[] parents = new Role[1];
            parents[0] = Guests;

            Role JoeGuest = new Role("JoeGuest", parents);
            acl.AddRole(JoeGuest);

            Resource CanBuild = new Resource("CanBuild");
            acl.AddResource(CanBuild);


            acl.GrantPermission("Guests", "CanBuild");

            Permission perm = acl.HasPermission("JoeGuest", "CanBuild");
            Assert.That(perm == Permission.Allow, "JoeGuest should have permission to build");
            perm = Permission.None;
            try
            {
                perm = acl.HasPermission("unknownGuest", "CanBuild");
                
            }
            catch (KeyNotFoundException)
            {
                
               
            }
            catch (Exception)
            {
                Assert.That(false,"Exception thrown should have been KeyNotFoundException");
            }
            Assert.That(perm == Permission.None,"Permission None should be set because exception should have been thrown");
            
        }
 private static S3CannedACL GetS3Acl(ACL acl)
 {
     switch (acl)
     {
         case ACL.Read:
             return S3CannedACL.PublicRead;
         default:
             return S3CannedACL.PublicRead;
     }
 }
 public void Deserialize(IInputArchive a_, String tag)
 {
     a_.StartRecord(tag);
     Path=a_.ReadString("path");
     {
       IIndex vidx1 = a_.StartVector("acl");
       if (vidx1!= null) {          var tmpLst=new System.Collections.Generic.List<ACL>();
       for (; !vidx1.Done(); vidx1.Incr()) {
     ACL e1;
     e1= new ACL();
     a_.ReadRecord(e1,"e1");
     tmpLst.Add(e1);
       }
     Acl=tmpLst;
       }
     a_.EndVector("acl");
     }
     Version=a_.ReadInt("version");
     a_.EndRecord(tag);
 }
示例#35
0
 private S3CannedACL GetS3Acl(ACL acl)
 {
     switch (acl)
     {
         case ACL.Read:
             return S3CannedACL.PublicRead;
         case ACL.Write:
             return S3CannedACL.PublicReadWrite;
         case ACL.Private:
             return S3CannedACL.AuthenticatedRead;
         default:
             return S3CannedACL.PublicRead;
     }
 }
示例#36
0
        public Uri Save(string domain, string path, Stream stream, string contentType,
                                 string contentDisposition, ACL acl, string contentEncoding = null, int cacheDays = 5)
        {
            bool postWriteCheck = false;
            if (QuotaController != null)
            {
                try
                {
                    QuotaController.QuotaUsedAdd(_modulename, domain, _dataList.GetData(domain), stream.Length);
                }
                catch (TenantQuotaException)
                {
                    //this exception occurs only if tenant has no free space
                    //or if file size larger than allowed by quota
                    //so we can exit this function without stream buffering etc
                    throw;
                }
                catch (Exception)
                {
                    postWriteCheck = true;
                }
            }


            using (AmazonS3 client = GetClient())
            {
                var request = new PutObjectRequest();
                string mime = string.IsNullOrEmpty(contentType)
                                  ? MimeMapping.GetMimeMapping(Path.GetFileName(path))
                                  : contentType;

                request.BucketName = _bucket;
                request.Key = MakePath(domain, path);
                request.CannedACL = acl == ACL.Auto ? GetDomainACL(domain) : GetS3Acl(acl);
                request.ContentType = mime;
                 
                request.ServerSideEncryptionMethod = ServerSideEncryptionMethod.AES256;

                var requestHeaders = new NameValueCollection();
                requestHeaders.Add("Cache-Control", string.Format("public, maxage={0}", (int)TimeSpan.FromDays(cacheDays).TotalSeconds));
                requestHeaders.Add("Etag", (DateTime.UtcNow.Ticks).ToString(CultureInfo.InvariantCulture));
                requestHeaders.Add("Last-Modified", DateTime.UtcNow.ToString("R"));
                requestHeaders.Add("Expires", DateTime.UtcNow.Add(TimeSpan.FromDays(cacheDays)).ToString("R"));

                if (!string.IsNullOrEmpty(contentDisposition))
                {
                    requestHeaders.Add("Content-Disposition", contentDisposition);
                }
                else if (mime == "application/octet-stream")
                {
                    requestHeaders.Add("Content-Disposition", "attachment");
                }

                if (!string.IsNullOrEmpty(contentEncoding))
                {
                    requestHeaders.Add("Content-Encoding", contentEncoding);
                }

                request.AddHeaders(requestHeaders);

                //Send body
                var buffered = stream.GetBuffered();
                if (postWriteCheck)
                {
                    QuotaController.QuotaUsedAdd(_modulename, domain, _dataList.GetData(domain), buffered.Length);
                }
                request.AutoCloseStream = false;

                request.InputStream = buffered;
                
                PutObjectResponse response = client.PutObject(request);
                var destinationObjectEncryptionStatus = response.ServerSideEncryptionMethod;

                    //..ServerSideEncryptionMethod;

                InvalidateCloudFront(MakePath(domain, path));

                return GetUri(domain, path);
            }
        }
示例#37
0
 public override Uri Save(string domain, string path, Stream stream, ACL acl)
 {
     return Save(domain, path, stream);
 }
示例#38
0
        bool CreateKeyDescriptor(IntPtr pOldSD, ACCOUNT_PERM Account, ref MEM_DATA MemData)
        {
            // reconstruct security descriptor
            bool bDefault = false;
            bool bPresent = false;
            int iControlBits = 0;
            int iControlSet = 0;
            int iDomain = 0;
            int iFlag = 0;
            int iLength = 0;
            int iRevision = 0;
            int iSidLen = 0;
            int iTotal = 0;
            int iUse = 0;
            StringBuilder sDomain = new StringBuilder(256);
            IntPtr pNewACL = IntPtr.Zero;
            IntPtr pAcl = IntPtr.Zero;
            IntPtr pSid = IntPtr.Zero;
            IntPtr pPnt = IntPtr.Zero;
            ACL_SIZE_INFORMATION tAclSize = new ACL_SIZE_INFORMATION();
            ACL tTempACL = new ACL();
            ACE tTempAce = new ACE();

            try
            {
                MemData.pAcl = IntPtr.Zero;
                MemData.pSd = IntPtr.Zero;
                // get size
                pSid = LocalAlloc(LMEM_INITIALIZED, SECURITY_DESCRIPTOR_MIN_LENGTH);
                if (pSid == IntPtr.Zero)
                {
                    return false;
                }
                // store pointer
                MemData.pSd = pSid;

                // init descriptor
                if (InitializeSecurityDescriptor(pSid, SECURITY_DESCRIPTOR_REVISION) == 0)
                {
                    return false;
                }

                // check for existing sd
                if (pOldSD != IntPtr.Zero)
                {
                    if (GetSecurityDescriptorDacl(pOldSD, out bPresent, ref pAcl, out bDefault) == true)
                    {
                        // extract dacl
                        if ((bPresent == true) && (pAcl != IntPtr.Zero))
                        {
                            if (GetAclInformation(pAcl, ref tAclSize, Marshal.SizeOf(tAclSize), ACL_INFORMATION_CLASS.AclSizeInformation) == false)
                            {
                                return false;
                            }
                            else
                            {
                                iTotal = tAclSize.AclBytesInUse;
                            }
                        }
                        else
                        {
                            iTotal = Marshal.SizeOf(tTempACL);
                        }
                    }
                    else
                    {
                        return false;
                    }
                }

                // allocate sid //
                // get callers sid
                if (Account.pSid == IntPtr.Zero)
                {
                    iDomain = 256;
                    // get size
                    LookupAccountName(null, Account.AccountName, IntPtr.Zero, ref iSidLen, sDomain, ref iDomain, out iUse);
                    Account.pSid = LocalAlloc(LMEM_INITIALIZED, iSidLen);
                    if (Account.pSid == IntPtr.Zero)
                    {
                        return false;
                    }
                    // get the sid
                    if (LookupAccountName(null, Account.AccountName, Account.pSid, ref iSidLen, sDomain, ref iDomain, out iUse) == false)
                    {
                        return false;
                    }
                }

                // ace buffer
                iLength = (Marshal.SizeOf(tTempAce) + GetLengthSid(Account.pSid)) - 4;
                iTotal += iLength;
                pNewACL = LocalAlloc(LMEM_INITIALIZED, iTotal);
                if (pNewACL == IntPtr.Zero)
                {
                    return false;
                }
                // store pointer
                MemData.pAcl = pNewACL;

                // init acl
                if (InitializeAcl(pNewACL, iTotal, ACL_REVISION) == false)
                {
                    return false;
                }

                // build dacl in sequence
                if (Account.AceType == ACCESS_DENIED_ACE_TYPE)
                {
                    if (BuildACE(pNewACL, Account.AceType, Account.AceFlags, Account.AccessMask, Account.pSid) == false)
                    {
                        return false;
                    }
                }

                // copy non-inherited ace
                if ((bPresent == true) && (pAcl != IntPtr.Zero) && (tAclSize.AceCount > 0))
                {
                    // combine old and new ACE entries
                    for (int count = 0; count < tAclSize.AceCount; count++)
                    {
                        // next ace
                        GetAce(pAcl, count, out pPnt);
                        if (pPnt == IntPtr.Zero)
                        {
                            return false;
                        }
                        RtlMoveMemory(ref tTempAce, pPnt, Marshal.SizeOf(tTempAce));
                        // exit on inherited ace
                        if (((int)tTempAce.Header.AceFlags & INHERITED_ACE) == INHERITED_ACE)
                        {
                            break;
                        }
                        int x = (int)pPnt + 8;
                        IntPtr pPt = new IntPtr(x);
                        // check ace value
                        if (!SidIsEqual(Account.pSid, pPt))
                        {
                            // add ace
                            AddAce(pNewACL, ACL_REVISION, MAXDWORD, pPnt, tTempAce.Header.AceSize);
                        }
                    }
                }

                // add explicit permit
                if (Account.AceType == ACCESS_ALLOWED_ACE_TYPE)
                {
                    BuildACE(pNewACL, Account.AceType, Account.AceFlags, Account.AccessMask, Account.pSid);
                }

                // enties with inheritence flag
                if ((bPresent == true) && (pAcl != IntPtr.Zero) && (tAclSize.AceCount > 0))
                {
                    for (int count = 0; count < tAclSize.AceCount; count++)
                    {
                        GetAce(pAcl, count, out pPnt);
                        RtlMoveMemory(ref tTempAce, pPnt, Marshal.SizeOf(tTempAce));
                        AddAce(pNewACL, ACL_REVISION, MAXDWORD, pPnt, tTempAce.Header.AceSize);
                    }
                }

                // descriptor flags
                if (pOldSD != IntPtr.Zero)
                {
                    if (GetSecurityDescriptorControl(pOldSD, out iFlag, out iRevision) != 0)
                    {
                        if ((iFlag & SE_DACL_AUTO_INHERITED) == SE_DACL_AUTO_INHERITED)
                        {
                            iControlBits = SE_DACL_AUTO_INHERIT_REQ | SE_DACL_AUTO_INHERITED;
                            iControlSet = iControlBits;
                        }
                        else if ((iFlag & SE_DACL_PROTECTED) == SE_DACL_PROTECTED)
                        {
                            iControlBits = SE_DACL_PROTECTED;
                            iControlSet = iControlBits;
                        }
                        if (iControlSet != 0)
                        {
                            SetSecurityDescriptorControl(pSid, iControlBits, iControlSet);
                        }
                    }
                }
                // add dacl
                return SetSecurityDescriptorDacl(pSid, 1, pNewACL, 0);
            }

            finally
            {
                if (Account.pSid != IntPtr.Zero)
                {
                    LocalFree(Account.pSid);
                    Account.pSid = IntPtr.Zero;
                }
            }
        }
示例#39
0
        public Uri Save(string domain, string path, Stream stream, string contentType,
                                 string contentDisposition, ACL acl)
        {
            bool postWriteCheck = false;
            if (QuotaController != null)
            {
                try
                {
                    QuotaController.QuotaUsedAdd(_modulename, domain, _dataList.GetData(domain), stream.Length);
                }
                catch (Exception)
                {
                    postWriteCheck = true;
                }
            }


            using (AmazonS3 client = GetClient())
            {
                var request = new PutObjectRequest();
                string mime = string.IsNullOrEmpty(contentType)
                                  ? MimeMapping.GetMimeMapping(Path.GetFileName(path))
                                  : contentType;

                request.WithBucketName(_bucket)
                    .WithKey(MakePath(domain, path))
                    .WithCannedACL(acl == ACL.Auto ? GetDomainACL(domain) : GetS3Acl(acl))
                    .WithContentType(mime);

                var headers = new NameValueCollection();
                headers.Add("Cache-Control", string.Format("public, maxage={0}", (int)TimeSpan.FromDays(5).TotalSeconds));
                headers.Add("Etag", (DateTime.UtcNow.Ticks).ToString());
                headers.Add("Last-Modified", DateTime.UtcNow.ToString("R"));
                headers.Add("Expires", DateTime.UtcNow.Add(TimeSpan.FromDays(5)).ToString("R"));
                if (!string.IsNullOrEmpty(contentDisposition))
                {

                    headers.Add("Content-Disposition", contentDisposition);
                }
                else if (mime == "application/octet-stream")
                {
                    headers.Add("Content-Disposition", "attachment");
                }

                request.AddHeaders(headers);

                //Send body
                var buffered = stream.GetBuffered();
                if (postWriteCheck)
                {
                    QuotaController.QuotaUsedAdd(_modulename, domain, _dataList.GetData(domain), buffered.Length);
                }
                request.AutoCloseStream = false;

                request.WithInputStream(buffered);
                client.PutObject(request);
                InvalidateCloudFront(MakePath(domain, path));

                return GetUri(domain, path);
            }
        }
示例#40
0
        public void KnownButPermissionDenyAndPermissionNoneUserTest()
        {
            ACL acl = new ACL();

            Role Guests = new Role("Guests");
            acl.AddRole(Guests);
            Role Administrators = new Role("Administrators");
            acl.AddRole(Administrators);
            Role[] Guestparents = new Role[1];
            Role[] Adminparents = new Role[1];

            Guestparents[0] = Guests;
            Adminparents[0] = Administrators;

            Role JoeGuest = new Role("JoeGuest", Guestparents);
            acl.AddRole(JoeGuest);

            Resource CanBuild = new Resource("CanBuild");
            acl.AddResource(CanBuild);

            Resource CanScript = new Resource("CanScript");
            acl.AddResource(CanScript);

            Resource CanRestart = new Resource("CanRestart");
            acl.AddResource(CanRestart);

            acl.GrantPermission("Guests", "CanBuild");
            acl.DenyPermission("Guests", "CanRestart");

            acl.GrantPermission("Administrators", "CanScript");

            acl.GrantPermission("Administrators", "CanRestart");
            Permission setPermission = acl.HasPermission("JoeGuest", "CanRestart");
            Assert.That(setPermission == Permission.Deny, "Guests Should not be able to restart");
            Assert.That(acl.HasPermission("JoeGuest", "CanScript") == Permission.None,
                        "No Explicit Permissions set so should be Permission.None");
        }
示例#41
0
文件: Security.cs 项目: rcarz/fusion
        /// <summary>
        /// Sets the mandatory label on the given file or directory object.
        /// </summary>
        /// <param name="target">target file or directory path</param>
        /// <param name="flags">flags to control inheritance</param>
        /// <param name="policy">access policy</param>
        /// <param name="mlrid">mandatory integrity level</param>
        public static void SetFileMandatoryLabel(string target, AceFlags flags, MandatoryPolicy policy, 
            MandatoryLabel mlrid)
        {
            SID_IDENTIFIER_AUTHORITY mlauth = new SID_IDENTIFIER_AUTHORITY() {
                Value = MANDATORY_LABEL_AUTHORITY
            };
            SYSTEM_MANDATORY_LABEL_ACE mlace = new SYSTEM_MANDATORY_LABEL_ACE();
            ACL acl = new ACL();
            IntPtr sdptr = new IntPtr(0);
            IntPtr saclptr;
            IntPtr mlauthptr;
            IntPtr sidptr;
            IntPtr newsdptr = new IntPtr(0);
            int szneeded = 0;
            int size = 0;
            bool present = false;
            bool defaulted = false;
            int errno = 0;

            if (!File.Exists(target) && !Directory.Exists(target))
                throw new FileNotFoundException("The path '" + target + "' was not found.");

            Security.GetFileSecurity(target, LABEL_SECURITY_INFORMATION, sdptr, size, ref szneeded);
            sdptr = Marshal.AllocHGlobal(szneeded);
            size = szneeded;

            if (!Security.GetFileSecurity(target, LABEL_SECURITY_INFORMATION, sdptr, size, ref szneeded)) {
                errno = Marshal.GetLastWin32Error();
                Marshal.FreeHGlobal(sdptr);
                throw new IOException("Failed to read file security information. (" + errno + ")");
            }

            if (!Security.GetSecurityDescriptorSacl(sdptr, ref present, out saclptr, ref defaulted)) {
                errno = Marshal.GetLastWin32Error();
                Marshal.FreeHGlobal(sdptr);
                throw new IOException("Failed to read security descriptor SACL. (" + errno + ")");
            }

            if (!Security.ConvertSecurityDescriptor(sdptr, out newsdptr, out errno)) {
                Marshal.FreeHGlobal(sdptr);
                throw new IOException("Failed to convert security descriptor. (" + errno + ")");
            }

            Marshal.FreeHGlobal(sdptr);

            mlauthptr = Marshal.AllocHGlobal(Marshal.SizeOf(mlauth));
            Marshal.StructureToPtr(mlauth, mlauthptr, false);

            if (!Security.AllocateAndInitializeSid(mlauthptr, 1, (int)mlrid, 0, 0, 0, 0, 0, 0, 0, out sidptr)) {
                errno = Marshal.GetLastWin32Error();
                Marshal.FreeHGlobal(newsdptr);
                Marshal.FreeHGlobal(mlauthptr);
                throw new IOException("Failed to allocate new SID. (" + errno + ")");
            }

            Marshal.FreeHGlobal(mlauthptr);

            int cbAcl = Marshal.SizeOf(acl) + Marshal.SizeOf(mlace) + (Security.GetLengthSid(sidptr) - sizeof(int));
            cbAcl = (cbAcl + (sizeof(int) - 1)) & 0xfffc;   /* align cbAcl to an int */
            saclptr = Marshal.AllocHGlobal(cbAcl);

            if (!InitializeAcl(saclptr, cbAcl, ACL_REVISION)) {
                errno = Marshal.GetLastWin32Error();
                Marshal.FreeHGlobal(newsdptr);
                Marshal.FreeHGlobal(sidptr);
                Marshal.FreeHGlobal(saclptr);
                throw new IOException("Failed to initialise new ACL. (" + errno + ")");
            }

            if (!Security.AddMandatoryAce(saclptr, ACL_REVISION, (int)flags, (int)policy, sidptr)) {
                errno = Marshal.GetLastWin32Error();
                Marshal.FreeHGlobal(newsdptr);
                Marshal.FreeHGlobal(sidptr);
                Marshal.FreeHGlobal(saclptr);
                throw new IOException("Failed to add new mandatory ACE. (" + errno + ")");
            }

            Marshal.FreeHGlobal(sidptr);

            if (!Security.SetSecurityDescriptorSacl(newsdptr, true, saclptr, false)) {
                errno = Marshal.GetLastWin32Error();
                Marshal.FreeHGlobal(newsdptr);
                Marshal.FreeHGlobal(saclptr);
                throw new IOException("Failed to set security descriptor SACL. (" + errno + ")");
            }

            if (!Security.SetFileSecurity(target, LABEL_SECURITY_INFORMATION, newsdptr)) {
                errno = Marshal.GetLastWin32Error();
                Marshal.FreeHGlobal(newsdptr);
                Marshal.FreeHGlobal(saclptr);
                throw new IOException("Failed to write file security information. (" + errno + ")");
            }

            Marshal.FreeHGlobal(newsdptr);
            Marshal.FreeHGlobal(saclptr);
        }
示例#42
0
 public void TestBlankACLNonAdminAccount()
 {
     ACL acl = new ACL();
     acl.Check(new ManagedSecurityContext(new Account()), DataOperation.Create);
 }
示例#43
0
 /// <summary>
 /// new
 /// </summary>
 /// <param name="path"></param>
 /// <param name="acl"></param>
 /// <param name="version"></param>
 public SetACLRequest(string path, ACL[] acl, int version)
 {
     this.Path = path;
     this.Acl = acl;
     this.Version = version;
 }
示例#44
0
 public void TestBlankACLAdminAccount()
 {
     ACL acl = new ACL();
     acl.Check(new ManagedSecurityContext(ManagedAccount.GetAdminAccount(Session)), DataOperation.Create);
 }
示例#45
0
 public void TestBlankACLInvalidAccount()
 {
     ACL acl = new ACL();
     acl.Add(new ACLAccount(new Account(), DataOperation.All));
     acl.Check(new ManagedSecurityContext((Account) null), DataOperation.Create);
 }
示例#46
0
        public Uri Save(string domain, string path, Stream stream, string contentType,
                                 string contentDisposition, ACL acl, string contentEncoding = null, int cacheDays = 5)
        {
            bool postWriteCheck = false;
            if (QuotaController != null)
            {
                try
                {
                    QuotaController.QuotaUsedAdd(_modulename, domain, _dataList.GetData(domain), stream.Length);
                }
                catch (TenantQuotaException)
                {
                    //this exception occurs only if tenant has no free space
                    //or if file size larger than allowed by quota
                    //so we can exit this function without stream buffering etc
                    throw;
                }
                catch (Exception)
                {
                    postWriteCheck = true;
                }
            }


            using (var client = GetClient())
            {

                var mime = string.IsNullOrEmpty(contentType)
                                  ? MimeMapping.GetMimeMapping(Path.GetFileName(path))
                                  : contentType;
                var buffered = stream.GetBuffered();

                var request = new PutObjectRequest
                {
                    BucketName = _bucket,
                    Key = MakePath(domain, path),
                    CannedACL = acl == ACL.Auto ? GetDomainACL(domain) : GetS3Acl(acl),
                    ContentType = mime,
                    ServerSideEncryptionMethod = ServerSideEncryptionMethod.AES256,
                    InputStream = buffered,
                    AutoCloseStream = false,
                    Headers =
                    {
                        CacheControl = string.Format("public, maxage={0}", (int)TimeSpan.FromDays(cacheDays).TotalSeconds),
                        ContentMD5 = Hasher.Base64Hash(buffered.GetCorrectBuffer(), HashAlg.MD5),
                        Expires = DateTime.UtcNow.Add(TimeSpan.FromDays(cacheDays))
                    }
                };


                if (!string.IsNullOrEmpty(contentDisposition))
                {
                    request.Headers.ContentDisposition = contentDisposition;
                }
                else if (mime == "application/octet-stream")
                {
                    request.Headers.ContentDisposition = "attachment";
                }

                if (!string.IsNullOrEmpty(contentEncoding))
                {
                    request.Headers.ContentEncoding = contentEncoding;
                }

                //Send body
                if (postWriteCheck)
                {
                    QuotaController.QuotaUsedAdd(_modulename, domain, _dataList.GetData(domain), buffered.Length);
                }

                var response = client.PutObject(request);
                var destinationObjectEncryptionStatus = response.ServerSideEncryptionMethod;

                //..ServerSideEncryptionMethod;

                InvalidateCloudFront(MakePath(domain, path));

                return GetUri(domain, path);
            }
        }
示例#47
0
 public void TestACLEveryoneRetreive()
 {
     ACL acl = new ACL();
     acl.Add(new ACLEveryoneAllowRetrieve());
     acl.Check(new ManagedSecurityContext(new Account()), DataOperation.Retreive);
 }
示例#48
0
 public abstract Uri Save(string domain, string path, Stream stream, ACL acl);
示例#49
0
文件: Cases.cs 项目: jrgcubano/zetbox
        public void DoCreateRightsViewUnmaterialized(ObjectClass objClass)
        {
            var tblName = db.GetTableName(objClass.Module.SchemaName, objClass.TableName);
            var tblRightsName = db.GetTableName(objClass.Module.SchemaName, Construct.SecurityRulesTableName(objClass));
            var rightsViewUnmaterializedName = db.GetTableName(objClass.Module.SchemaName, Construct.SecurityRulesRightsViewUnmaterializedName(objClass));

            if (objClass.AccessControlList.Count == 0)
            {
                Log.ErrorFormat("Unable to create RightsViewUnmaterialized: ObjectClass '{0}' has an empty AccessControlList", objClass.Name);
                db.CreateEmptyRightsViewUnmaterialized(rightsViewUnmaterializedName);
                return;
            }

            List<ACL> viewAcls = new List<ACL>();
            foreach (var ac in objClass.AccessControlList.OfType<RoleMembership>())
            {
                if (ac.Relations.Count == 0)
                {
                    Log.ErrorFormat("Unable to create RightsViewUnmaterialized: RoleMembership '{0}' has no relations", ac.Name);
                    db.CreateEmptyRightsViewUnmaterialized(rightsViewUnmaterializedName);
                    return;
                }

                var viewAcl = new ACL();
                viewAcls.Add(viewAcl);
                viewAcl.Right = (Zetbox.API.AccessRights)ac.Rights;
                try
                {
                    viewAcl.Relations.AddRange(SchemaManager.CreateJoinList(db, objClass, ac.Relations));
                }
                catch (SchemaManager.JoinListException ex)
                {
                    Log.ErrorFormat(ex.Message);
                    db.CreateEmptyRightsViewUnmaterialized(rightsViewUnmaterializedName);
                    return;
                }
            }

            db.CreateRightsViewUnmaterialized(rightsViewUnmaterializedName, tblName, tblRightsName, viewAcls);
        }