Azure Sentinel - Log Analysis - Help - Finding all sucessful azure signs over 3 months period by location and user - azure-sentinel

I'm new to Sentinel/Work Analytics and KMQ. I have been trying to figure out a query to get all successful login by user and location from azure actvity sign in. I hope you can help me or point me to some references.
I've tried using some examples from the github and Sentinel dashboard. I can get all the failed user logins by country but not successful. I was going to use this log data for a geo blocking activity.
any help would be really appreciated, and sorry for such a beginner question.
thanks in advance

let data = SigninLogs
| extend AppDisplayName = iff(AppDisplayName == '', 'Unknown', AppDisplayName)
| where AppDisplayName in ('*') or '*' in ('*')
| where UserDisplayName in ('*') or '*' in ('*')
| extend Country = tostring(LocationDetails.countryOrRegion)
| extend City = tostring(LocationDetails.city)
| extend errorCode = Status.errorCode
| extend SigninStatus = case(errorCode == 0, "Success", errorCode == 50058, "Pending user action", errorCode == 50140, "Pending user action", errorCode == 51006, "Pending user action", errorCode == 50059, "Pending user action", errorCode == 65001, "Pending user action", errorCode == 52004, "Pending user action", errorCode == 50055, "Pending user action", errorCode == 50144, "Pending user action", errorCode == 50072, "Pending user action", errorCode == 50074, "Pending user action", errorCode == 16000, "Pending user action", errorCode == 16001, "Pending user action", errorCode == 16003, "Pending user action", errorCode == 50127, "Pending user action", errorCode == 50125, "Pending user action", errorCode == 50129, "Pending user action", errorCode == 50143, "Pending user action", errorCode == 81010, "Pending user action", errorCode == 81014, "Pending user action", errorCode == 81012, "Pending user action", "Failure")
| where SigninStatus == '*' or '*' == '*' or '*' == 'All Sign-ins'
| where details.Type == '*' or (details.Type == 'Country' and Country == details.Name) or (details.Type == 'City' and City == details.Name)
| where UserPrincipalName contains "example.com"
| where Country != "AU";
//| where SigninStatus contains "success";
data
| top 10000 by TimeGenerated desc
//| extend TimeFromNow = now() - TimeGenerated
//| extend TimeAgo = strcat(case(TimeFromNow < 2m, strcat(toint(TimeFromNow / 1m), ' seconds'), TimeFromNow < 2h, strcat(toint(TimeFromNow / 1m), ' minutes'), TimeFromNow < 2d, //strcat(toint(TimeFromNow / 1h), ' hours'), strcat(toint(TimeFromNow / 10d), ' days')), ' ago')
| project User = UserDisplayName, ['Sign-in Status'] = strcat(iff(SigninStatus == 'Success', '✔️', '❌'), ' ', SigninStatus), ['Sign-in Time'] = TimeGenerated, App = AppDisplayName, ['Error code'] = errorCode, ['Result type'] = ResultType, ['Result signature'] = ResultSignature, ['Result description'] = ResultDescription, ['Conditional access policies'] = ConditionalAccessPolicies, ['Conditional access status'] = ConditionalAccessStatus, ['Operating system'] = DeviceDetail.operatingSystem, Browser = DeviceDetail.browser, ['Country or region'] = LocationDetails.countryOrRegion, ['State'] = LocationDetails.state, ['City'] = LocationDetails.city, ['Time generated'] = TimeGenerated, Status, ['User principal name'] = UserPrincipalName, ['ClientAppUsed'] = ClientAppUsed````

Related

Adding strings from python to text file and then verify lines in while loop

I'm new to coding and still learning about Python.
I have a task where I have to upload lines from Python to a text file and then verify the lines later in the code e.g. I have to input user names and user passwords and add to the text file as [user_name, user_pass].
My problem is that when I try to verify the line one of 2 things happen. After I added a split function for the line e.g. verified_user, verified_password = line.split(", ") it runs into an error stating that I do not have enough values for the request made e.g 2 expected, 1 made. If I change the split input and it does run, the verification loop states that my inputs does not match any lines in the string.
Every thing works if I add the information to the text file only. But the moment I add via the appendix action in Python it no longer works.
this is what I have so far:
user_list = []
all_names_entered = "no"
while all_names_entered == "no":
user_name = input("Enter user name: ")
user_pass = input("Enter password: ")
user_list.append(user_name + ", " + user_pass)
while True:
all_names_entered = input("All users entered?: ")
if all_names_entered in ['yes','no']:
break
else:
print( 'please answer with yes or no' )
for items in user_list:
with open('user.txt', 'a') as file:
file.write(f"{user_name}, {user_pass}\n")
print (user_list)
file.close()
the next block reads as follow:
user_file = open("user.txt", "r+")
login = False
while login == False:
username = input("Enter user name: ")
password = input("Enter user password: ")
for line in user_file:
other = line.strip()
valid_user, valid_password = line.split(", ")
if username == valid_user and password == valid_password:
login = True
print ("You have successfully logged in")
break
else:
print("You have entered incorrect detail. Please try again")
user_file.seek(0)
user_file.close()
Firstly, indentation is important in Python.
Secondly, you're supposed to loop if user enters 'no'.
Utilize the item that's initialized in each for loop.
You initialized other but it was never consumed.
Following is code for writing into file:
user_list = []
all_names_entered = "no"
while all_names_entered == "no":
user_name = input("Enter user name: ")
user_pass = input("Enter password: ")
user_list.append(user_name + ", " + user_pass)
query_all_names_entered = True
while query_all_names_entered:
all_names_entered = input("All users entered?: ")
if all_names_entered == 'yes':
query_all_names_entered = False
break
elif all_names_entered == 'no':
query_all_names_entered = False
continue
else:
print('Please answer with yes or no')
all_names_entered = "no"
with open('user.txt', 'a') as file:
for item in user_list:
file.write(f"{item}\n")
print (user_list)
file.close()
And following is for reading file to log in:
user_file = open("user.txt", "r+")
login = False
lines = user_file.readlines()
while login == False:
username = input("Enter user name: ")
password = input("Enter user password: ")
for line in lines:
valid_user, valid_password = line.strip().split(", ")
if username == valid_user and password == valid_password:
login = True
print ("You have successfully logged in")
break
if login == False: print ("You have entered incorrect detail. Please try again")
user_file.close()

ADFS PowerShell: Scripting Web API (Add-AdfsWebApiApplication) with RuleTemplate in IssuanceTransformRules

I've defined an ADFS Application Group using the ADFS MMC. I'd like to create a script for deployment. I've successfully scripted using New-AdfsApplicationGroup and Add-AdfsNativeClientApplication. Next I'd like to script the Web API. Looking at the output of Get-AdfsWebApiApplication I see the following IssuanceTransformRules. The rule is named and references a template.
#RuleTemplate = "LdapClaims"
#RuleName = "2"
c:[Type ==
"http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname",
Issuer == "AD AUTHORITY"]
=> issue(store = "Active Directory", types = ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"), query =
";mail,sAMAccountName,userPrincipalName;{0}", param = c.Value);
I scripted this as:
Add-AdfsWebApiApplication -Name "My Web API" -AllowedClientTypes 6 -ApplicationGroupIdentifier "MyApp" -IssueOAuthRefreshTokensTo 2 -TokenLifetime 7 -Identifier {https://apphost/myapp/api/} -IssuanceTransformRules '#RuleTemplate = "LdapClaims", #RuleName = "2", c:[Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname", Issuer == "AD AUTHORITY"] => issue(store = "Active Directory", types = ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"), query = ";mail,sAMAccountName,userPrincipalName;{0}", param = c.Value);'
This results in the following error.
Parser error: 'POLICY0030: Syntax error, unexpected COMMA, expecting
one of the following: O_SQ_BRACKET IDENTIFIER NOT AT IMPLY .' At
line:1 char:1
+ Add-AdfsWebApiApplication -Name "My Web API" -AllowedClientTypes ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo :InvalidData: (#RuleTemplate =...ram = c.Value);:String) [Add-AdfsWebApiApplication],
PolicyValidationException
+ FullyQualifiedErrorId: POLICY0002.Microsoft.IdentityServer.Management.Commands.Add-AdfsWebApiApplicationCommand
Removing both #RuleTemplate and #RuleName, the following executes successfully but produces a custom rule that cannot be edited using the graphical template which provides dropdown lists for LDAP Attributes and Outgoing Claim Types.
Add-AdfsWebApiApplication -Name "My Web API" -AllowedClientTypes 6 -ApplicationGroupIdentifier "MyApp" -IssueOAuthRefreshTokensTo 2 -TokenLifetime 7 -Identifier {https://apphost/myapp/api/} -IssuanceTransformRules 'c:[Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname", Issuer == "AD AUTHORITY"] => issue(store = "Active Directory", types = ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"), query = ";mail,sAMAccountName,userPrincipalName;{0}", param = c.Value);'
Might someone suggest a way to include a name or template in the script?
What if you include your transform claim data in a variable and then reference variable in your cmdlet?
$transformRules = #"
#RuleTemplate = "LdapClaims"
#RuleName = "2"
c:[Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname", Issuer == "AD AUTHORITY"]
=> issue(store = "Active Directory", types = ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"), query = ";mail,sAMAccountName,userPrincipalName;{0}", param = c.Value);
"#
Add-AdfsWebApiApplication -Name "My Web API" -AllowedClientTypes 6 -ApplicationGroupIdentifier "MyApp" -IssueOAuthRefreshTokensTo 2 -TokenLifetime 7 -Identifier {https://apphost/myapp/api/} -IssuanceTransformRules $transformRules

Coffescript not compiling in rails app. Says syntax error - unexpected indentation

I'm new to coffeescript and I'm not sure what is wrong with my syntax. I want to add an error message if either the date or time field is empty upon clicking the update button. Here is my code.
$.add_error = (field, message) ->
unless field.hasClass('input-error')
field.after('<span class="input-error-message">' + message + '</span>')
field.addClass('input-error')
$.remove_error = (field) ->
field.removeClass('input-error')
field.parent().find('.input-error-message').remove()
$('.btn.update_schedule').click ->
date = $('#date')
time = $('#time')
if (date.val() && !time.val()) || (!date.val() && time.val())
if !time.val()
$.add_error(repeat_count, 'Please select both a date and time')
false
else !date.val()
$.add_error(repeat_date, 'Please select both a date and time')
false
else
$.remove_error(time) || $.remove_error(date)
I'm unable to compile this code because it says there's an unexpected indentation but I don't see it. Any advice would be greatly appreciated.
In the last block $('.btn.update_schedule').click ->, there is an
if ... else ... else ...
that is basically non-sense.
It seems that should be instead an
if ... else if ... else ...
This seems the correct version:
$('.btn.update_schedule').click ->
date = $('#date')
time = $('#time')
if (date.val() && !time.val()) || (!date.val() && time.val())
if !time.val()
$.add_error(repeat_count, 'Please select both a date and time')
false
else if !date.val()
$.add_error(repeat_date, 'Please select both a date and time')
false
else
$.remove_error(time) || $.remove_error(date)

Firebase FireAuthErrorCode when email address is empty

I'm implementing FireAuth error codes for firebase email and password signup, they all work except in 2 cases. When the email address field is empty, case .errorCodeInvalidEmail is called. When i type some letters (no valid email address), the default case is called. For the password field, it's the other way around. When i type one character the case .ErrorCodeWeakPassword" is called. When i leave the field empty, i go to the default case.
this is my code:
#IBAction func SignInButtonPressed(_ sender: LogInVcButton) {
if let email = emailField.text, let password = pwdField.text {
FIRAuth.auth()?.signIn(withEmail: email, password: password, completion: { (user, error) in
if error == nil {
print("Email User Authenticated with Firebase")
} else {
FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user, error) in
if error != nil {
if let errCode = FIRAuthErrorCode(rawValue: (error?._code)!) {
switch errCode {
case .errorCodeEmailAlreadyInUse: self.errorMessage(message: "Email address is already in use")
case .errorCodeInvalidEmail: self.errorMessage(message: "Email address is invalid")
case .errorCodeWrongPassword: self.errorMessage(message: "Wrong password")
case .errorCodeWeakPassword: self.errorMessage(message: "Password needs to be minimum 6 characters")
// TODO: A case for if the password field is blank
default: print("default")
}
} else {
print("Successfully Authenticated with Firebase")
}
}
})
}
})
}
}
I don't see which error code would handle the wrong email format or the empty password field in the docs. I can try to handle them my own, but i would think firebase would cover these cases ? https://firebase.google.com/docs/auth/ios/errors
Anyone can help me out ?
edit: after digging in some deeper i managed to print out the firebase descriptions of the errors.
if i pres sign in with emailAddress and password empty:
Optional(Error Domain=FIRAuthErrorDomain Code=17008 "The email address is badly formatted." UserInfo={NSLocalizedDescription=The email address is badly formatted., error_name=ERROR_INVALID_EMAIL})
case .errorCodeInvalidEmail is called. this is ok
When i write an invalid email address and empty password empty i get:
Optional(Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x6080000565c0 Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 400;
errors = (
{
domain = global;
message = "MISSING_PASSWORD";
reason = invalid;
}
);
message = "MISSING_PASSWORD";
}}}, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.})
NOK .errorCodeInternalError: It says missing password, but it should check the email address
When i type an invalid email address and one character in the password field i get:
Optional(Error Domain=FIRAuthErrorDomain Code=17008 "The email address is badly formatted." UserInfo={NSLocalizedDescription=The email address is badly formatted., error_name=ERROR_INVALID_EMAIL})
This seems ok
when i type a valid email address and no password:
Optional(Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x6080000565c0 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 400;
errors = (
{
domain = global;
message = "MISSING_PASSWORD";
reason = invalid;
}
);
message = "MISSING_PASSWORD";
}}}, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.})
NOK. .errorCodeInternalError
when i type a valid email address and one character in the pw field
Optional(Error Domain=FIRAuthErrorDomain Code=17026 "The password must be 6 characters long or more." UserInfo={NSLocalizedDescription=The password must be 6 characters long or more., error_name=ERROR_WEAK_PASSWORD, NSLocalizedFailureReason=Password should be at least 6 characters})
.errorCodeWeakPassword is called. This is ok too. and should also be the case on point 5 imo
When i type no email and a valid password
Optional(Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x600000053ce0 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 400;
errors = (
{
domain = global;
message = "MISSING_EMAIL";
reason = invalid;
}
);
message = "MISSING_EMAIL";
}}}, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.})
NOK Internal Error is called. Why not same as in point 1 ?

In Load Test - "The cast to value type 'System.Int32' failed because the materialized value is null"

when we are debugging below code with single user it is working fine. But while we tried to run Load test when user count goes more than 30 we are getting
"The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type." exception.
This is code snippet where we are getting exception.
profile.AccessRights = (
from t in entities.Opportunities
join x in entities.OpportunityWorkloadGroups on t.OpportunityId equals x.OpportunityId into oppworkloads
from ow in oppworkloads.DefaultIfEmpty()
join m in entities.OpportunityWorkloads on ow.OpportunityWorkloadGroupId equals m.OpportunityWorkloadGroupId into oppworkloadmodules
from om in oppworkloadmodules.DefaultIfEmpty()
join y in entities.OpportunityUsers on om.OpportunityWorkloadId equals y.OpportunityWorkloadId into users
from ou in users.DefaultIfEmpty()
where (((t.LookupOpportunityStatu.Name.Equals(Constants.EstimationStatusCompletedName) || t.LookupOpportunityStatu.Name.Equals(Constants.OpportunityStatusDiscardedName)
|| t.LookupOpportunityStatu.Name.Equals(OSEConstants.OpportunityStatusCompletedWithDiscards)) && !t.IsRestricted) ? true : ou.User.Alias == null ? true : ou.User.Alias == alias)
select new Microsoft.OneEstimator.DataAccess.Entities.AccessRights()
{
MasterUserId = userId,
MasterUserRole = roleName,
OpportunityId = t.OpportunityId,
IsOpportunityOwner = t.OpportunityOwner == userId ? true : false,
IsRestricted = t.IsRestricted,
StatusName = t.LookupOpportunityStatu.Name,
OpportunityWorkloadId = ow.OpportunityWorkloads.Any(m => m.OpportunityWorkloadGroupId == ow.OpportunityWorkloadGroupId) ? ow.OpportunityWorkloads.FirstOrDefault(m => m.OpportunityWorkloadGroupId == ow.OpportunityWorkloadGroupId).OpportunityWorkloadId : 0,
EstimationId = ow.OpportunityWorkloadGroupId == null ? 0 : ow.IsActive == false ? 0 : ow.OpportunityWorkloadGroupId,
RoleName = ou.Role == null ? string.Empty : ou.User.Alias == alias ? ou.Role.RoleName : string.Empty,
HasRightsForWA = ow.WorkloadGroupVersion != null ? entities.WorkloadGroupUsers.Any(y => y.WorkloadGroupId == ow.WorkloadGroupVersion.WorkloadGroup.WorkloadGroupId && y.UserId == userId && y.Role.RoleName.Equals(OSEConstants.Estimator)) : true,
WorkstreamUserRoleName = ow.WorkloadGroupVersion != null ? entities.WorkloadGroupUsers.FirstOrDefault(y => y.WorkloadGroupId == ow.WorkloadGroupVersion.WorkloadGroup.WorkloadGroupId && y.UserId == userId).Role.RoleName : string.Empty
}).ToList();
I guess I'm doing something wrong with DefaultIfNull() not sure.