Getting the user's Country ISO or Country name [duplicate] - ruby

I am trying to access the Control Panel: Region and Language: Location: Current location setting using Ruby. I am only interested in the country code.
The closest I have got is the country code from the System Locale but that is not quite what I was after.
`systeminfo | findstr /B /C:"System Locale"`.to_s.upcase.strip[30..31]
I hope that someone out there might know. Thanks.

Using the Win32 API:
require 'Win32API'
# Set up some Win32 constants
GEOCLASS_NATION = 16
GEO_ISO2 = 4
GEO_FRIENDLYNAME = 8
# Set up some API calls
GetUserGeoID = Win32API.new('kernel32', 'GetUserGeoID', ['L'], 'L')
GetGeoInfo = Win32API.new('kernel32', 'GetGeoInfoA', ['L', 'L', 'P', 'L', 'L'], 'L')
# Get user's GEOID
geoid = GetUserGeoID.call(GEOCLASS_NATION)
=> 77
# Get ISO name
buffer = " " * 100
GetGeoInfo.call(geoid, GEO_ISO2, buffer, buffer.length, 0)
geo_iso = buffer.strip
=> "FI"
# Get friendly name
buffer = " " * 100
GetGeoInfo.call(geoid, GEO_FRIENDLYNAME, buffer, buffer.length, 0)
geo_name = buffer.strip
=> "Finland"
Documentation for GetUserGeoID:
http://msdn.microsoft.com/en-us/library/dd318138.aspx
Documentation for GetGeoInfo:
https://learn.microsoft.com/en-us/windows/desktop/api/winnls/nf-winnls-getgeoinfoa
To convert a GEOID to a location name you can also use this table:
http://msdn.microsoft.com/en-us/library/dd374073.aspx

Related

In windows, how do I find out a folders sort by parameters

I am building an image viewing app in Node.js. I noticed that in Windows, the pictures in a folder can be sorted by name, size, status, type, date and tags etc, and grouped after sorting by the same list and more.
Is there a way of getting the sort parameters or maybe just retrieving the sorted list of files, matching the regular expression /\.(jpg|jpg_large|jpeg|jpe|jfif|jif|jfi|jpe|gif|png|ico|bmp|webp|svg)$/i, as an array (ex: ['c:\man.jpg', 'c:\woman.jpg'] using Powershell?
EDIT:
This article got me closer to a solution. https://cyberforensicator.com/2019/02/03/shellbags-forensics-directory-viewing-preferences/
Unfortunately it doesn't explain how to get the nodelist value for a given folder so I used an app called shellbagsview from nirsoft to get this value. In any case, if the value is found the rest is easy. I have included a sample python script which explains how this is done here.
from winreg import *
# Registry is of the form:
# HKEY_CURRENT_USER\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\Bags\1375\Shell\{5C4F28B5-F869-4E84-8E60-F11DB97C5CC7}
# where 1375 is a value called the NodeList, and {5C4F28B5-F869-4E84-8E60-F11DB97C5CC7} is a value under Shell chosen based on creation date. It is a good idea to look at the registry after getting the nodelist from shellbagsview
folder_reg_path = "Software\\Classes\\Local Settings\\Software\\Microsoft\\Windows\Shell\\Bags\\1375\\Shell\\{5C4F28B5-F869-4E84-8E60-F11DB97C5CC7}"
# the size of icons used by the folder
def get_folder_icon_size(reg_key):
with OpenKey(HKEY_CURRENT_USER, reg_key) as key:
value = QueryValueEx(key, 'IconSize')
return '%d pixels' % (value[0])
# the folder view. details, list, tiles e.t.c
def get_logical_view_mode(reg_key):
with OpenKey(HKEY_CURRENT_USER, reg_key) as key:
value = QueryValueEx(key, 'LogicalViewMode')
logical_view_mode_dict = {1 : "Details view", 2 : "Tiles view", 3 : "Icons view", 4 : "List view", 5 : "Content view"}
return logical_view_mode_dict[value[0]]
# folder view is based on view mode. so you can have a logical view mode of icons view with a view mode of large icons for instance
def get_folder_view_mode(reg_key):
with OpenKey(HKEY_CURRENT_USER, reg_key) as key:
value = QueryValueEx(key, 'Mode')
# view_mode 7 is only available on xp. A dead os
view_mode_dict = {1 : "Medium icons", 2 : "Small icons", 3 : "List", 4 : "Details", 5 : "Thumbnail icons", 6 : "Large icons", 8 : "Content"}
return view_mode_dict[value[0]]
# how is the folder being sorted
def get_folder_sort_by(reg_key):
with OpenKey(HKEY_CURRENT_USER, reg_key) as key:
value = QueryValueEx(key, 'Sort')
folder_sort_dict = {"0E000000" : "Date Modified", "10000000" : "Date Accessed", "0F000000" : "Date Created", "0B000000" : "Type", "0C000000" : "Size", "0A000000" : "Name", "02000000" : "Title", "05000000" : "Tags"}
# we get a byte value which we will hexify and get a rather long string
# similar to : 000000000000000000000000000000000100000030f125b7ef471a10a5f102608c9eebac0c000000ffffffff
reg_value = value[0].hex()
# now for this string, we need to get the last 16 strings. then we now get the first 8 out of it. so we will have
folder_sort_dict_key = (reg_value[-16:][:8]).upper()
return folder_sort_dict[folder_sort_dict_key]
# in what order is the folder being sorted. ascending or descending???
def get_folder_sort_by_order(reg_key):
with OpenKey(HKEY_CURRENT_USER, reg_key) as key:
value = QueryValueEx(key, 'Sort')
folder_sort_dict = {"01000000" : "Ascending", "FFFFFFFF" : "Descending"}
# we get a byte value which we will hexify and get a rather long string
# similar to : 000000000000000000000000000000000100000030f125b7ef471a10a5f102608c9eebac0c000000ffffffff
reg_value = value[0].hex()
# now for this string, we need to get the last 16 strings. then we now get the last 8 out of it. so we will have
folder_sort_dict_key = (reg_value[-16:][-8:]).upper()
return folder_sort_dict[folder_sort_dict_key]
icon_size = get_folder_icon_size(folder_reg_path)
logical_view_mode = get_logical_view_mode(folder_reg_path)
view_mode = get_folder_view_mode(folder_reg_path)
sorted_by = get_folder_sort_by(folder_reg_path)
sorted_by_order = get_folder_sort_by_order(folder_reg_path)
print ('The folder icon size is %s' % icon_size)
print('The folder logical view mode is %s' % logical_view_mode)
print('The folder view mode is %s' % view_mode)
print('The folder is sorted by %s in %s order' % (sorted_by, sorted_by_order))
The question itself and
the environment to run this in is unclear.
As you reference PowerShell and a RegEx to limit to specific extensions,
With this sample tree:
> tree /f a:\
A:\
└───Test
boy.bmp
child.ico
girl.gif
man.jpg
woman.jpg
this script:
Get-ChildItem -Path A:\Test -File |
Where-Object Extension -match '\.(jpg|jpg_large|jpeg|jpe|jfif|jif|jfi|jpe|gif|png|ico|bmp|webp|svg)$' |
Sort-Object Name |
Select-Object -ExpandProperty FullName |
ConvertTo-Json -Compress
yields:
["A:\\Test\\boy.bmp","A:\\Test\\child.ico","A:\\Test\\girl.gif","A:\\Test\\man.jpg","A:\\Test\\woman.jpg"]
The IShellView implementation (the file list part of Explorer) asks its IShellBrowser for a stream when it needs to load/save its state. My suggestion would be to host a IExplorerBrowser instance "browsed to the folder" and ask the view for its items. I don't know if you can ask it about which column it has sorted by but just getting the items in sorted order should be enough for your needs.
I don't know how to this in a scripting language but I assume PS supports enough COM for it to be possible.

How to LM Hash in Powershell

OK so i have been working on this for a bit, and i cant see how to get any further. I keep running into roadblocks with the DESCryptoServiceProvider and somehow it just doesnt seem to be comming out with the right answers.
the sudo code version of LM_Hash is:
LMHASH = concat(DES(Upper(PWD)[0..7],KGS!##$%),DES(Upper(PWD)[8..13],KGS!##$%))
First issue is the LM Key I keep seeing the atleast two variants its either "KGS!##$%" or "KGS!+#$%" neither gets me the right answers but both dont seem to fit with the origin story (its KGS and SHIFT 12345 assuming a US keyboard
on a UK thats "KGS!"£$%")
I am pretty sure i have the parameters set up correctly now, but my understanding seems to be failing me. here's what i have so far, any help is appreciated I am running Powershell V5.1 on Win 10, the string to encrypt is passed in as $string
$plaintext = "KGS!##$%"
$OEM = [System.Text.Encoding]::GetEncoding($Host.CurrentCulture.TextInfo.OEMCodePage)
$str1 = $OEM.GetBytes($string.substring(0,7)) +[Byte]$null
$str2 = $OEM.GetBytes($string.Substring(7)) +[Byte]$null
$IV = new-object "System.Byte[]" 8
$hasher = New-Object -TypeName System.Security.Cryptography.DESCryptoServiceProvider -Property #{key=$str1; IV = $IV; mode = [System.Security.Cryptography.CipherMode]::ECB; Padding=[System.Security.Cryptography.PaddingMode]::None}
$outbyte = new-object "System.Byte[]" 8
$encrypter1 = $hasher.CreateEncryptor()
$outbyte = $encrypter1.TransformFinalBlock($OEM.GetBytes($plaintext),0,8)
$data1 = [System.BitConverter]::ToString($outbyte).replace("-","")
$encrypter1.Dispose()
In theory this should encrypt the Key (which ever one it is) with DES using the first 7 characters of the string ($str1) as the key (with a null byte on the end) and then we do this to the second half ($str2) and concat them back together to get the LMHASH.
The ASCII-encoded string KGS!##$% is the correct magic constant to use
using the first 7 characters of the string ($str1) as the key (with a null byte on the end)
This, however, is incorrect. The key is not composed by padding the 7 bytes of partial input with a single 0-byte at the end, but by partitioning the input into 8 7-bit chunks and left-shifting them once (resulting in 8 bytes).
The easiest way to implement this in PowerShell is probably with strings, so I'd likely do something like this:
# Convert string to byte array
$inBytes = $OEM.GetBytes($str1)
# Create a binary string from our bytes
$bitString = ''
foreach($byte in $inBytes){
$bitstring += [convert]::ToString($byte, 2).PadLeft(8, '0')
}
# Partition the byte string into 7-bit chunks
[byte[]]$key = $bitString -split '(?<=\G.{7}(?<!$))' |ForEach-Object {
# Insert 0 as the least significant bit in each chunk
# Convert resulting string back to [byte]
[convert]::ToByte("${_}0", 2)
}
try{
# Create the first encryptor from our new key, and an empty IV
[byte[]]$iv = ,0 * 8
$enc = $hasher.GetEncryptor($key, $iv)
# Calculate half of the hash
$block1 = $enc.TransformFinalBlock($plaintext, 0, 8)
}
finally{
# Dispose of the encryptor
$enc.Dispose()
}
Then repeat for $str2 and concatenate the resulting blocks for the full LM hash
anyone having issues, based on #mathias R. Jessen
's answer above, here is a fuction that computes half the LM-Hash takes in 7 character string and outputs the hash as Hex.
Function LM-hash {
Param(
[Parameter(mandatory=$true,ValueFromPipeline=$true,position=0)]
[ValidateLength(7,7)]
[String]$Invalue
)
$plaintext = "KGS!##$%"
$OEM = [System.Text.Encoding]::GetEncoding($Host.CurrentCulture.TextInfo.OEMCodePage)
$inBytes = $OEM.GetBytes($invalue)
$bitString = ''
foreach($byte in $inBytes){
$bitstring += [convert]::ToString($byte, 2).PadLeft(8, '0')
}
[byte[]]$key = $bitString -split '(?<=\G.{7}(?<!$))' |ForEach-Object { [convert]::ToByte("${_}0", 2)}
$iv = new-object "System.Byte[]" 8
$DESCSP = New-Object -TypeName System.Security.Cryptography.DESCryptoServiceProvider -Property #{key=$key; IV = $IV; mode = [System.Security.Cryptography.CipherMode]::ECB; Padding=[System.Security.Cryptography.PaddingMode]::None}
$enc = $DESCSP.CreateEncryptor()
$block1 = $enc.TransformFinalBlock($OEM.GetBytes($plaintext), 0, 8)
return [System.BitConverter]::ToString($block1).replace("-","")
$enc.Dispose()
}
this gives the correct result for half the hash, so feeding each half in seperatley and concatenating the strings gives you a full LM hash

How to retrieve entire cost for a SoftLayer machine, including any extra costs such as bandwidth overages?

I've been retrieving monthly invoice cost information on our SoftLayer accounts for quite some time using the Ruby softlayer gem. However, there is a concern in the team that we may be missing certain costs, such as any overages on network utilization. I'd like to have some piece of mind that what I'm doing is correctly gathering all costs and we are not missing anything. Here is my code/query:
account = SoftLayer::Service.new("SoftLayer_Account",:username => user, :api_key => api_key, :timeout => 999999999)
softlayer_client = SoftLayer::Client.new(:username => user, :api_key => api_key, :timeout => 999999999)
billing_invoice_service = softlayer_client.service_named("Billing_Invoice")
object_filter = SoftLayer::ObjectFilter.new
object_filter.set_criteria_for_key_path('invoices.createDate', 'operation' => 'betweenDate', 'options' => [{'name' => 'startDate', 'value' => ["#{startTime}"]}, {'name' => 'endDate', 'value' => ["#{endTime}"]}])
# Set startDate and endDate around the beginning of the month in search of the "Recurring" invoice that should appear on the 1st.
invoices = account.result_limit(0,10000).object_filter(object_filter).object_mask("mask[id,typeCode,itemCount,invoiceTotalAmount,closedDate,createDate]").getInvoices
invoices.each do | invoice |
if invoice["typeCode"] == "RECURRING"
invoice_reference = billing_invoice_service.object_with_id(invoice["id"])
invoice_object = invoice_reference.object_mask("mask[itemCount]").getObject
billing_items_count = invoice_object["itemCount"]
billing_machines_map = Hash.new
all_billing_items = Array.new
# Search for billing items containing a hostName value.
# The corresponding billing item ID will become the key of a new hash.
# Child costs will be added to the existing costs.
billing_items_retrieval_operation = proc {
for i in 0..(billing_items_count/8000.0).ceil - 1
billing_items = invoice_reference.result_limit(i*8000, 8000).object_mask("mask[id,resourceTableId,billingItemId,parentId,categoryCode,hostName,domainName,hourlyRecurringFee,laborFee,oneTimeFee,recurringFee,recurringTaxAmount,setupFee,setupTaxAmount,location[name]]").getItems()
billing_items.each do | billing_item |
if billing_item["hostName"]
billing_machines_map[billing_item["id"]] = billing_item
end
end
all_billing_items.concat(billing_items)
end
}
# Look for items with parentIds or resourceTableIds.
# Both Ids represent a "parent" of the item.
# Give higher importance to parentId.
billing_items_retrieval_callback = proc {
cost_of_billing_items_without_parent = BigDecimal.new("0.00")
all_billing_items.each do | billing_item |
if billing_item["parentId"] != ""
parent_billing_machine = billing_machines_map[billing_item["parentId"]]
if parent_billing_machine parent_billing_machine["recurringFee"] = (BigDecimal.new(parent_billing_machine["recurringFee"]) + BigDecimal.new(billing_item["recurringFee"])).to_s('F')
parent_billing_machine["setupFee"] = (BigDecimal.new(parent_billing_machine["setupFee"]) + BigDecimal.new(billing_item["setupFee"])).to_s('F')
parent_billing_machine["laborFee"] = (BigDecimal.new(parent_billing_machine["laborFee"]) + BigDecimal.new(billing_item["laborFee"])).to_s('F')
parent_billing_machine["oneTimeFee"] = (BigDecimal.new(parent_billing_machine["oneTimeFee"]) + BigDecimal.new(billing_item["oneTimeFee"])).to_s('F')
end
elsif billing_item["resourceTableId"] != ""
parent_billing_machine = billing_machines_map[billing_item["resourceTableId"]]
if parent_billing_machine
parent_billing_machine["recurringFee"] = (BigDecimal.new(parent_billing_machine["recurringFee"]) + BigDecimal.new(billing_item["recurringFee"])).to_s('F')
parent_billing_machine["setupFee"] = (BigDecimal.new(parent_billing_machine["setupFee"]) + BigDecimal.new(billing_item["setupFee"])).to_s('F')
parent_billing_machine["laborFee"] = (BigDecimal.new(parent_billing_machine["laborFee"]) + BigDecimal.new(billing_item["laborFee"])).to_s('F')
parent_billing_machine["oneTimeFee"] = (BigDecimal.new(parent_billing_machine["oneTimeFee"]) + BigDecimal.new(billing_item["oneTimeFee"])).to_s('F')
end
else
cost_of_billing_items_without_parent = (BigDecimal.new(cost_of_billing_items_without_parent) + BigDecimal.new(billing_item["recurringFee"])).to_s('F')
cost_of_billing_items_without_parent = (BigDecimal.new(cost_of_billing_items_without_parent) + BigDecimal.new(billing_item["setupFee"])).to_s('F')
cost_of_billing_items_without_parent = (BigDecimal.new(cost_of_billing_items_without_parent) + BigDecimal.new(billing_item["laborFee"])).to_s('F')
cost_of_billing_items_without_parent = (BigDecimal.new(cost_of_billing_items_without_parent) + BigDecimal.new(billing_item["oneTimeFee"])).to_s('F')
end
end
pp "INVOICE: Total cost of devices for account without a parent is:"
pp cost_of_billing_items_without_parent
end
end
end
After the above I make calls to getVirtualGuests and getHardware to get some additional meta information for each machine (I tie them together based on billingItem.id. Example:
billingItemId = billing_machine["billingItemId"]
account_service = softlayer_client.service_named("Account")
filter = SoftLayer::ObjectFilter.new {|f| f.accept("virtualGuests.billingItem.id").when_it is(billingItemId)}
virtual_guests_array = account_service.object_filter(filter).object_mask("mask[id, hostname, datacenter[name], billingItem[orderItem[order[userRecord[username]]]], tagReferences[tagId, tag[name]], primaryIpAddress, primaryBackendIpAddress]").getVirtualGuests()
As you can see I don't make any calls to capture bandwith overage charges. I have printed out the various "category" values I get from the above query but I am not seeing anything specific to network utilization (it's possible there are no extra network utilization costs but I am not certain).
Thank you.
Any extra costs such as bandwidth overages will be included in the billing item from the server. So you don't need to make any other call to the api to get it.

Parsing a string field

I have these Syslog messages:
N 4000000 PROD 15307 23:58:12.13 JOB78035 00000000 $HASP395 GGIVJS27 ENDED\r
NI0000000 PROD 15307 23:58:13.41 STC81508 00000200 $A J78036 /* CA-JOBTRAC JOB RELEASE */\r
I would like to parse these messages into various fields in a Hash, e.g.:
event['recordtype'] #=> "N"
event['routingcode'] #=> "4000000"
event['systemname'] #=> "PROD"
event['datetime'] #=> "15307 23:58:12.13"
event['jobid'] #=> "JOB78035"
event['flag'] #=> "00000000"
event['messageid'] #=> "$HASP395"
event['logmessage'] #=> "$HASP395 GGIVJS27 ENDED\r"
This is the code I have currently:
message = event["message"];
if message.to_s != "" then
if message[2] == " " then
array = message.split(%Q[ ]);
event[%q[recordtype]] = array[0];
event[%q[routingcode]] = array[1];
event[%q[systemname]] = array[2];
event[%q[datetime]] = array[3] + " " +array[4];
event[%q[jobid]] = message[38,8];
event[%q[flags]] = message[47,8];
event[%q[messageid]] = message[57,8];
event[%q[logmessage]] = message[56..-1];
else
array = message.split(%Q[ ]);
event[%q[recordtype]] = array[0][0,2];
event[%q[routingcode]] = array[0][2..-1];
event[%q[systemname]] = array[1];
event[%q[datetime]] = array[2] + " "+array[3];
event[%q[jobid]] = message[38,8];
event[%q[flags]] = message[47,8];
event[%q[messageid]] = message[57,8];
event[%q[logmessage]] = message[56..-1];
end
end
I'm looking to improve the above code. I think I could use a regular expression, but I don't know how to approach it.
You can't use split(' ') or a default split to process your fields because you are dealing with columnar data that has fields that have no whitespace between them, resulting in your array being off. Instead, you have to pick apart each record by columns.
There are many ways to do that but the simplest and probably fastest, is indexing into a string and grabbing n characters:
'foo'[0, 1] # => "f"
'foo'[1, 2] # => "oo"
The first means "starting at index 0 in the string, grab one character." The second means "starting at index 1 in the string, grab two characters."
Alternately, you could tell Ruby to extract by ranges:
'foo'[0 .. 0] # => "f"
'foo'[1 .. 2] # => "oo"
These are documented in the String class.
This makes writing code that's easily understood:
record_type = message[ 0 .. 1 ].rstrip
routing_code = message[ 2 .. 8 ]
system_name = message[ 10 .. 17 ]
Once you have your fields captured add them to a hash:
{
'recordtype' => record_type,
'routingcode' => routing_code,
'systemname' => system_name,
'datetime' => date_time,
'jobid' => job_id,
'flags' => flags,
'messageid' => message_id,
'logmessage' => log_message,
}
While you could use a regular expression there's not much gained using one, it's just another way of doing it. If you were picking data out of free-form text it'd be more useful, but in columnar data it tends to result in visual noise that makes maintenance more difficult. I'd recommend simply determining your columns then cutting the data you need based on those from each line.

unpack base64-encoded 32bit integer representing IP address

I have a base64-encoded, 32-bit integer, that's an IP address: DMmN60
I cannot for the life of me figure out how to both unpack it and turn it into a quad-dotted representation I can actually use.
Unpacking it with unpack('m') actually only gives me three bytes. I don't see how that's right either, but this is far from my expertise.
Hello from the future (two years later) with Ruby 1.9.3. To encode:
require 'base64'
ps = "204.152.222.180"
pa = ps.split('.').map { |_| _.to_i } # => [204, 152, 222, 180]
pbs = pa.pack("C*") # => "\xCC\x98\xDE\xB4"
es = Base64.encode64(s) # => "zJjetA==\n"
To decode:
require 'base64'
es = "zJjetA==\n"
pbs = Base64.decode64(es) # => "\xCC\x98\xDE\xB4"
pa = pbs.unpack("C*") # => [204, 152, 222, 180]
ps = pa.map { |_| _.to_s }.join('.') # => "204.152.222.180"
Name explanation:
ps = plain string
pa = plain array
pbs = plain binary string
es = encoded string
For your example:
Base64.decode64("DMmN60==").unpack("C*").map { |_| _.to_s }.join('.')
# => "12.201.141.235"
Just like #duskwuff said.
Your comment above said that the P10 base64 is non-standard, so I took a look at: http://carlo17.home.xs4all.nl/irc/P10.html which defines:
<base64> = 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',
'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
'w','x','y','z','0','1','2','3','4','5','6','7','8','9','[',']'
It is the same as http://en.wikipedia.org/wiki/Base64 -- except that the last two characters are + and / in the normal Base64. I don't see how this explains the discrepancy, since your example did not use those characters. I do wonder, however, if it was due to some other factor -- perhaps an endian issue.
Adding padding (DMmN60==) and decoding gives me the bytes:
0C C9 8D EB
Which decodes to 12.201.141.235.

Resources