Playing with Logs – Regex

Playing with Logs – Regex

Recently I was playing with some sql event viewer logs. These logs don’t have properties that we can pull from to make life easier. So, everything has to be parsed through the string. Which isn’t bad, but it’s a challenge to think about. Here is what one of the strings looks like:

Login failed for user 'db_admin'. Reason: Password did not match that for the login provided. [CLIENT: 10.0.80.55]

I wanted three items from this list, the username, the reason, and the IP address. The username is inside the single quotes. The reason goes from the word reason to the [ for client. The IP address is inside the brackets for the client. Lets get started. First lets get the data.

$test = invoke-command -ComputerName servername -ScriptBlock {Get-WinEvent -FilterHashTable @{logname='application';providername='MSSQLSERVER';Keywords='4503599627370496'}}

Grabing Everything between double single qoutes.

Now we have the data, it’s time to get the username. As I said, the username is found inside the single quotes. So we want to select the string with a pattern that pulls the double single quotes.

($t.message | Select-String -Pattern "'.*?'" -AllMatches).Matches.Value -replace "'",""

‘.*?’

This bad boy here grabs everything between the single quotes. The ‘—‘ is the boundaries. the . says to match any character except the terminators. Yeah, we don’t want skynet. Then the X? tells it to match the previous token between 0 and forever times. The select starts off with the first and then moves to the next character. which is a wild card. Then we search all wildcards forever until the next with the *? characters.

We select every item in the string that matches that pattern using the -AllMatches. Then we grab the Matches by using the ().Matches. We want those values so we select the value from the matches. ().Matches.Value. This still selects the double single quotes and we really don’t want this. So we simply remove them by using the -replace command. We replace the ‘ by saying -replace “‘”,””. Looks a little confusing but it works.

Grabbing Text after a word and before a symbol.

The next part is to grab the reason. This is basically grabbing everything after a single word and before something different. The logic is the same as before, but this time we are grabbing it based off a word.

Reason =  (($t.Message | Select-String -Pattern "Reason:.*\[" -AllMatches).Matches.Value -replace ' \[','') -replace 'Reason: ',''

“Reason:.*\[“

In this instance we are searching for the word Reason:. Once we find that word, we select the first object in front of it using a wild card again. The wild card is a . like before. Then we tell it to continue searching using the * until we reach special character of [. Notice the \ is before the [. The reason for this is because in the world of Regex the bracket, [, is a special character used for searching. Thus this code is saying, start with the word reason: and search everything until you reach the square bracket.

Once we have the pattern we select all the matches like before with the -allmatches. We then select the matches and the values using the ().matches.value commands. From there we want to remove the square bracket and the word reason:. We do that with replace commands to remove the word reason we use -replace (“Reason: “,”) and to remove the extra space and square bracket we us -replace (‘ \[‘,”). Notice once again, the \ before the square bracket.

Pulling an IP address from a string

The next thing we need is the IP address of the log. The IP address is located in the square brackets with the word client inside of it. The key here is not to search those brackets. We want the IP address of any and all strings. We want all the IP addresses and not just one.

IPAddress = ($t.message |  Select-String -Pattern "\d{1,3}(\.\d{1,3}){3}" -AllMatches).Matches.Value

\d{1,3}(\.\d{1,3}){3}

This one is much more complex than the last one. The first thing we do is look for is up to three digits side by side. \d means digits. The {1,3} means between 1 and 3. We do this until we reach a . mark. Then we repeat the process again 3 times. We use the () to create a group. Inside that group, we have the \. which is the decimal point followed by the \d{1,3} again. Saying after the decimal point looks for up to three digits again. Finally, we tell the code to do this 3 times with the {3} tag at the end of the group.

Like before we use the -allmatches flag to get all the matches and pipe it out using the ().Matches.value method. But wait! This only pulls the IP address format, not the IP address. This works for an IP address of 512.523.252.1 which we all know is an invalid IP address. To do that we have to dive much deeper into regex. This next part is complex.

Validate an IP address

The above gives an idea of what we want to look for, a starting point, here is the big fish that we need to break down. This code is a bit longer. This code is broken up between whatif structures. Which is pretty cool. It’s going to take some effort to explain it all. So we will take one group at a time with each whatif | statement. Remember each group represented with () is for a single octet. I am going to try my best at explaining this one. I’m not fully sure, but once again, I will try.

^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-5][0-9]|[01]?[0-9][0-9]?)$

25[0-5]|

Our first what if statement is the 25[0-5]. The maximum number for an octet is 255. In fact, 255.255.255.255 is the broadcast address. In this what-if statement, we are looking at matching the first two characters of an octet as 25 then we are looking for any number after that as a 0 to 5. So, anything like 256 would be ignored.

2[0-4][0-9]|

The next one is for the middle of the 255 range. This tests to see if the range is 2xy. The x is between 0 and 4 and the y is 0 and 9. I’ll be honest, When I changed out the 4 with a 5, the value of 256 was accepted when it shouldn’t have been. There is something special later on on this one.

[01]?[0-9][0-9]?

Now we are matching if the first character is a 1. So, this will cover the 100-199 ranges. If there is a 1 there, if not, then it will cover the 0-99. The ? matches the previous item between 0 and one times. So the previous item is a 1 or a number. This creates the nice 0-199 range.

\.){3}

The \ symbol is our break symbol to break the regex processing on the next item which is our . symbol. Normally . means a wild card. In this case it means a period or decimal point. Then we close the group with our closing parentheses, ). Now we have made a group that determines if an object is between 1 and 255 with a period at the end, we need to do this 3 times. There is multiple ways to do this. We can repeat the code 3 times or we can just say {3}. That’s what we did here.

(25[0-5]|2[0-5][0-9]|[01]?[0-9][0-9]?)

Finally, we repeat the code again. This time without the \. at the end. The reason we do this is that the last octet doesn’t have a period at the end. This matches between 1-255 without the period.

Grabbing Mac Addresses from a string

Another item I pull from logs is mac addresses. Most of the time these are security logs from a firewall. However, it’s important to be able to pull a match address. The big thing between a mac address and an IP address is the mac address requires letters and numbers. They also come in all forms of delimiters. the most common are :, ., , and a space for the truly evil people. Thus, you have to address each of these items. Here is the code:

([0-9a-fA-F]{2}[: \.-]){5}([0-9a-fA-F]{2})

[0-9a-fA-F]{2}

The first part of the code is looking for the numbers 0 – 9. For example 0F:69:0F:FE:00:01 is the code. The first section is 0F. The 0 – 9 helps us find the 0. The next part a – f helps us find a,b,c,d,e, and f. The A – F helps us find A,B,C,D,E, and F. This way we don’t have to worry about case sensitivity when searching for the logs as some logs don’t capitalize the letters. Finally, we are going to search this two times before our next symbol.

[: \.-]

This next part is the search for the different symbols. Notice we have the common ones in there. The first is the standard colon :. It is followed by a space and then the escape character because the period is a wild card character. Which is then followed by the hyphen as ipconfig /all gives you hypens. It’s all within the search brackets.

(){5}

We then close up the group with our () marks. This will search for at least one of those that match. We want 5 items in a row for a mac address. Mac addresses contain 6 sections. So, the next code is important to find that 6th. We search for the 5 in the row by the {5} mark.

([0-9a-fA-F]{2})

We repeat the code over again. This way we get that last section of the mac address. This time tho, we don’t have the search for the unique symbols as the last section of a mac address doesn’t have one.

Putting these in a script

If you read my blog often, you know I like functions. Here are two functions you can add to your tool bag.

Get-SHDIPFromString

Function Get-SHDIPFromString{
    [cmdletbinding()]
    Param (
        [string]$String
    )
    foreach ($string in $string) {
        ($String | Select-String -Pattern "((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" -AllMatches).Matches.Value
    }
}

Example:

PS> Get-SHDIPFromString -String "This message contains 192.168.25.5 as an IP address." 
192.168.25.5  

Get-SHDMacFromString

function Get-SHDMacFromString {
    [cmdletbinding()]
    Param (
        [string[]]$String
    )
    foreach ($string in $String) {
        ($String | Select-String -Pattern '(?<mac>([0-9a-fA-F]{2}[: \.-]){5}([0-9a-fA-F]{2}))' -AllMatches).matches.value
    }
}

Example:

PS> Get-SHDMacFromString -String "Physical Address. . . . . . . . . : 11-35-AF-FE-11-A1"
11-35-AF-FE-11-A1
Resolve a Site name to Geo Location

Resolve a Site name to Geo Location

With everything that happened with Facebook yesterday, I began to wonder where does my query goes when I type in facebook.com. So, I did a few things and found out. The first thing I did was resolve the name facebook.com to an IP address, or group of IP addresses in this case with the command resolve-dnsname.

Resolve-DnsName -Name facebook.com

Then from there, I used the site, ip-api.com to pull the location information of the IP address. This awesome little site gives you city, state, country, zip codes, and even the ISP information of an IP address.

$Info = Invoke-RestMethod -Method Get -URI "http://ip-api.com/json/$IP"

That’s the base of the code that we will explore. It’s very straightforward, but I want to clean it up some. I want to make a Get GEO IP information and a Resolve DNSname to Geo IP. I want it to all work together even if there is multiple IP addresses and hosts names. So, lets start off with the scripts and break them down. This will contain two functions for what we are wanting.

Get-SHDGeoIP

function Get-SHDGeoIP {
    [cmdletbinding()]
    param (
        [parameter(Mandatory = $true)][ipaddress[]]$IPAddress,
        [switch]$Complete
    )
    foreach ($IP in $IPAddress) {
        
        $Info = Invoke-RestMethod -Method Get -URI "http://ip-api.com/json/$IP"
        if ($Complete) {
            $Info
        }
        else {
            [pscustomobject]@{
                IPAddress = $info.Query
                City      = $Info.city
                State     = $Info.regionName
                Country   = $Info.country
                ISP       = $Info.isp
            }
        }
    }
}

This script is going to pull the geo information for us. We start off with the parameters. We are testing the parameters to see if the IP address is an valid IP address. We do that with [ipaddress]. This tests for both IPv4 and IPv6. We tell it to be a array of IPaddresses with the [] inside of it. [ipaddress[]]. Just for cleaner fun, I have a switch for a complete information dump. This way

Since this is an array of IP addresses, we will start a foreach loop for each IP address in the array. We start the foreach loop by grabbing the IP information. If the user selected complete, we just dump the information we gathered to the user. if they didn’t select complete, we create a custom object with the IP address, city, state, country and ISP information.

Resolve-SHDDNSNameToGeoIP

Function Resolve-SHDDNSNameToGeoIP {
    [cmdletbinding()]
    param (
        [parameter(Mandatory = $true)][string[]]$Hostname,
        [switch]$Complete
    )
    foreach ($Name in $Hostname) {
        if ($Complete) {
            Get-SHDGeoIP -IPAddress (Resolve-DnsName -Name $Name).IPAddress -Complete
        }
        else { 
            Get-SHDGeoIP -IPAddress (Resolve-DnsName -Name $Name).IPAddress
        }
    }
}

The next function uses the previous function and combines it with Resolve-DnsName. We start off with a list of strings for our hostname parameter and our complete parameter. We start our loop like before of the host names. Then we use the Get-SHDGeoIP -IPAddress command with the Resolve-DnsName -Name and the link name. We then select the IP addresses which is an array. We place that array inside the Get-SHDGeoIP and bam, we have our information. Converting a hostname like Facebook.com to IP information.

With these two little scripts, you will be able to find quick information about a website and where it is being hosted. For example, this site is hosted in new jersey. I personally didn’t know that.

Let me know if you use this and how.

Datamuse API and PowerShell

Datamuse API and PowerShell

There are 171,476 or so words in the English language. This doesn’t include names or other items. Datamuse is a very powerful database of English words. It contains rhyming, like, anonymous, Synonyms and much more. What I like about this site is it has a simple API that can be stacked. You can find the API here.

What do I mean by stacked. Some APIs use the URL and gathers all the information from that. While others uses the custom header and body of requests. Datamuse uses the URL. It returns a nice json to work with as well inside its content area. Basically, it’s my kind of API. The below API is an example of a url API. After words? each XX= has the word to query with. Each item means something different. The ML means, means like and the sp is spelled like. So we are looking for words that means like black and starts with the letter b.

https://api.datamuse.com/words?ml=Black&sp=b*

URL API’s are super easy to work within PowerShell. The key is to make a string of what you are looking for. If you have a flag of $meansLike = Black. Then it will add the &ml=black to the string. Same as $Spelling=”B*”. It will add the &ml=Black&sp=B*. Then we just remove the first character of the string and we have our string. We do that with substring. Let’s take a look at the full script.

The Script

function Get-SHDWords {
    [cmdletbinding()]
    param (
        [string]$MeansLike,
        [string]$SoundsLike,
        [string]$SpelledLike,
        [string]$LeftContext,
        [string]$RightContext,
        [string]$Topic,
        [string]$NounModifiedByAdjective,
        [string]$AdjectiveModifiedbyNoun,
        [string]$Synonym,
        [string]$Trigger,
        [string]$Antonym,
        [string]$KindOf,
        [string]$MoreGeneralThan,
        [string]$Comprises,
        [string]$Meronym,
        [string]$FrequentFollowers,
        [string]$FrequentPredecessors,
        [string]$Rhymes,
        [string]$NearRhymes,
        [string]$Homophones,
        [string]$Consonant,
        [switch]$Random
    )
    $actionstring = ""
    if ($PSBoundParameters.ContainsKey('MeansLike')) { $actionstring = "$($actionstring)&ml=$MeansLike" }
    if ($PSBoundParameters.ContainsKey('SoundsLike')) { $actionstring = "$($actionstring)&sl=$SoundsLike" }
    if ($PSBoundParameters.ContainsKey('SpelledLike')) { $actionstring = "$($actionstring)&sp=$SpelledLike" }
    if ($PSBoundParameters.ContainsKey('LeftContext')) { $actionstring = "$($actionstring)&lc=$LeftContext" }
    if ($PSBoundParameters.ContainsKey('RightContext')) { $actionstring = "$($actionstring)&rc=$RightContext" }
    if ($PSBoundParameters.ContainsKey('Topic')) { $actionstring = "$($actionstring)&topics=$Topic" }
    if ($PSBoundParameters.ContainsKey('NounModifiedByAdjective')) { $actionstring = "$($actionstring)&rel_jja=$NounModifiedByAdjective" }
    if ($PSBoundParameters.ContainsKey('AdjectiveModifiedbyNoun')) { $actionstring = "$($actionstring)&rel_jjb=$AdjectiveModifiedbyNoun" }
    if ($PSBoundParameters.ContainsKey('Synonym')) { $actionstring = "$($actionstring)&rel_syn=$Synonym" }
    if ($PSBoundParameters.ContainsKey('Trigger')) { $actionstring = "$($actionstring)&rel_trg=$Trigger" }
    if ($PSBoundParameters.ContainsKey('Antonym')) { $actionstring = "$($actionstring)&rel_ant=$Antonym" }
    if ($PSBoundParameters.ContainsKey('KindOf')) { $actionstring = "$($actionstring)&rel_spc=$KindOf" }
    if ($PSBoundParameters.ContainsKey('MoreGeneralThan')) { $actionstring = "$($actionstring)&rel_gen=$MoreGeneralThan" }
    if ($PSBoundParameters.ContainsKey('Comprises')) { $actionstring = "$($actionstring)&rel_com=$Comprises" }
    if ($PSBoundParameters.ContainsKey('Meronym')) { $actionstring = "$($actionstring)&rel_par=$Meronym" }
    if ($PSBoundParameters.ContainsKey('FrequentFollowers')) { $actionstring = "$($actionstring)&rel_bag=$FrequentFollowers" }
    if ($PSBoundParameters.ContainsKey('FrequentPredecessors')) { $actionstring = "$($actionstring)&rel_bgb=$FrequentPredecessors" }
    if ($PSBoundParameters.ContainsKey('Rhymes')) { $actionstring = "$($actionstring)&rel_rhy=$Rhymes" }
    if ($PSBoundParameters.ContainsKey('NearRhymes')) { $actionstring = "$($actionstring)&rel_nry=$NearRhymes" }
    if ($PSBoundParameters.ContainsKey('Homophones')) { $actionstring = "$($actionstring)&rel_hom=$Homophones" }
    if ($PSBoundParameters.ContainsKey('Consonant')) { $actionstring = "$($actionstring)&rel_cns=$Consonant" }
    if ($Random) {
        $Character = [char](Get-Random -Minimum 65 -Maximum 90)
        $actionstring = "$($actionstring)&sp=$Character*"
    }
    $actionstring = $actionstring.Substring(1)
        (Invoke-WebRequest -Uri "https://api.datamuse.com/words?$actionstring").content | convertfrom-json
}

The Breakdown

Ok, first notice that we have each of the items from the datamuse site as string values that can take input. None of them are mandatory. The first thing after the parameters is our blank action string.

Next, we start questioning the input like a youtube conspiracy theorist. We do that by asking if the bound parameters contains a key. If it does we add to the action string.

    if ($PSBoundParameters.ContainsKey('MeansLike')) { $actionstring = "$($actionstring)&ml=$MeansLike" }

Here we are recreating the string by taking the value of the string and adding the &ml=$MeansLike. We do this for each parameter we use except for random. Random we just grab a random english word character and ask for a word that starts with that word. After we have created our action string we use our substring command to remove the first & from the string.

$actionstring = $actionstring.Substring(1)

Once we have the action string formatted right, we are ready to go. We use the invoke-webrequest command and we will grab the data. We will select only the content, which is in a nice json format. Then we will pipe that information into convertfrom-json to create a Powershell object.

(Invoke-WebRequest -Uri "https://api.datamuse.com/words?$actionstring").content | convertfrom-json

From here you can select the data you want. Lets look at some examples.

Example 1 – Link

Get-SHDWords -SpelledLike "L*" -Rhymes "Pink"

Here are the results:

word     score numSyllables
----     ----- ------------
link      2267            1
linc       144            1
lip sync   105            2
lynk        43            1
linke       31            1
linck        2            1

Here we are looking for all the words that start with the letter L and that Rhyme with Pink.

Example 2 – Lash

Get-SHDWords -MeansLike anger -SoundsLike love | Where-Object {$_.tags -contains "v"}

Here are the results:

word score tags
---- ----- ----
lash 14742 {v}

In this example, we are looking for words that mean anger but sound like love. Some of the results will have tags. Items like means like and sounds like have tags that you can filter through. With this example, we are looking for verbs. So we look with the where-object command.

Example 3 – Random Word

$Test = Get-SHDWords -Random
$test[(Get-Random -Minimum 0 -Maximum $test.count)].word
ominous

In this example, we get a random list of words that start with a random letter. Then we select from that list a random item. We do that with the get-random with a minimum of 0 and the maximum of the test count. Then we select the word. All that produced the word ominous.

Taking a step farther – Passwords

Let’s take this one step further and make a two-word password. The first thing we want is a word. So we use the command Get-SHDwords again. We are going to use the word trust.

$Charcter = [char](Get-Random -Minimum 33 -Maximum 64)
$CharcterEnd = [char](Get-Random -Minimum 33 -Maximum 64)
$CharcterMiddle = [char](Get-Random -Minimum 33 -Maximum 64)
$One = "Trust"
$Two = Get-SHDWords -Rhymes $One
$Two = $two[(Get-Random -Minimum 0 -Maximum $two.count)].word -replace ("[ aAeEiIoOuUyY](?!.*[aAeEiIoOuUyY])", "$Charcter")
"$one$($CharcterMiddle)$Two$($CharcterEnd)"

The password this produced was: Trust<comb?st’

Here we generate 3 random characters. We then select our word, trust by putting it into the $One. We can replace our word by replacing the $One input. Then we get the second word with two. Get-SHDWords -Rhymes $One Then we grab just one of those words like before. This time we replace all the vowels with the character we generated at the beginning. Then we combine it all together. The first word, $One, the middle character, $characterMiddle, the second word $two, and finally the ending Character $CharacterEnd. Now we have an easy-to-remember password.

Datamuse offers even more options than what this script offers. Check them out and see what amazing things you can create.

I’m going to leave off here with a challenge this week. Can you write a poem using datamuse based off the word:

$Test = Get-SHDWords -Random
$test[(Get-Random -Minimum 0 -Maximum $test.count)].word

Post your results in the comments.

Embed Files into Powershell Scripts

Embed Files into Powershell Scripts

Do you have a zip file or an msi file that you need to embed into a powershell script for deployment. This is a quick and simple way to do this. The method is pretty sound and works most of the time. The larger the file, the more troubles the system has converting and converting back, so small files works wonders for this method.

The first thing we are going to do is convert a file into a base 64 string. This is done through the command Get-Content and the system convert method. Powershell 7 recently changed the command for this method and we will cover that first.

Powershell 7 Command

The get content changed the encoding flag to asbytestream flag.

$Content = Get-Content -Path $Path -AsByteStream -raw

This command will read the data as raw byte data which is needed for the System convert method. The Powershell 5 method users Encoding and then you select your type which is byte.

Powershell 5

$Content = Get-Content -Path $Path -Encoding Byte

These commands reads the data as raw information that will be used for the system.convert to base 64 string method.

$base64 = [system.convert]::ToBase64String($content)

Now the Base64 contains something that looks like this:

"//4wADEAMAAwADAAMAAwADAAZAAwADgAYwA5AGQAZABmADAAMQAxADUAZAAxADEAMQA4AGMANwBhADAAMABjADAANABmAGMAMgA5ADcAZQBiADAAMQAwADAAMAAwADAAMABlADYAYQAyADMAOAA4ADIAOQA3ADIAOQBiADIANABhAGEAMAA0ADcAMQBjADEANQBjADcAYwAwAGQANQA4AGYAMAAwADAAMAAwADAAMAAwADAAMgAwADAAMAAwADAAMAAwADAAMAAwADAAMwA2ADYAMAAwADAAMABjADAAMAAwADAAMAAwADAAMQAwADAAMAAwADAAMAAwAGIAMQA5ADcAOAA5AGQAYgBmADkAMAAxADYANgA2ADEANQBlADgAMwAzAGQAOQAxADMANgA0ADEAYwBmAGIANAAwADAAMAAwADAAMAAwADAAMAA0ADgAMAAwADAAMAAwAGEAMAAw==

We take that information and Pipe it into the clip.exe to bring it to our clipboard.

$Base64 | clip.exe

Converting it back

Now we need to convert the string back to a file. To do that we are going to use the System.Convert from base 64 string.

$Object = [System.Convert]::FromBase64String("The crazy text")

Now we have an object of random-looking data like before. We need to write those bytes to a file we do that with the System.IO.File write all bytes method. We will need the outfile location. and the object we created earlier to complete this task.

[system.io.file]::WriteAllBytes($OutFile,$object)

This will create the file you embedded into your powershell script.

Use Case

Encrypted Passwords

Let’s secure a password file and key file inside our embedded script. First, we are going to create the key for out password file.

$key = New-Object byte[] 16
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key)
$key | Out-File C:\temp\TestPassword.key 

This is the content of our key file:

41
202
16
223
129
18
138
116
106
132
9
217
180
41
226
108

Now we have our key made it’s time to create the password file.

$Password = "lazyAppl351" | ConvertTo-SecureString -AsPlainText -Force 
$Password | ConvertFrom-SecureString -Key $Key | Out-File c:\temp\TestPassword.txt

This is what the Password file looks like on the inside:

76492d1116743f0423413b16050a5345MgB8ADkAMAA1AGYAaABaAC8ASAB3AG8AUQBQAGUAdwBKAHgAbwBJAFIAKwA5AHcAPQA9AHwAZQA2ADQAOQBiADMAMQA2AGEAYwBjADAANAA4AGUANQAxAGMAOAA2ADgAOABkADkAYgBmAGIANgBkAGUAMgAwADQAZQA3AGQAMgA2ADMAMQBiADQANQA4AGIAOAA1ADcAMABlADAAMQBhAGIAYgA4AGIAYQBhADEAOAA4ADMANAA=

Now we will embed these files into our script.

$KeyFile = Get-Content -Path C:\temp\TestPassword.key -Encoding Byte
$base64 = [system.convert]::ToBase64String($Keyfile)
$Base64 | clip.exe

This will convert the key file into a working string that we can convert later. This is what the information looks like:

NDENCjIwMg0KMTYNCjIyMw0KMTI5DQoxOA0KMTM4DQoxMTYNCjEwNg0KMTMyDQo5DQoyMTcNCjE4MA0KNDENCjIyNg0KMTA4DQo=

Now we will do the same thing for the password file.

$KeyFile = Get-Content -Path C:\temp\TestPassword.txt -Encoding Byte
$base64 = [system.convert]::ToBase64String($Keyfile)
$Base64 | clip.exe

This is what this looks like:

NzY0OTJkMTExNjc0M2YwNDIzNDEzYjE2MDUwYTUzNDVNZ0I4QURrQU1BQTFBR1lBYUFCYUFDOEFTQUIzQUc4QVVRQlFBR1VBZHdCS0FIZ0Fid0JKQUZJQUt3QTVBSGNBUFFBOUFId0FaUUEyQURRQU9RQmlBRE1BTVFBMkFHRUFZd0JqQURBQU5BQTRBR1VBTlFBeEFHTUFPQUEyQURnQU9BQmtBRGtBWWdCbUFHSUFOZ0JrQUdVQU1nQXdBRFFBWlFBM0FHUUFNZ0EyQURNQU1RQmlBRFFBTlFBNEFHSUFPQUExQURjQU1BQmxBREFBTVFCaEFHSUFZZ0E0QUdJQVlRQmhBREVBT0FBNEFETUFOQUE9DQo=

Now we build the script with these two pieces of information. We recreate the files from the script and then pull them in like before. Here is the key code:

$keyBase64 = "NDENCjIwMg0KMTYNCjIyMw0KMTI5DQoxOA0KMTM4DQoxMTYNCjEwNg0KMTMyDQo5DQoyMTcNCjE4MA0KNDENCjIyNg0KMTA4DQo="
$Object = [System.Convert]::FromBase64String($keyBase64)
[system.io.file]::WriteAllBytes('C:\temp\TestPassword.key',$object)

and here is the Password code:

$PassBase64 = "NzY0OTJkMTExNjc0M2YwNDIzNDEzYjE2MDUwYTUzNDVNZ0I4QURrQU1BQTFBR1lBYUFCYUFDOEFTQUIzQUc4QVVRQlFBR1VBZHdCS0FIZ0Fid0JKQUZJQUt3QTVBSGNBUFFBOUFId0FaUUEyQURRQU9RQmlBRE1BTVFBMkFHRUFZd0JqQURBQU5BQTRBR1VBTlFBeEFHTUFPQUEyQURnQU9BQmtBRGtBWWdCbUFHSUFOZ0JrQUdVQU1nQXdBRFFBWlFBM0FHUUFNZ0EyQURNQU1RQmlBRFFBTlFBNEFHSUFPQUExQURjQU1BQmxBREFBTVFCaEFHSUFZZ0E0QUdJQVlRQmhBREVBT0FBNEFETUFOQUE9DQo="
$Object = [System.Convert]::FromBase64String($PassBase64)
[system.io.file]::WriteAllBytes('C:\temp\TestPassword.txt',$object)

Now we have both files needed to receive our password, let’s convert that password using the key from before. We get the content of the .key file with get-content. Then we use it when we convert to secure string the password file. Pushing all that information into a new credential object for later use in something like a nextcloud download. Then we remove the files as we don’t want that password getting out there.

$Username = "BobTheUser"
$key = Get-Content 'C:\temp\TestPassword.Key'
$MyCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content 'c:\temp\TestPassword.txt' | ConvertTo-SecureString -Key $key)
remove-item c:\temp\TestPassword.txt
remove-item c:\temp\TestPassword.key

MSI file

Let’s say we need to embed an MSI file. For example, we have a custom Open DNS MSI that will auto setup the Umbrella client on an end user’s computer. The first thing we want to do is convert that msi file to the base 64 string like above.

$content = Get-Content -Path C:\Temp\CustomOpenDNS.msi -Encoding Bye
[system.Convert]::ToBase64String($Content) | clip.exe

Here we are using the powershell 5 code to convert the msi into a string and pushing it out to our clipboard. Now we need to place that information into the script. This is what the script would look like:

$Base64 = "PCFET0NUWVBFIGh0bWw+CjxodG1sIGNsYXNzPSJuZy1jc3AiIGRhdGEtcGxhY2Vob2xkZXItZm9jdXM9ImZhbHNlIiBsYW5nPSJlbiIgZGF0YS1sb2NhbGU9ImVuIiA+Cgk8aGVhZAogZGF0YS1yZXF1ZXN0dG9rZW49IkZPVkorSVltUkJucnoyNU4zZDZyclhIM0Y5c3NzK3BSOS9HaVN2WFBMZHc9OldLQjd0OHdRSzE2TWx5VVBsNy9ZM0R2T1dMWjk5dHBpcjRlYkxzS3RXTFU9Ij4KCQk8bWV0YSBjaGFyc2V0PSJ1dGYtOCI+CgkJPHRpdGxlPgoJCVJhbmRvbW5lc3MJCTwvdGl0bGU+CgkJPG1ldGEgaHR0cC1lcXVpdj0iWC1VQS1Db21wYXRpYmxlIiBjb250ZW50PSJJRT1lZGdlIj4KCQk8bWV0YSBuYW1lPSJ2aWV3cG9ydCIgY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Fzcz0ic3ZnIGljb24tY29uZmlybSBpbnB1dC1idXR0b24taW5saW5lIiB2YWx1ZT0iIiBkaXNhYmxlZD0iZGlzYWJsZWQiIC8+CgkJPC9wPgoJPC9maWVsZHNldD4KPC9mb3JtPgoJCQkJPC9tYWluPgoJCQk8L2Rpdj4KCQk8L2Rpdj4KCQk8Zm9vdGVyIHJvbGU9ImNvbnRlbnRpbmZvIj4KCQkJPHAgY2xhc3M9ImluZm8iPgoJCQkJPGEgaHJlZj0iaHR0cHM6Ly9uZXh0Y2xvdWQuY29tIiB0YXJnZXQ9Il9ibGFuayIgcmVsPSJub3JlZmVycmVyIG5vb3BlbmVyIiBjbGFzcz0iZW50aXR5LW5hbWUiPlJhbmRvbW5lc3M8L2E+IOKAkyBCZWhvbGQgV29ybGQgb2Ygd2V0IHNvY2tzCQkJPC9wPgoJCTwvZm9vdGVyPgoJPC9ib2R5Pgo8L2h0bWw+Cg==
"
$Object = [System.Convert]::FromBase64String($Base64)
[system.io.file]::WriteAllBytes("C:\temp\test.msi",$object)
msiexec /i C:\temp\test.msi /qn /norestart

As you can see by the size of the base64 string, that seems like a large file. Surprisingly that’s only 11kb in size. The larger the file the more code will be present and the chances of buffer overload increases.

Scripts

What kind of person would I be without giving you a function or two to make life easier on you. Here are two functions. The first converts the item to base64 string and copies it to your clipboard. The second converts a base64 string to an object.

function convertto-base64 {
    [cmdletbinding()]
    param (
        [string]$Path
    )
    process {
        if ($PSVersionTable.PSVersion.Major -ge 7) {
            $Content = Get-Content -Path $Path -AsByteStream -raw
        } else {
            $Content = Get-Content -Path $Path -Encoding Byte
        }
        $base64 = [system.convert]::ToBase64String($content)
        $Base64 | clip.exe
    }
}

Here is the convert back to the object script. You will need the string and an out path.

function Convertfrom-base64 {
    [cmdletbinding()]
    param (
        [string]$Base64String,
        [string]$OutFile
    )
    process {
        $Object = [System.Convert]::FromBase64String($Base64String)
        [system.io.file]::WriteAllBytes($OutFile,$object)
    }
}
Log Public IP Changes

Log Public IP Changes

This little script logs public IP address changes. The original design was to email out. I’ll make sure to point out when and where to put that code. So the idea is simple. It checks to see if it’s public IP address has changed using an invoke-webrequest. If it has changed, it checks to see if a log has been made. If it has been made, it updates the log, if it hasn’t been made, it creates the log. Then when the IP address changes back, it backs up the logs and stops. Lets take a look at the script.

The Script

Param (
    [string]$IPAddress = "Your IP Address"
)  
$IP = (invoke-webrequest -Uri "http://ifconfig.me/ip" -UseBasicParsing).content
If (!(Test-Path C:\temp)) { New-Item -Path "c:\temp" -ItemType Directory }
if (!($IP -like "$IPAddress")) {
    if (!(Test-Path c:\temp\IPTrigger.log )) {

#Email Code Goes Here

        $Datetime = (Get-Date).ToString("yyyy-MM-dd_HH-mm")
        "Datetime,IP" > c:\temp\IPTrigger.log
        "$datetime,$IP" >> c:\temp\IPTrigger.log 
    }
    else {
        $Datetime = (Get-Date).ToString("yyyy-MM-dd_HH-mm")
        "$datetime,$IP" >> c:\temp\IPTrigger.log 
    }
}
else {
    if (Test-Path c:\temp\IPTrigger.log) {
        $Datetime = (Get-Date).ToString("yyyy-MM-dd_HH-mm")
        Copy-Item -Path c:\temp\IPTrigger.log -Destination "c:\temp\IPTrigger_$($datetime).log.bak"
        Remove-Item -Path  c:\temp\IPTrigger.log

#Email Code goes here with attachment of the log bak. 

    }
}

The Breakdown

We grab the IP address from the Paramters. This way you can have the script called Public-IPChecker -IPAddress Something from your task scheduler. After we get what the IP Address should be we get what It is with the Invoke-webrequest command.

$IP = (invoke-webrequest -Uri "http://ifconfig.me/ip" -UseBasicParsing).content

There are a hand full of sites that grabs the IP address for you. I personally like Ifconfig.me because it places the IP address as the content. Thus no sorting through the HTML to get the IP address.

Next we ask if it’s the IP address. Then we ask if the log has been made.

if (!($IP -like "$IPAddress")) {
    if (!(Test-Path c:\temp\IPTrigger.log )) {}
}

If it doesn’t exist, we create it by getting the DateTime into a file friendly format. and Piping that information into the log file along with the current IP address.

$Datetime = (Get-Date).ToString("yyyy-MM-dd_HH-mm")
"Datetime,IP" > c:\temp\IPTrigger.log
"$datetime,$IP" >> c:\temp\IPTrigger.log 

If it does exist, we just update the log file using the same code but this time we remove the “Datetime,IP” part.

$Datetime = (Get-Date).ToString("yyyy-MM-dd_HH-mm")
"$datetime,$IP" >> c:\temp\IPTrigger.log 

If the IP addresses do match then we test to see if the log file is there. If it is there we create a bak of the log file and remove the old one. This is when you can send an email saying it’s back up. If it doesn’t exist, we do nothing.

if (Test-Path c:\temp\IPTrigger.log) {
        $Datetime = (Get-Date).ToString("yyyy-MM-dd_HH-mm")
        Copy-Item -Path c:\temp\IPTrigger.log -Destination "c:\temp\IPTrigger_$($datetime).log.bak"
        Remove-Item -Path  c:\temp\IPTrigger.log
}

That’s the full script in a nutshell.