You can paginate the results using the MaxItems and Marker parameters.
MaxItems
Marker
/// <summary> /// <para>Lists the groups the specified User belongs to.</para> <para>You /// can paginate the results using the <c>MaxItems</c> and <c>Marker</c> /// parameters.</para> /// </summary> /// /// <param name="listGroupsForUserRequest">Container for the necessary /// parameters to execute the ListGroupsForUser service method on /// AmazonIdentityManagementService.</param> /// /// <returns>The response from the ListGroupsForUser service method, as /// returned by AmazonIdentityManagementService.</returns> /// /// <exception cref="NoSuchEntityException"/> public ListGroupsForUserResponse ListGroupsForUser(ListGroupsForUserRequest listGroupsForUserRequest) { IRequest<ListGroupsForUserRequest> request = new ListGroupsForUserRequestMarshaller().Marshall(listGroupsForUserRequest); ListGroupsForUserResponse response = Invoke<ListGroupsForUserRequest, ListGroupsForUserResponse> (request, this.signer, ListGroupsForUserResponseUnmarshaller.GetInstance()); return response; }
/// <summary> /// Paginator for ListGroupsForUser operation ///</summary> public IListGroupsForUserPaginator ListGroupsForUser(ListGroupsForUserRequest request) { return(new ListGroupsForUserPaginator(this.client, request)); }
/// <summary> /// Initiates the asynchronous execution of the ListGroupsForUser operation. /// <seealso cref="Amazon.IdentityManagement.IAmazonIdentityManagementService.ListGroupsForUser"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListGroupsForUser operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public async Task<ListGroupsForUserResponse> ListGroupsForUserAsync(ListGroupsForUserRequest request, CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListGroupsForUserRequestMarshaller(); var unmarshaller = ListGroupsForUserResponseUnmarshaller.GetInstance(); var response = await Invoke<IRequest, ListGroupsForUserRequest, ListGroupsForUserResponse>(request, marshaller, unmarshaller, signer, cancellationToken) .ConfigureAwait(continueOnCapturedContext: false); return response; }
/// <summary> /// Initiates the asynchronous execution of the ListGroupsForUser operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListGroupsForUser operation on AmazonIdentityManagementServiceClient.</param> /// <param name="callback">An Action delegate that is invoked when the operation completes.</param> /// <param name="options">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> public void ListGroupsForUserAsync(ListGroupsForUserRequest request, AmazonServiceCallback<ListGroupsForUserRequest, ListGroupsForUserResponse> callback, AsyncOptions options = null) { options = options == null?new AsyncOptions():options; var marshaller = new ListGroupsForUserRequestMarshaller(); var unmarshaller = ListGroupsForUserResponseUnmarshaller.Instance; Action<AmazonWebServiceRequest, AmazonWebServiceResponse, Exception, AsyncOptions> callbackHelper = null; if(callback !=null ) callbackHelper = (AmazonWebServiceRequest req, AmazonWebServiceResponse res, Exception ex, AsyncOptions ao) => { AmazonServiceResult<ListGroupsForUserRequest,ListGroupsForUserResponse> responseObject = new AmazonServiceResult<ListGroupsForUserRequest,ListGroupsForUserResponse>((ListGroupsForUserRequest)req, (ListGroupsForUserResponse)res, ex , ao.State); callback(responseObject); }; BeginInvoke<ListGroupsForUserRequest>(request, marshaller, unmarshaller, options, callbackHelper); }
internal ListGroupsForUserResponse ListGroupsForUser(ListGroupsForUserRequest request) { var marshaller = new ListGroupsForUserRequestMarshaller(); var unmarshaller = ListGroupsForUserResponseUnmarshaller.Instance; return Invoke<ListGroupsForUserRequest,ListGroupsForUserResponse>(request, marshaller, unmarshaller); }
}//EndIamUserScan /// <summary> /// Given a profile and user, collect additional information. /// </summary> /// <param name="aprofile">An AWS Profile name stored in Windows Credential Store</param> /// <param name="auser">The Name of a User</param> /// <returns>Dictionary containing keys for each type of data[AccessKeys], [Groups], [Policies]</returns> public Dictionary<string, string> GetUserDetails(string aprofile, string username) { var credential = new Amazon.Runtime.StoredProfileAWSCredentials(aprofile); var iam = new AmazonIdentityManagementServiceClient(credential); Dictionary<string, string> ToReturn = new Dictionary<string, string>(); string policylist = ""; string aklist = ""; string groups = ""; try { ListAccessKeysRequest LAKREQ = new ListAccessKeysRequest(); LAKREQ.UserName = username; var LAKRES = iam.ListAccessKeys(LAKREQ); foreach (var blivet in LAKRES.AccessKeyMetadata) { if (aklist.Length > 1) aklist += "\n"; aklist += blivet.AccessKeyId + " : " + blivet.Status; } } catch { aklist = ""; } try { ListAttachedUserPoliciesRequest LAUPREQ = new ListAttachedUserPoliciesRequest(); LAUPREQ.UserName = username; var LAUPRES = iam.ListAttachedUserPolicies(LAUPREQ); foreach (var apol in LAUPRES.AttachedPolicies) { if (policylist.Length > 1) policylist += "\n"; policylist += apol.PolicyName; } } catch { policylist = ""; } try { var groopsreq = new ListGroupsForUserRequest(); groopsreq.UserName = username; var LG = iam.ListGroupsForUser(groopsreq); foreach (var agroup in LG.Groups) { if (groups.Length > 1) groups += "\n"; groups += agroup.GroupName; } } catch { groups = ""; } ToReturn.Add("Groups", groups); ToReturn.Add("Policies", policylist); ToReturn.Add("AccessKeys", aklist); return ToReturn; }
internal ListGroupsForUserResponse ListGroupsForUser(ListGroupsForUserRequest request) { var task = ListGroupsForUserAsync(request); try { return task.Result; } catch(AggregateException e) { ExceptionDispatchInfo.Capture(e.InnerException).Throw(); return null; } }
IAsyncResult invokeListGroupsForUser(ListGroupsForUserRequest listGroupsForUserRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new ListGroupsForUserRequestMarshaller().Marshall(listGroupsForUserRequest); var unmarshaller = ListGroupsForUserResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; }
public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent; // create request and set iteration invariants var request = new Amazon.IdentityManagement.Model.ListGroupsForUserRequest(); if (cmdletContext.UserName != null) { request.UserName = cmdletContext.UserName; } // Initialize loop variants and commence piping System.String _nextToken = null; int? _emitLimit = null; int _retrievedSoFar = 0; if (AutoIterationHelpers.HasValue(cmdletContext.Marker)) { _nextToken = cmdletContext.Marker; } if (AutoIterationHelpers.HasValue(cmdletContext.MaxItem)) { // The service has a maximum page size of 1000. If the user has // asked for more items than page max, and there is no page size // configured, we rely on the service ignoring the set maximum // and giving us 1000 items back. If a page size is set, that will // be used to configure the pagination. // We'll make further calls to satisfy the user's request. _emitLimit = cmdletContext.MaxItem; } var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.Marker)); var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); do { request.Marker = _nextToken; if (_emitLimit.HasValue) { int correctPageSize = AutoIterationHelpers.Min(1000, _emitLimit.Value); request.MaxItems = AutoIterationHelpers.ConvertEmitLimitToInt32(correctPageSize); } CmdletOutput output; try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; if (!useParameterSelect) { pipelineOutput = cmdletContext.Select(response, this); } output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; int _receivedThisCall = response.Groups.Count; _nextToken = response.Marker; _retrievedSoFar += _receivedThisCall; if (_emitLimit.HasValue) { _emitLimit -= _receivedThisCall; } } catch (Exception e) { if (_retrievedSoFar == 0 || !_emitLimit.HasValue) { output = new CmdletOutput { ErrorResponse = e }; } else { break; } } ProcessOutput(output); } while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken) && (!_emitLimit.HasValue || _emitLimit.Value >= 1)); if (useParameterSelect) { WriteObject(cmdletContext.Select(null, this)); } return(null); }
private Amazon.IdentityManagement.Model.ListGroupsForUserResponse CallAWSServiceOperation(IAmazonIdentityManagementService client, Amazon.IdentityManagement.Model.ListGroupsForUserRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Identity and Access Management", "ListGroupsForUser"); try { #if DESKTOP return(client.ListGroupsForUser(request)); #elif CORECLR return(client.ListGroupsForUserAsync(request).GetAwaiter().GetResult()); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } }
public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent; #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute // create request and set iteration invariants var request = new Amazon.IdentityManagement.Model.ListGroupsForUserRequest(); if (cmdletContext.MaxItem != null) { request.MaxItems = AutoIterationHelpers.ConvertEmitLimitToServiceTypeInt32(cmdletContext.MaxItem.Value); } if (cmdletContext.UserName != null) { request.UserName = cmdletContext.UserName; } // Initialize loop variant and commence piping var _nextToken = cmdletContext.Marker; var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.Marker)); var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); do { request.Marker = _nextToken; CmdletOutput output; try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; if (!useParameterSelect) { pipelineOutput = cmdletContext.Select(response, this); } output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; _nextToken = response.Marker; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } ProcessOutput(output); } while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken)); if (useParameterSelect) { WriteObject(cmdletContext.Select(null, this)); } return(null); }
IAsyncResult invokeListGroupsForUser(ListGroupsForUserRequest request, AsyncCallback callback, object state, bool synchronized) { var marshaller = new ListGroupsForUserRequestMarshaller(); var unmarshaller = ListGroupsForUserResponseUnmarshaller.Instance; return Invoke(request, callback, state, synchronized, marshaller, unmarshaller, signer); }
internal ListGroupsForUserPaginator(IAmazonIdentityManagementService client, ListGroupsForUserRequest request) { this._client = client; this._request = request; }
/// <summary> /// Initiates the asynchronous execution of the ListGroupsForUser operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListGroupsForUser operation on AmazonIdentityManagementServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListGroupsForUser /// operation.</returns> public IAsyncResult BeginListGroupsForUser(ListGroupsForUserRequest request, AsyncCallback callback, object state) { var marshaller = new ListGroupsForUserRequestMarshaller(); var unmarshaller = ListGroupsForUserResponseUnmarshaller.Instance; return BeginInvoke<ListGroupsForUserRequest>(request, marshaller, unmarshaller, callback, state); }
/// <summary> /// <para>Lists the groups the specified user belongs to.</para> <para>You can paginate the results using the <c>MaxItems</c> and <c>Marker</c> /// parameters.</para> /// </summary> /// /// <param name="listGroupsForUserRequest">Container for the necessary parameters to execute the ListGroupsForUser service method on /// AmazonIdentityManagementService.</param> /// /// <returns>The response from the ListGroupsForUser service method, as returned by AmazonIdentityManagementService.</returns> /// /// <exception cref="T:Amazon.IdentityManagement.Model.NoSuchEntityException" /> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> public Task<ListGroupsForUserResponse> ListGroupsForUserAsync(ListGroupsForUserRequest listGroupsForUserRequest, CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListGroupsForUserRequestMarshaller(); var unmarshaller = ListGroupsForUserResponseUnmarshaller.GetInstance(); return Invoke<IRequest, ListGroupsForUserRequest, ListGroupsForUserResponse>(listGroupsForUserRequest, marshaller, unmarshaller, signer, cancellationToken); }
/// <summary> /// <para>Lists the groups the specified user belongs to.</para> <para>You can paginate the results using the <c>MaxItems</c> and <c>Marker</c> /// parameters.</para> /// </summary> /// /// <param name="listGroupsForUserRequest">Container for the necessary parameters to execute the ListGroupsForUser service method on /// AmazonIdentityManagementService.</param> /// /// <returns>The response from the ListGroupsForUser service method, as returned by AmazonIdentityManagementService.</returns> /// /// <exception cref="NoSuchEntityException"/> public ListGroupsForUserResponse ListGroupsForUser(ListGroupsForUserRequest listGroupsForUserRequest) { IAsyncResult asyncResult = invokeListGroupsForUser(listGroupsForUserRequest, null, null, true); return EndListGroupsForUser(asyncResult); }
private async Task<Resource[]> QueryReference( IQueryParameters parameters, string correlationIdentifier) { if (null == parameters) { throw new ArgumentNullException(AmazonWebServicesProvider.ArgumentNameParameters); } if (string.IsNullOrWhiteSpace(correlationIdentifier)) { throw new ArgumentNullException(AmazonWebServicesProvider.ArgumentNameCorrelationIdentifier); } if (null == parameters.RequestedAttributePaths || !parameters.RequestedAttributePaths.Any()) { throw new NotSupportedException(ProvisioningAgentResources.ExceptionUnsupportedQuery); } string selectedAttribute = parameters.RequestedAttributePaths.SingleOrDefault(); if (string.IsNullOrWhiteSpace(selectedAttribute)) { throw new NotSupportedException(ProvisioningAgentResources.ExceptionUnsupportedQuery); } ProvisioningAgentMonitor.Instance.Inform(selectedAttribute, true, correlationIdentifier); if ( !string.Equals( selectedAttribute, Microsoft.SystemForCrossDomainIdentityManagement.AttributeNames.Identifier, StringComparison.OrdinalIgnoreCase) ) { throw new NotSupportedException(ProvisioningAgentResources.ExceptionUnsupportedQuery); } if (null == parameters.AlternateFilters) { throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidParameters); } if (string.IsNullOrWhiteSpace(parameters.SchemaIdentifier)) { throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidParameters); } string informationAlternateFilterCount = parameters.AlternateFilters.Count.ToString(CultureInfo.InvariantCulture); ProvisioningAgentMonitor.Instance.Inform(informationAlternateFilterCount, true, correlationIdentifier); if (parameters.AlternateFilters.Count != 1) { string exceptionMessage = string.Format( CultureInfo.InvariantCulture, ProvisioningAgentResources.ExceptionFilterCountTemplate, 1, parameters.AlternateFilters.Count); throw new NotSupportedException(exceptionMessage); } AmazonWebServicesProvider.Validate(parameters); IFilter filterPrimary = parameters.AlternateFilters.Single(); if (null == filterPrimary.AdditionalFilter) { throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidParameters); } IFilter filterAdditional = filterPrimary.AdditionalFilter; if (filterAdditional.AdditionalFilter != null) { throw new NotSupportedException(ProvisioningAgentResources.ExceptionUnsupportedQuery); } IReadOnlyCollection<IFilter> filters = new IFilter[] { filterPrimary, filterAdditional }; IFilter filterIdentifier = filters .SingleOrDefault( (IFilter item) => string.Equals( AttributeNames.Identifier, item.AttributePath, StringComparison.OrdinalIgnoreCase)); if (null == filterIdentifier) { throw new NotSupportedException(ProvisioningAgentResources.ExceptionUnsupportedQuery); } IFilter filterReference = filters .SingleOrDefault( (IFilter item) => string.Equals( AttributeNames.Members, item.AttributePath, StringComparison.OrdinalIgnoreCase)); if (null == filterReference) { return new Resource[0]; } IAmazonIdentityManagementService proxy = null; try { proxy = AWSClientFactory.CreateAmazonIdentityManagementServiceClient(this.credentials); Amazon.IdentityManagement.Model.User member = await this.RetrieveUser(filterReference.ComparisonValue, proxy); if (member != null) { return new Resource[0]; } ListGroupsForUserRequest request = new ListGroupsForUserRequest() { MaxItems = AmazonWebServicesProvider.SizeListPage, UserName = member.UserName }; while (true) { ListGroupsForUserResponse response = await proxy.ListGroupsForUserAsync(request); if (null == response.Groups || !response.Groups.Any()) { return null; } Group group = response .Groups .SingleOrDefault( (Group item) => string.Equals(item.GroupName, filterReference.ComparisonValue, StringComparison.OrdinalIgnoreCase)); if (group != null) { WindowsAzureActiveDirectoryGroup groupResource = new WindowsAzureActiveDirectoryGroup() { Identifier = group.GroupId, ExternalIdentifier = group.GroupName }; Resource[] results = new Resource[] { groupResource }; return results; } if (string.IsNullOrWhiteSpace(response.Marker)) { return null; } if (string.Equals(request.Marker, response.Marker, StringComparison.OrdinalIgnoreCase)) { return null; } request.Marker = response.Marker; } } finally { if (proxy != null) { proxy.Dispose(); proxy = null; } } }
/// <summary> /// Initiates the asynchronous execution of the ListGroupsForUser operation. /// <seealso cref="Amazon.IdentityManagement.AmazonIdentityManagementService.ListGroupsForUser"/> /// </summary> /// /// <param name="listGroupsForUserRequest">Container for the necessary parameters to execute the ListGroupsForUser operation on /// AmazonIdentityManagementService.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListGroupsForUser /// operation.</returns> public IAsyncResult BeginListGroupsForUser(ListGroupsForUserRequest listGroupsForUserRequest, AsyncCallback callback, object state) { return invokeListGroupsForUser(listGroupsForUserRequest, callback, state, false); }
/// <summary> /// <para>Lists the groups the specified user belongs to.</para> <para>You can paginate the results using the <c>MaxItems</c> and <c>Marker</c> /// parameters.</para> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListGroupsForUser service method on /// AmazonIdentityManagementService.</param> /// /// <returns>The response from the ListGroupsForUser service method, as returned by AmazonIdentityManagementService.</returns> /// /// <exception cref="T:Amazon.IdentityManagement.Model.NoSuchEntityException" /> public ListGroupsForUserResponse ListGroupsForUser(ListGroupsForUserRequest request) { var task = ListGroupsForUserAsync(request); try { return task.Result; } catch(AggregateException e) { throw e.InnerException; } }
/// <summary> /// Initiates the asynchronous execution of the ListGroupsForUser operation. /// <seealso cref="Amazon.IdentityManagement.IAmazonIdentityManagementService"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListGroupsForUser operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ListGroupsForUserResponse> ListGroupsForUserAsync(ListGroupsForUserRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListGroupsForUserRequestMarshaller(); var unmarshaller = ListGroupsForUserResponseUnmarshaller.Instance; return InvokeAsync<ListGroupsForUserRequest,ListGroupsForUserResponse>(request, marshaller, unmarshaller, cancellationToken); }
public Dictionary<string, DataTable> ScanProfile(ScanRequest Request) { Dictionary<string, DataTable> ScanResults = new Dictionary<string, DataTable>(); DataTable UserDetailsTable = GetUsersDetailsTable(); DataTable EC2DetailsTable = GetEC2DetailsTable(); DataTable S3DetailsTable = GetS3DetailsTable(); string accountid = ""; Amazon.Runtime.AWSCredentials credential; var aprofile = Request.Profile; var regions2process = Request.Regions; var SubmitResults = Request.ResultQueue; try { credential = new Amazon.Runtime.StoredProfileAWSCredentials(aprofile); //Try to get the AccountID ID// #region UserDetails var iam = new AmazonIdentityManagementServiceClient(credential); var myUserList = iam.ListUsers().Users; try { accountid = myUserList[0].Arn.Split(':')[4];//Get the ARN and extract the AccountID ID accountid = "ID: " + accountid;// Prefix added because Excel exsucks. } catch { accountid = "?"; } try // Send command to AWS to generate a Credential Report { var createcredreport = iam.GenerateCredentialReport(); } catch (Exception) { throw; } bool needreport = true; Amazon.IdentityManagement.Model.GetCredentialReportResponse credreport = new GetCredentialReportResponse(); DateTime getreportstart = DateTime.Now; DateTime getreportfinish = DateTime.Now; while (needreport) { try { credreport = iam.GetCredentialReport(); needreport = false; getreportfinish = DateTime.Now; var dif = getreportstart - getreportfinish; //Just a check on how long it takes. //Extract data from CSV Stream into DataTable var streambert = credreport.Content; streambert.Position = 0; StreamReader sr = new StreamReader(streambert); string myStringRow = sr.ReadLine(); if (myStringRow != null) myStringRow = sr.ReadLine();//Dump the header line while (myStringRow != null) { var arow = myStringRow.Split(",".ToCharArray()[0]); var newrow = new object[UserDetailsTable.Columns.Count]; newrow[0] = accountid; newrow[1] = aprofile; newrow[2] = ""; //UserID not in report. pull it later. newrow[3] = arow[0]; newrow[4] = arow[1]; newrow[5] = arow[2]; newrow[6] = arow[3]; newrow[7] = arow[4]; newrow[8] = arow[5]; newrow[9] = arow[6]; newrow[10] = arow[7]; newrow[11] = arow[8]; newrow[12] = arow[9]; newrow[13] = arow[10]; newrow[14] = arow[11]; newrow[15] = arow[12]; newrow[16] = arow[13]; newrow[17] = arow[14]; newrow[18] = arow[15]; newrow[19] = arow[16]; newrow[20] = arow[17]; newrow[21] = arow[18]; newrow[22] = arow[19]; newrow[23] = arow[20]; newrow[24] = arow[21]; RawUsers.Rows.Add(newrow); UserDetailsTable.Rows.Add(newrow); myStringRow = sr.ReadLine(); } sr.Close(); sr.Dispose(); } catch (Exception ex) { string test = ""; //Deal with this later if necessary. } } foreach (var auser in myUserList)//Fill in the userID. Why? because it exists. { string auserid = auser.UserId; string arn = auser.Arn; string username = auser.UserName; string policylist = ""; string aklist = ""; string groups = ""; ListAccessKeysRequest LAKREQ = new ListAccessKeysRequest(); LAKREQ.UserName = username; ListAccessKeysResult LAKRES = iam.ListAccessKeys(LAKREQ); foreach (var blivet in LAKRES.AccessKeyMetadata) { if (aklist.Length > 1) aklist += "\n"; aklist += blivet.AccessKeyId + " : " + blivet.Status; } ListAttachedUserPoliciesRequest LAUPREQ = new ListAttachedUserPoliciesRequest(); LAUPREQ.UserName = username; ListAttachedUserPoliciesResult LAUPRES = iam.ListAttachedUserPolicies(LAUPREQ); foreach (var apol in LAUPRES.AttachedPolicies) { if (policylist.Length > 1) policylist += "\n"; policylist += apol.PolicyName; } //Need to get policy and group info outta user var groopsreq = new ListGroupsForUserRequest(); groopsreq.UserName = username; ListGroupsForUserResult LG = iam.ListGroupsForUser(groopsreq); foreach (var agroup in LG.Groups) { if (groups.Length > 1) groups += "\n"; groups += agroup.GroupName; } foreach (DataRow myrow in UserDetailsTable.Rows) { if (myrow["ARN"].Equals(arn)) { myrow["UserID"] = auserid; myrow["User-Policies"] = policylist; myrow["Access-Keys"] = aklist; myrow["Groups"] = groups; } } } #endregion #region S3Details try { AmazonS3Client S3Client = new AmazonS3Client(credential,Amazon.RegionEndpoint.USEast1); ListBucketsResponse response = S3Client.ListBuckets(); foreach (S3Bucket abucket in response.Buckets) { DataRow abucketrow = GetS3DetailsTable().NewRow(); var name = abucket.BucketName; GetBucketLocationRequest gbr = new GetBucketLocationRequest(); gbr.BucketName=name; GetBucketLocationResponse location = S3Client.GetBucketLocation(gbr); var region = location.Location.Value; if (region.Equals(""))region="us-east-1"; var pointy = RegionEndpoint.GetBySystemName(region); //Build a config that references the buckets region. AmazonS3Config S3C = new AmazonS3Config(); S3C.RegionEndpoint=pointy; AmazonS3Client BS3Client = new AmazonS3Client(credential, S3C); var createddate = abucket.CreationDate; string owner = ""; string grants = ""; string tags = ""; string lastaccess = ""; string defaultpage = ""; string website = ""; //Now start pulling der einen data. GetACLRequest GACR = new GetACLRequest(); GACR.BucketName = name; var ACL = BS3Client.GetACL(GACR); var grantlist = ACL.AccessControlList; owner = grantlist.Owner.DisplayName; foreach (var agrant in grantlist.Grants) { if (grants.Length > 1) grants += "\n"; var gName = agrant.Grantee.DisplayName; var gType = agrant.Grantee.Type.Value; var aMail = agrant.Grantee.EmailAddress; if (gType.Equals("Group")) { grants += gType + " - " + agrant.Grantee.URI + " - " + agrant.Permission + " - " + aMail ; } else { grants += gName + " - "+ agrant.Permission + " - " + aMail; } } GetObjectMetadataRequest request = new GetObjectMetadataRequest(); request.BucketName = name; GetObjectMetadataResponse MDresponse = BS3Client.GetObjectMetadata(request); lastaccess = MDresponse.LastModified.ToString(); //defaultpage = MDresponse.WebsiteRedirectLocation; GetBucketWebsiteRequest GBWReq = new GetBucketWebsiteRequest(); GBWReq.BucketName = name; GetBucketWebsiteResponse GBWRes = BS3Client.GetBucketWebsite(GBWReq); defaultpage = GBWRes.WebsiteConfiguration.IndexDocumentSuffix; if (defaultpage != null) { website = @"http://" + name + @".s3-website-" + region + @".amazonaws.com/" + defaultpage; } //Amazon.S3.Model.req abucketrow["AccountID"] = accountid; abucketrow["Profile"] = aprofile; abucketrow["Bucket"] = name; abucketrow["Region"] = region; abucketrow["CreationDate"] = createddate.ToString(); abucketrow["LastAccess"] = lastaccess; abucketrow["Owner"] = owner; abucketrow["Grants"] = grants; abucketrow["WebsiteHosting"] = website; abucketrow["Logging"] = "X"; abucketrow["Events"] = "X"; abucketrow["Versioning"] = "X"; abucketrow["LifeCycle"] = "X"; abucketrow["Replication"] = "X"; abucketrow["Tags"] = "X"; abucketrow["RequesterPays"] = "X"; S3DetailsTable.Rows.Add(abucketrow.ItemArray); } } catch(Exception ex) { System.Windows.Forms.MessageBox.Show("S3 Failed!\n"+ex); } #endregion #region GetEC2Region ////////////////////////////////////////////////////////// //Foreach aregion foreach (var aregion in regions2process) { //Skip GovCloud and Beijing. They require special handling and I dont need em. if (aregion == Amazon.RegionEndpoint.USGovCloudWest1) continue; if (aregion == Amazon.RegionEndpoint.CNNorth1) continue; var region = aregion; regioncounter++; //Try to get scheduled events on my Profile/aregion var ec2 = AWSClientFactory.CreateAmazonEC2Client(credential, region); var request = new DescribeInstanceStatusRequest(); request.IncludeAllInstances = true; Dispatcher.Invoke(doupdatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, regioncounter }); var instatresponse = ec2.DescribeInstanceStatus(request); var indatarequest = new DescribeInstancesRequest(); foreach (var instat in instatresponse.InstanceStatuses) { indatarequest.InstanceIds.Add(instat.InstanceId); } DescribeInstancesResult DescResult = ec2.DescribeInstances(indatarequest); int count = instatresponse.InstanceStatuses.Count(); foreach (var instat in instatresponse.InstanceStatuses) { //Collect the datases string instanceid = instat.InstanceId; string instancename = ""; ProcessingLabel.Content = "Scanning -> Profile:" + aprofile + " Region: " + region + " Instance: " + instanceid; Dispatcher.Invoke(doupdatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, regioncounter }); var status = instat.Status.Status; string AZ = instat.AvailabilityZone; var istate = instat.InstanceState.Name; string profile = aprofile; string myregion = region.ToString(); int eventnumber = instat.Events.Count(); string eventlist = ""; var urtburgle = DescResult.Reservations; string tags = ""; // Holds the list of tags to print out. var loadtags = (from t in DescResult.Reservations where t.Instances[0].InstanceId.Equals(instanceid) select t.Instances[0].Tags).AsEnumerable(); Dictionary<string, string> taglist = new Dictionary<string, string>(); foreach (var rekey in loadtags) { foreach (var kvp in rekey) { taglist.Add(kvp.Key, kvp.Value); } } foreach (var atag in taglist)//Set instancename, and add value to combobox. { if (atag.Key.Equals("Name")) { instancename = atag.Value; } if (!TagFilterCombo.Items.Contains(atag.Key)) { TagFilterCombo.Items.Add(atag.Key); } if (tags.Length > 1) { tags += "\n" + atag.Key + ":" + atag.Value; } else { tags += atag.Key + ":" + atag.Value; } } if (eventnumber > 0) { foreach (var anevent in instat.Events) { eventlist += anevent.Description + "\n"; } } var platform = (from t in urtburgle where t.Instances[0].InstanceId.Equals(instanceid) select t.Instances[0].Platform).FirstOrDefault(); if (String.IsNullOrEmpty(platform)) platform = "Linux"; var Priv_IP = (from t in urtburgle where t.Instances[0].InstanceId.Equals(instanceid) select t.Instances[0].PrivateIpAddress).FirstOrDefault(); if (String.IsNullOrEmpty(Priv_IP)) Priv_IP = "?"; var publicIP = (from t in urtburgle where t.Instances[0].InstanceId.Equals(instanceid) select t.Instances[0].PublicIpAddress).FirstOrDefault(); if (String.IsNullOrEmpty(publicIP)) publicIP = ""; var publicDNS = (from t in urtburgle where t.Instances[0].InstanceId.Equals(instanceid) select t.Instances[0].PublicDnsName).FirstOrDefault(); if (String.IsNullOrEmpty(publicDNS)) publicDNS = ""; //Virtualization type (HVM, Paravirtual) var ivirtType = (from t in urtburgle where t.Instances[0].InstanceId.Equals(instanceid) select t.Instances[0].VirtualizationType).FirstOrDefault(); if (String.IsNullOrEmpty(ivirtType)) ivirtType = "?"; // InstanceType (m3/Large etc) var instancetype = (from t in urtburgle where t.Instances[0].InstanceId.Equals(instanceid) select t.Instances[0].InstanceType).FirstOrDefault(); if (String.IsNullOrEmpty(instancetype)) instancetype = "?"; var SGs = (from t in urtburgle where t.Instances[0].InstanceId.Equals(instanceid) select t.Instances[0].SecurityGroups); string sglist = ""; if (SGs.Count() > 0) { foreach (var ansg in SGs.FirstOrDefault()) { if (sglist.Length > 2) { sglist += "\n"; } sglist += ansg.GroupName; } } else { sglist = "_NONE!_"; } //Add to table if (String.IsNullOrEmpty(sglist)) sglist = "NullOrEmpty"; if (String.IsNullOrEmpty(instancename)) instancename = ""; string rabbit = accountid + profile + myregion + instancename + instanceid + AZ + status + eventnumber + eventlist + tags + Priv_IP + publicIP + publicDNS + istate + ivirtType + instancetype + sglist; if(instancename.Contains("p1-job")) { string yup = "y"; } EC2DetailsTable.Rows.Add(accountid, profile, myregion, instancename, instanceid, AZ, platform, status, eventnumber, eventlist, tags, Priv_IP, publicIP, publicDNS, istate, ivirtType, instancetype, sglist); } } #endregion ScanResults.Add("EC2", EC2DetailsTable); ScanResults.Add("Users", UserDetailsTable); ScanResults.Add("S3", S3DetailsTable); return ScanResults; } catch (Exception ex) { //If we failed to connect with creds. string error = new string(ex.ToString().TakeWhile(c => c != '\n').ToArray()); System.Windows.MessageBox.Show(error, Request.Profile.ToString() + " credentials failed to work.\n"); //Try to flag the menu item so it no longer selectable, and maybe make she red. System.Windows.Controls.MenuItem Proot = (System.Windows.Controls.MenuItem)this.MainMenu.Items[1]; foreach (System.Windows.Controls.MenuItem amenuitem in Proot.Items) { if (amenuitem.Header.ToString() == aprofile.ToString()) { amenuitem.IsCheckable = false; amenuitem.IsChecked = false; amenuitem.Background = Brushes.Red; amenuitem.ToolTip = Request.Profile.ToString() + " credentials failed to work.\n"; } } ScanResults.Add("EC2", GetEC2DetailsTable()); ScanResults.Add("Users", GetUsersDetailsTable()); ScanResults.Add("S3", GetS3DetailsTable()); return ScanResults; } }