Ejemplo n.º 1
0
        /// <summary>
        /// Initializes a new instance of the SearchResultCollection class
        /// </summary>
        /// <param name="response">The initial enumeration response from the Resource Management Service</param>
        /// <param name="pageSize">The page size used in the search operation</param>
        /// <param name="searchClient">The client proxy used for performing the search</param>
        /// <param name="client">The client used to convert response data into ResourceObjects</param>
        /// <param name="locale">The localization culture that the search results are represented as</param>
        internal SearchResultPager(EnumerateResponse response, int pageSize, SearchClient searchClient, ResourceManagementClient client, CultureInfo locale)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }

            if (pageSize < 0)
            {
                throw new ArgumentException("The page size must be zero or greater", "pageSize");
            }

            if (searchClient == null)
            {
                throw new ArgumentNullException("client");
            }

            this.TotalCount           = Convert.ToInt32(response.EnumerationDetail.Count);
            this.client               = client;
            this.locale               = locale;
            this.context              = response.EnumerationContext;
            this.context.CurrentIndex = 0;
            this.PageSize             = pageSize;
            this.searchClient         = searchClient;
            this.EndOfSequence        = response.EndOfSequence != null;
        }
Ejemplo n.º 2
0
        public async Task EnumerateAsync_ReturnsSuccess()
        {
            // Arrange
            Mock <ILogger <SubdomainController> > mockLogger = new Mock <ILogger <SubdomainController> >();
            Mock <ISubdomainService> mockSubdomainService    = new Mock <ISubdomainService>();

            const string domainName = "yahoo.com";

            EnumerateResponse response = new EnumerateResponse
            {
                Subdomains = new List <string>
                {
                    "aa.yahoo.com"
                },
                Success = true
            };

            mockSubdomainService.Setup(q => q.EnumerateAsync(domainName)).Returns(Task.FromResult(response));

            SubdomainController controller = new SubdomainController(mockLogger.Object, mockSubdomainService.Object);

            // Act
            IActionResult result = await controller.EnumerateAsync(domainName);

            ObjectResult okObjectResult = result as ObjectResult;

            // Assert
            EnumerateResponse actual = (EnumerateResponse)okObjectResult.Value;

            Assert.NotNull(okObjectResult);
            Assert.True(okObjectResult is OkObjectResult);
            Assert.IsType <EnumerateResponse>(okObjectResult.Value);
            Assert.Equal(StatusCodes.Status200OK, okObjectResult.StatusCode);
            Assert.True(actual.Success);
        }
Ejemplo n.º 3
0
        public void CopyFromVM(string remoteFilePathGlob, string localFilePath, bool recursive, bool force)
        {
            CheckProfileCanResolveSlave();

            Log(string.Format("Copying from remote path '{0}' to local path '{1}'{2}{3}.", localFilePath, remoteFilePathGlob,
                              recursive ? " recursively" : "",
                              force ? " force overwrite" : ""));

            var client = GetSlaveClient();

            EnumerateRequest enumerateRequest = new EnumerateRequest()
            {
                PathGlob  = remoteFilePathGlob,
                Recursive = recursive
            };
            EnumerateResponse enumerateResponse = client.Enumerate(enumerateRequest);

            if (enumerateResponse.Items.Count == 0 && !FileUtil.HasWildcard(remoteFilePathGlob))
            {
                throw new OperationFailedException()
                      {
                          Why = string.Format("Remote file{0} not found '{1}'.", recursive ? " or directory" : "", remoteFilePathGlob)
                      }
            }
            ;

            foreach (EnumerateItem item in enumerateResponse.Items)
            {
                string path = Path.Combine(localFilePath, item.RelativePath);

                if (item.Kind == EnumerateItemKind.DIRECTORY)
                {
                    if (!Directory.Exists(path))
                    {
                        Log(string.Format("Creating directory '{0}'.", item.RelativePath));
                        Directory.CreateDirectory(path);
                    }
                }
                else
                {
                    Log(string.Format("Copying '{0}'.", item.RelativePath));

                    ReadFileRequest request = new ReadFileRequest()
                    {
                        Path = item.FullPath
                    };
                    ReadFileResponse response = client.ReadFile(request);
                    if (!force && File.Exists(path))
                    {
                        throw new OperationFailedException()
                              {
                                  Why = string.Format("Local file already exists '{0}'.", path)
                              }
                    }
                    ;
                    File.WriteAllBytes(path, response.Contents);
                }
            }
        }
Ejemplo n.º 4
0
        public async Task EnumerateAsync_ReturnsSuccess()
        {
            // Act
            EnumerateResponse actual = await _subdomainService.EnumerateAsync("yahoo.com");

            // Assert
            Assert.NotNull(actual);
            Assert.True(actual.Success);
        }
Ejemplo n.º 5
0
        public async Task EnumerateAsync_ReturnsSuccessAndArSubdomainAsFirstOrDefault()
        {
            // Act
            EnumerateResponse actual = await _subdomainService.EnumerateAsync("yahoo.com");

            // Assert
            Assert.NotNull(actual);
            Assert.True(actual.Success);
            Assert.Equal("ar.yahoo.com", actual.Subdomains.FirstOrDefault());
        }
        private EnumerateResponse Enumerate(string filter, int pageSize, IEnumerable <string> attributesToReturn, IEnumerable <SortingAttribute> sortingAttributes, CultureInfo locale)
        {
            if (pageSize < 0)
            {
                pageSize = DefaultPageSize;
            }

            using (Message requestMessage = MessageComposer.CreateEnumerateMessage(filter, pageSize, attributesToReturn, sortingAttributes, locale))
            {
                using (Message responseMessage = this.Invoke((c) => c.Enumerate(requestMessage)))
                {
                    responseMessage.ThrowOnFault();

                    EnumerateResponse response = responseMessage.DeserializeMessageWithPayload <EnumerateResponse>();
                    return(response);
                }
            }
        }
        public async Task <IActionResult> EnumerateAsync(string domain_name)
        {
            _logger?.LogDebug("'{0}' has been invoked.", nameof(EnumerateAsync));

            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            try
            {
                EnumerateResponse response = await _subdomainService.EnumerateAsync(domain_name);

                return(Ok(response));
            }
            catch (Exception ex)
            {
                _logger?.LogCritical("There was an error on '{0}' invocation: {1}", nameof(EnumerateAsync), ex);

                return(StatusCode(StatusCodes.Status500InternalServerError, new IpAddressesResponse {
                    ErrorMessage = ex.Message
                }));
            }
        }
Ejemplo n.º 8
0
        public override EnumerateResponse Enumerate(EnumerateRequest request)
        {
            log.InfoFormat("Enumerate:\n  Path: {0}\n  Recursive: {1}", request.PathGlob, request.Recursive);

            EnumerateResponse response = new EnumerateResponse();

            response.Items = new List <EnumerateItem>();

            FileUtil.TraverseFiles(request.PathGlob, request.Recursive,
                                   (file, relativePath) => response.Items.Add(new EnumerateItem()
            {
                Kind         = EnumerateItemKind.FILE,
                RelativePath = relativePath,
                FullPath     = file.FullName
            }),
                                   (directory, relativePath) => response.Items.Add(new EnumerateItem()
            {
                Kind         = EnumerateItemKind.DIRECTORY,
                RelativePath = relativePath,
                FullPath     = directory.FullName
            }));

            return(response);
        }
Ejemplo n.º 9
0
        private void EnumerateInternalWithADWS(string distinguishedName, string filter, string[] properties, string scope, ReceiveItems callback)
        {
            bool          nTSecurityDescriptor = false;
            List <string> listproperties       = new List <string>();

            Enumerate enumerate = new Enumerate();

            enumerate.Filter                      = new FilterType();
            enumerate.Filter.LdapQuery            = new LdapQuery();
            enumerate.Filter.LdapQuery.BaseObject = distinguishedName;
            Trace.WriteLine("LdapQuery.BaseObject=" + enumerate.Filter.LdapQuery.BaseObject);

            enumerate.Filter.LdapQuery.Scope  = scope;
            enumerate.Filter.LdapQuery.Filter = filter;
            Trace.WriteLine("LdapQuery.Filter=" + enumerate.Filter.LdapQuery.Filter);

            if (properties != null)
            {
                listproperties.AddRange(properties);
                enumerate.Selection = new Selection();

                enumerate.Selection.SelectionProperty = BuildProperties(listproperties);
            }
            EnumerateResponse enumerateResponse = null;

            Trace.WriteLine("[" + DateTime.Now.ToLongTimeString() + "] Running enumeration");
            bool hasNewProperties = true;

            while (hasNewProperties)
            {
                try
                {
                    enumerateResponse = Search.Enumerate(enumerate);
                    hasNewProperties  = false;
                }
                catch (FaultException <schemas.microsoft.com._2008._1.ActiveDirectory.EnumerateFault> ex)
                {
                    // handle the case where the property is not available in the schema.
                    // an exception is thrown
                    // remove the litigious property and resume the query
                    Trace.WriteLine("The server doesn't support the property: " + ex.Detail.InvalidProperty);
                    int    postns   = ex.Detail.InvalidProperty.IndexOf(':');
                    string property = ex.Detail.InvalidProperty;
                    if (postns > 0)
                    {
                        property = ex.Detail.InvalidProperty.Substring(postns + 1);
                    }
                    if (!listproperties.Remove(property))
                    {
                        throw;
                    }
                    if (listproperties.Count == 0)
                    {
                        return;
                    }
                    enumerate.Selection.SelectionProperty = BuildProperties(listproperties);
                }
            }
            Trace.WriteLine("[" + DateTime.Now.ToLongTimeString() + "]Enumeration successful");
            Trace.WriteLine("Enumeration expires at " + enumerateResponse.Expires);
            Trace.WriteLine("Enumeration context is " + String.Join(",", enumerateResponse.EnumerationContext.Text));

            // prepare the flag for the ntsecuritydescriptor
            foreach (string property in listproperties)
            {
                if (String.Compare("nTSecurityDescriptor", property, true) == 0)
                {
                    nTSecurityDescriptor = true;
                }
            }

            // do not fail if the expiration cannot be parsed
            DateTime expiration = DateTime.Now.AddMinutes(30);

            DateTime.TryParse(enumerateResponse.Expires, out expiration);

            bool bcontinue = true;
            int  pagenum   = 0;

            while (bcontinue)
            {
                if (expiration.AddMinutes(-5) < DateTime.Now)
                {
                    Trace.WriteLine("[" + DateTime.Now.ToLongTimeString() + "]Renewing the enumeration (expiration)");
                    Renew renew = new Renew();
                    renew.EnumerationContext = enumerateResponse.EnumerationContext;
                    renew.Expires            = DateTime.Now.AddMinutes(20).ToString("O");
                    RenewResponse renewresponse = Search.Renew(renew);
                    Trace.WriteLine("New expiration at " + renewresponse.Expires);
                    DateTime.TryParse(renewresponse.Expires, out expiration);
                    Trace.WriteLine("New enumeration context " + String.Join(",", renewresponse.EnumerationContext.Text));
                    enumerateResponse.EnumerationContext = renewresponse.EnumerationContext;
                }
                Trace.WriteLine("[" + DateTime.Now.ToLongTimeString() + "]Getting Enumerate page " + pagenum);
                Pull pull = new Pull();
                pull.EnumerationContext = enumerateResponse.EnumerationContext;
                pull.MaxElements        = "500";
                if (nTSecurityDescriptor || DomainScope)
                {
                    List <controlsControl> controls = new List <controlsControl>();
                    if (nTSecurityDescriptor)
                    {
                        // this is the flag https://msdn.microsoft.com/en-us/library/cc223323.aspx
                        // the last byte, 0x07, is OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION
                        controlsControl control = new controlsControl();
                        controls.Add(control);
                        control.controlValue = Convert.ToBase64String(new byte[] { 0x30, 0x84, 0x00, 0x00, 0x00, 0x03, 0x02, 0x01, 0x07 });
                        control.criticality  = true;
                        control.type         = "1.2.840.113556.1.4.801";
                    }
                    if (DomainScope)
                    {
                        // this is the flag https://msdn.microsoft.com/en-us/library/cc223323.aspx
                        // the last byte, 0x07, is OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION
                        controlsControl control = new controlsControl();
                        controls.Add(control);
                        control.criticality = true;
                        control.type        = "1.2.840.113556.1.4.1339";
                    }
                    pull.controls = controls.ToArray();
                }

                PullResponse pullResponse = null;
                try
                {
                    pullResponse = Search.Pull(pull);
                }
                catch (FaultException ex)
                {
                    Trace.WriteLine("[" + DateTime.Now.ToLongTimeString() + "]Pull unsuccessful");
                    Trace.WriteLine("Fault Exception: " + ex.Message);
                    Trace.WriteLine("Reason: " + ex.Reason);
                    var stringWriter  = new StringWriter();
                    var xmlTextWriter = new XmlTextWriter(stringWriter);
                    var messageFault  = ex.CreateMessageFault();
                    messageFault.WriteTo(xmlTextWriter, EnvelopeVersion.Soap12);
                    var stringValue = Convert.ToString(stringWriter);
                    Trace.WriteLine("Detail:");
                    Trace.WriteLine(stringValue);
                    throw new PingCastleException("An ADWS exception occured (fault:" + ex.Message + ";reason:" + ex.Reason + ").\r\nADWS is a faster protocol than LDAP but bound to a default 30 minutes limitation. If this error persists, we recommand to force the LDAP protocol. Run PingCastle with the following switches: --protocol LDAPOnly --interactive");
                }
                Trace.WriteLine("[" + DateTime.Now.ToLongTimeString() + "]Pull successful");
                if (pullResponse.EndOfSequence != null)
                {
                    bcontinue = false;
                }
                callback(pullResponse.Items);
                pagenum++;
            }
            Trace.WriteLine("[" + DateTime.Now.ToLongTimeString() + "]Releasing the enumeration context");
            Release relase = new Release();

            relase.EnumerationContext = enumerateResponse.EnumerationContext;
            Search.Release(relase);
        }
Ejemplo n.º 10
0
        public override EnumerateResponse Enumerate(EnumerateRequest request)
        {
            log.InfoFormat("Enumerate:\n  Path: {0}\n  Recursive: {1}", request.PathGlob, request.Recursive);

            EnumerateResponse response = new EnumerateResponse();
            response.Items = new List<EnumerateItem>();

            FileUtil.TraverseFiles(request.PathGlob, request.Recursive,
                (file, relativePath) => response.Items.Add(new EnumerateItem()
                {
                    Kind = EnumerateItemKind.FILE,
                    RelativePath = relativePath,
                    FullPath = file.FullName
                }),
                (directory, relativePath) => response.Items.Add(new EnumerateItem()
                {
                    Kind = EnumerateItemKind.DIRECTORY,
                    RelativePath = relativePath,
                    FullPath = directory.FullName
                }));

            return response;
        }