Oracle 10g & PowerShell - How to create hashed password - oracle

I have a PowerShell script that will create a new Oracle user. The code is correct, and the user is created as expected. My only problem is replicating Oracle's password hashing.
I'd like to have the ability to hash the password in PowerShell using the same algorithm as Oracle 10g and then insert the hashed password into Oracle using this code. IDENTIFIED BY VALUES 'NEED TO INSERT HASHED PASSWORD'.
Here's an example of a current password in the database: IDENTIFIED BY VALUES '033348433385A2DE'
I tried a few things in PowerShell but couldn't get it to work. According to my understanding, Oracle uses the username & password combination to generate the hashed value, among other things. Any advice would be greatly appreciated.
This is the code I'm currently using. It establishes an Oracle connection and then inserts the required information.
$login_newname = 'SomeName'
$query_user = CREATE USER $login_newname
IDENTIFIED BY VALUES 'NEED TO INSERT HASHED PASSWORD'
DEFAULT TABLESPACE USER_DATA
TEMPORARY TABLESPACE TEMPORARY_DATA
PROFILE DEFAULT
ACCOUNT UNLOCK"
$connectionstring = "User Id = $username;Password = $password;Data Source = $datasource"
$con = New-Object Oracle.ManagedDataAccess.Client.OracleConnection(“$connectionString”)
$con.open()
$cmd=$con.CreateCommand()
$query_user_1 = "GRANT CONNECT TO $login_newname WITH ADMIN OPTION"
$query_user_2 = "GRANT RESOURCE TO $login_newname WITH ADMIN OPTION"
$query_user_3 = "GRANT ALL_ACCESS TO $login_newname WITH ADMIN OPTION"
$query_user_4 = "ALTER USER $login_newname DEFAULT ROLE CONNECT, RESOURCE"
$query_user_5 = "GRANT SELECT ANY TABLE TO $login_newname WITH ADMIN OPTION"
$query_user_6 = "GRANT UNLIMITED TABLESPACE TO $login_newname WITH ADMIN OPTION"
$cmd.CommandText=$query_user
$cmd.ExecuteNonQuery() | Out-Null
$cmd.CommandText=$query_user_1
$cmd.ExecuteNonQuery() | Out-Null
$cmd.CommandText=$query_user_2
$cmd.ExecuteNonQuery() | Out-Null
$cmd.CommandText=$query_user_3
$cmd.ExecuteNonQuery() | Out-Null
$cmd.CommandText=$query_user_4
$cmd.ExecuteNonQuery() | Out-Null
$cmd.CommandText=$query_user_5
$cmd.ExecuteNonQuery() | Out-Null
$cmd.CommandText=$query_user_6
$cmd.ExecuteNonQuery() | Out-Null

I have managed to find a work-around for anyone that needs to replicate the same functionality.
I have defaulted this line like so IDENTIFIED BY VALUES 'password' .This will now create a user in Oracle with a password of 'password' but it won't apply the hashing.
I had to add an extra line:
$query_user_7 = "ALTER USER $login_newname IDENTIFIED BY password(This can be anything, your desired password)"
And then execute the query like so:
$cmd.CommandText=$query_user_7
$cmd.ExecuteNonQuery() | Out-Null
This will apply Oracle hashing to your new password and will allow you to login.
Please note, this works for Oracle 10g. I have not tried to do this on later Oracle versions.

Related

Using PowerShell to Check for Newly Created Local Admins

So, as the title says: I am trying to write up a PowerShell script that checks to see if any user accounts have been added to the Local Administrators group or have been added as an Administrator on the local machine. I have been using Get-EventLog and Get-WinEvent in an attempt to accomplish what I a trying to do. The problem I am having is isolating or extracting the information I want out of the event logs.
This is what I have so far:
$Date = ((Get-Date).AddDays(-1)).Date
$Events = Get-WinEvent -FilterHashtable #{
StartTime = $Date
LogName = 'Security'
ProviderName = 'Microsoft-Windows-Security-Auditing'
ID = 4732
}
I figure, if I can get the Username of the account that was added; which group or permissions it was given; and the date it was created, I can selectively output that information for each log over the last 24 hours. I'm not sure if I should be trying to use Get-Item or Get-Content, or if there is another way I should be trying to tackle this.
Unless you have powershell v6.0+ installed, you'll need to use -FilterXPath instead:
$Alerts = Get-WinEvent -LogName Security -FilterXPath #'
<QueryList>
<Query Id="0" Path="Security">
<Select Path="Security">*[System[
EventID=4732 and
TimeCreated[timediff(#SystemTime) <= 604800000]]] and
*[EventData[Data[#Name="TargetDomainName"]='BUILTIN']] and
*[EventData[Data[#Name='TargetUserName']='Administrators']]
</Select>
</Query>
</QueryList>
'#
You can use -FilterHashTable if you are running powershell v6.0 or higher. I would use something like this to check for those events. My servers don't all have v6, so I would have to run it remotely like so:
#Requires -Version 6.0
$alerts = Get-WinEvent -ComputerName $computername -FilterHashtable #{
StartTime = ((Get-Date).AddDays(-1)).Date
LogName = 'Security'
ProviderName = 'Microsoft-Windows-Security-Auditing'
ID = 4732
TargetDomainName='Builtin' ## These fields require
TargetUserName='Administrators' ## Powershell v6.0+
}
I'll include how I convert event log's local SIDs to usernames for reports, since it's a pain
# Process event(s)
if ($alerts) { foreach ($event in $alerts) {
# Try and convert SID to account name:
$sid = $event.Properties[1].Value.Value
$localuser = ([System.Security.Principal.SecurityIdentifier]::new($sid)
).Translate([System.Security.Principal.NTAccount])).Value
}
# Use SID in case of failure
if (!$localuser){$localuser=$event.Properties[1].Value}
# Example action
Write-Warning "User $localuser added to local Administrators group on $computername by user $($event.Properties[7].Value)\$($event.Properties[6].Value)"
}}
# Outputs
WARNING: User Server01\local-user01 added to local Administrators group on Server01 by user DOMAIN\AdminUser01

using Ruby to check that username exists in sqlite3 database

I am new to ruby. I am trying use ruby accept username from user and check it against sqlite3 database to see if it exists. if it exists, then ask user to input a different username. I have tried below code but it doesn't work. Please help me.
The sqlite3 table is "cpu_dues" and the column I am checking against is "user_name". Then I am accepting a variable "user" to compare with values in the database.
require 'sqlite3'
print "Enter your Username: "
user = gets.chomp().to_s
db = SQLite3::Database.open 'ipu_db.db'
db.results_as_hash = false
user_exist = [db.execute( "SELECT user_name FROM ipu_dues WHERE user_name = ('#{user}')"), 1]
if user_exist[0] = user
puts "Keep asking for username"
else
puts "accept username and carry on"
end

Can you create an anonymous-access Windows share all from PowerShell?

Windows makes it difficult to create a network share with anonymous access (in other words, users who the share-hosting machine does not know about can access). The net share ShareName=C:\DesiredShareSource /GRANT:EVERYONE,FULL gives access to Everyone, but that does not include anonymous access (e.g. non-domain joined users, WITHOUT prompting credentials).
I know there's a way to do this from a GUI (https://serverfault.com/questions/272409/setting-up-an-anonymous-windows-server-2008-network-share), but is there a way changing security policies and creating anonymous network shares can be done strictly from PowerShell?
EDIT
This is what happens when I run the WMI script posted by Ansgar Wiechers. I get an exception but the share mounts successfully:
However, when I try and connect to the share from another box on the same network, I am still prompted for a username and password, as seen below:
Again, I want anonymous access (no username and password) to be set up all from command line.
Here is the exact code I am using in testingAnonShare.ps1, on a Win7 system:
$path = 'C:\Users\<REDACTED>\Desktop\Attempt'
$name = 'testinganon'
$description = 'share description'
function Get-Trustee($sid) {
$trustee = ([wmiclass]'Win32_Trustee').CreateInstance()
$trustee.SID = ([wmi]"Win32_SID.SID='$sid'").BinaryRepresentation
return $trustee
}
function New-FullAce($sid) {
$ace = ([wmiclass]'Win32_ACE').CreateInstance()
$ace.AccessMask = 2032127 # full control
$ace.AceFlags = 3 # container inherit + object inherit
$ace.AceType = 0 # access allowed
$ace.Trustee = Get-Trustee $sid
return $ace
}
$sd = ([wmiclass]'Win32_SecurityDescriptor').CreateInstance()
$sd.ControlFlags = 4
$sd.DACL = (New-FullAce 'S-1-1-0'),
(New-FullAce 'S-1-5-7')
$wmi = Get-WmiObject Win32_Share -List
$wmi.Create($path, $name, 0, $null, $description, '', $sd) | Out-Null
All examples create a share called test mapped to a path D:\test, granting full access to Anonymous and Everyone.
Windows Server 2012 R2 and newer
To create a share with everyone having Full access this is the command
New-SmbShare -Name 'test' -path 'D:\test' -FullAccess 'ANONYMOUS LOGON','Everyone'
To update an existing share to have the same permission is a little more complicated. First, assume the share name is test. Here is the code to change it to the same permissions as above.
Get-SmbShare -Name test |
Set-SmbShare -SecurityDescriptor 'O:BAG:DUD:(A;;FA;;;AN)(A;;FA;;;WD)'
To get the SecurityDescriptor string, create a share test like you want it and run the following command.
(get-smbshare -Name Test).SecurityDescriptor
Backward compatible (NET SHARE)
This can also be done with net share
net share test=D:\test /GRANT:"ANONYMOUS LOGON,FULL" /GRANT:"Everyone,FULL"
In addition to New-SmbShare (Windows Server 2012 or newer) and net share you can also use WMI for creating network shares.
$path = 'C:\DesiredShareSource'
$name = 'sharename'
$description = 'share description'
function Get-Trustee($sid) {
$trustee = ([wmiclass]'Win32_Trustee').CreateInstance()
$trustee.SID = ([wmi]"Win32_SID.SID='$sid'").BinaryRepresentation
return $trustee
}
function New-FullAce($sid) {
$ace = ([wmiclass]'Win32_ACE').CreateInstance()
$ace.AccessMask = 2032127 # full control
$ace.AceFlags = 3 # container inherit + object inherit
$ace.AceType = 0 # access allowed
$ace.Trustee = Get-Trustee $sid
return $ace
}
$sd = ([wmiclass]'Win32_SecurityDescriptor').CreateInstance()
$sd.ControlFlags = 4
$sd.DACL += (New-FullAce 'S-1-1-0').PSObject.BaseObject
$sd.DACL += (New-FullAce 'S-1-5-7').PSObject.BaseObject
$wmi = Get-WmiObject Win32_Share -List
$wmi.Create($path, $name, 0, $null, $description, '', $sd) | Out-Null
S-1-1-0 and S-1-5-7 are the well-known SIDs of the Everyone and Anonymous groups respectively.
Appending each ACE separately to the DACL property is required to make the code work with PowerShell v2. In more recent version you can assign the ACEs as an array, and you also don't need to unwrap the base object:
$sd.DACL = (New-FullAce 'S-1-1-0'), (New-FullAce 'S-1-5-7')
To actually enable anonymous access to shares you also need to make three changes to the local security policy (source):
Start secpol.msc.
Navigate to Security Settings → Local Policies → Security Options.
Change the following settings:
Accounts: Guest account status → Enabled
Network access: Let Everyone permissions apply to anonymous users → Enabled
Network access: Shares that can be accessed anonymously → sharename
Note that I did not have to change the setting Network access: Restrict anonymous access to Named Pipes and Shares to enable anonymous access from Windows 7 to an anonymous share on Server 2012 R2, but I did have to add NTFS permissions for the Everyone group.
$acl = Get-Acl -Path 'C:\DesiredShareSource'
$ace = New-Object Security.AccessControl.FileSystemAccessRule(
'Everyone', 'ReadAndExecute', 'ContainerInherit, ObjectInherit', 'None', 'Allow'
)
$acl.AddAccessRule($ace)
Get-Acl -Path 'C:\DesiredShareSource' -AclObject $acl
I'm not aware of a way to make the policy changes with a script. You may be able to cook up something by wrapping secedit in PowerShell, but whenever I had to deal with secedit it turned out to be … bothersome, so I wouldn't recommend it. In a domain environment you can deploy local security policy settings via group policies, though.

How to add another windows user to MS Dynamics NAV valid user?

I installed MS Dynamics NAV from my windows admin account and It's running successfully on admin login. But when I login from another account and start NAV(2016), It shows :
you do not have access to microsoft dynamics nav .verify that you have been setup as a valid user in ms dynamics NAV.
I can't install NAV setup from my windows account as It don't have permission to install anything.
I am totally new to it, need help.
Step 1 - You will need the Windows Security ID or SSID
Open powershell and paste the below code
$objUser = New-Object System.Security.Principal.NTAccount("YourDomain\Your ID")
$strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
$strSID.Value
Replace YourDomain\Your ID with your Your Domain and USER ID.
Run the code and in the output, you will find the SSID.
STEP 2 - ENTER USER Details in NAVISION Database with Roles.
Open SQL Server Management Studio.
In My Case the database that i want to get access is Demo Database NAV (7-1).
Click on New Query and paste below listed command in the query window.
USE [DATABASE NAME]
DECLARE #USERSID uniqueidentifier, #WINDOWSSID nvarchar(119), #USERNAME nvarchar(50), #USERSIDTXT varchar(50)
SELECT NEWID()
SET #USERNAME = 'YourDomain\Your ID'
SET #USERSID = NEWID()
SET #USERSIDTXT = CONVERT(VARCHAR(50), #USERSID)
SET #WINDOWSSID = 'Your SSID'
INSERT INTO [dbo].[User]
([User Security ID],[User Name],[Full Name],[State],[Expiry Date], [Windows Security ID],[Change Password],[License Type],[Authentication Email])
VALUES
(#USERSID,#USERNAME,'',0,'1753-01-01 00:00:00.000',#WINDOWSSID,0,0,'')
INSERT INTO [dbo].[User Property]
([User Security ID],[Password],[Name Identifier],[Authentication Key], [WebServices Key],[WebServices Key Expiry Date],[Authentication Object ID])
VALUES
(#USERSID,'','','','','1753-01-01 00:00:00.000','')
INSERT INTO [dbo].[Access Control]([User Security ID],[Role ID],[Company Name])
VALUES
(#USERSID,'SUPER','')
GO
Replace
DATABASE NAME - with your database name
YourDomain\Your ID - with your Domain Name & User Name
Your SSID - with SSID as copied in STEP 1
The Query provide SUPER Role to user, if required you can change the Role in the Last part of the query.
Go to SQL Server Management Studio
Right click on database you are using , select new query and copy paste below syntax:
delete from [dbo].[User]
press F5 and restart. It will help you .
Quick way option with powershell, you should change some configurations.
For NAV 2016
$appUser = "XXX\XXX"; # User Name
$appUserFullName = "XXXXXxxxXX"; # FullName
$dataSource = "192.168.100.XX"; # SQL SERVER IP
$user = "sa"; # USERNAME
$pwd = "XXxxXX"; # SA Password
$database = "NAVERP"; # Database
$connectionString = "Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;";
$connection = New-Object System.Data.SqlClient.SqlConnection;
$connection.ConnectionString = $connectionString;
$objUser = New-Object System.Security.Principal.NTAccount($appUser)
$strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
$sqlCommandText ="
USE NAVERP
DECLARE #USERSID uniqueidentifier, #WINDOWSSID nvarchar(119), #USERNAME nvarchar(50), #USERSIDTXT varchar(50), #FullName as varchar(50)
SELECT NEWID()
SET #USERNAME = '$appUser'
set #FullName = '$appUserFullName'
SET #USERSID = NEWID()
SET #USERSIDTXT = CONVERT(VARCHAR(50), #USERSID)
SET #WINDOWSSID = '$strSID'
INSERT INTO [dbo].[User]
([User Security ID],[User Name],[Full Name],[State],[Expiry Date],[Windows Security ID], [Change Password],[License Type],[Authentication Email],[Contact Email])
VALUES
(#USERSID,#USERNAME,#FullName,0,'1753-01-01 00:00:00.000',#WINDOWSSID,0,0,'','');
INSERT INTO [dbo].[User Property]
([User Security ID],[Password],[Name Identifier],[Authentication Key], [WebServices Key],[WebServices Key Expiry Date],[Authentication Object ID])
VALUES
(#USERSID,'','','','','1753-01-01 00:00:00.000','');
INSERT INTO [dbo].[Access Control]([User Security ID],[Role ID],[Company Name],[App ID],Scope)
VALUES
(#USERSID,'SUPER','',cast(cast(0 as binary) as uniqueidentifier),0);
";
$connection.Open();
$command = $connection.CreateCommand();
$command.CommandText = $sqlCommandText;
$command.ExecuteNonQuery();
$connection.Close();
$sqlCommandText

PowerShell folder permission error - Some or all identity references could not be translated

I am running this script as Admin and It does create the folders requred, just does not set the appropriate permissions.
$Users = Get-Content "D:\New_Users.txt"
ForEach ($user in $users)
{
$newPath = Join-Path "F:\Users" -childpath $user
New-Item $newPath -type directory
$UserObj = New-Object System.Security.Principal.NTAccount("DOMAIN",$user)
$acl = Get-Acl $newpath
$acl.SetAccessRuleProtection($True, $False)
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("O1OAK\$user","AppendData,CreateDirectories,CreateFiles,DeleteSubdirectoriesAndFiles,ExecuteFile,ListDirectory,Modify,Read,ReadAndExecute,ReadAttributes,ReadData,ReadExtendedAttributes,ReadPermissions,Synchronize,Traverse,Write,WriteAttributes,WriteData,WriteExtendedAttributes","ContainerInherit, ObjectInherit","None","Allow")
$acl.SetAccessRule($accessRule)
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("NT AUTHORITY\SYSTEM","FullControl","ContainerInherit, ObjectInherit","None","Allow")
$acl.SetAccessRule($accessRule)
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Administrators","FullControl","ContainerInherit, ObjectInherit","None","Allow")
$acl.SetAccessRule($accessRule)
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("1OAK\$user","Delete","ContainerInherit, ObjectInherit","None","Allow")
$acl.removeAccessRule($accessRule)
$acl.SetOwner($UserObj)
$acl | Set-Acl $newpath
}
The first error in a string of 3 that I get is below. I think it is the most important and will fix the other 2.
Exception calling "SetAccessRule" with "1" argument(s): "Some or all identity references could not be translated."
At D:\DOMAIN\IT\IT Private\User Drives\user_folders.ps1:12 char:20
+ $acl.SetAccessRule <<<< ($accessRule)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
The error is pretty self explanatory: Some or all identity references could not be translated.
This means the account couldn't be found. So what you have to do is verify your accounts. Since you're adding 4 ACE's, you'll need to identify which is invalid.
The easiest way to do this is to debug through, line by line using the ISE or PowerGUI.
I tried your code with "NT AUTHORITY\SYSTEM" and "BUILTIN\Administrators" and it works so the issue is with "O1OAK\$user" or "1OAK\$user". You likely have an invalid account in your text file.
a gotch with the user ID is that AD truncates the username, so a user with a long name "j_reallylongname" will have a samid (Security Account Manager (SAM) account name) which is truncated. (j_reallylong)
so when fetching usernames, make sure you verify against the AD before using it.
When i've got the upns, so i run a dsget query to get the samid then use that to build the identity reference.
Adding this in case any C#/ASP.NET developers get this (which is my scenario, and I found this post).
I am using .NET Core in a corporate environment, and I need to check UserGroups as part of security. The code is like (where "user" is a ClaimsPrincipal):
var windowsIdentity = user.Identity as WindowsIdentity;
if( windowsIdentity is null )
throw new Exception( $"Invalid Windows Identity {user.Identity.Name}" );
return windowsIdentity.Groups
.Select( g => g.Translate( typeof( NTAccount ) ).Value );
Anyway, someone in charge of groups deleted a group I was part of, and the AD replication lag caused me to get the error in the title. A logoff and/or reboot worked just fine.
For me it was a case of where i verified whether the script execution knew the password by using $user = Get-Credential "username". i had to turn my $user into $user.UserName To give the script parameters the value they were expecting

Resources