That Time Windows 10 Defeated Me

So, I’m a gamer — it’s one of my primary hobbies outside of rock climbing and go-karting and fast car driving at the track.

I’m going to speak blasphemy here for a moment by telling you that until about 45 days ago, I was running on the same base install of my OS that I deployed when Windows 7 launched.  Yep, I’m an IT guy and I ran Windows 7 until 8 came out, did an in-place upgrade to 8, then did an in-place upgrade to 8.1, then did an in-place upgrade to 10.  I’m that guy.

In my defense, my computer worked fine throughout — a lot of people like to give Windows grief for its ability to fall apart after long periods of time, and most IT people (myself included) recommend doing a refresh of your OS every one to two years to make sure it’s in a good shape — but as I had not experienced any real issues, I kept chugging away on the same OS install.  At least, until the great alt-tabbing of 2017 began to occur.

It started small — once every few hours of playing a full-screen game, I would be randomly alt-tabbed out to the desktop and have to alt-tab back into the game I was playing. I did all of the requisite checking — made sure my anti-malware was up to date, ran through startup options, checked running processes, did a full scan, the whole 9.  Uncovered nothing.  Did an nVidia driver update, made sure my chipset drivers had been updated, ensured my motherboard drivers were current, did a quick BIOS update.  Glasswire showed no network traffic being sent during the incidents and a cursory review showed no unexpected network traffic to any unexpected hosts at any period of time.

Still occurred.  Went through scheduled tasks and cleaned out a lot of cruft that had migrated from previous versions of Windows as a few of the tasks seemed to coincide with the times that I was being alt-tabbed out of games and did uncover a Microsoft Office update telemetry scheduled task that caused a console window to appear for a second before disappearing (they’ve since updated and fixed that issue), which I thought was the culprit.

Alas, disabling it made no difference.  On the contrary, as the months passed, the frequency of this became higher and higher until about 45 days ago when it was happening within 5-7 minutes of running any full screen game or video application.  I ran Process Monitor to log every single system call being made to see what I could find and it never gave me any indication as to what was occurring.  I downloaded a couple of apps that purported to tell me what application was stealing focus when focus was lost and all they told me was that Explorer had stolen focus.  I saw no scheduled tasks executing that should be calling Explorer and couldn’t correlate the times to any actual event happening in Process Monitor.

I spent something like 2 months troubleshooting this — I’m a problem solver by nature and there’s nothing I like (and … dislike) more than a difficult and complicated problem to solve.  I noted some Scheduled Tasks that were only shown in ‘Running Tasks’ and referenced solely by GUID but that I couldn’t ever track down in the actual task scheduler.  I monitored reads/writes to the Task Scheduler library directories on the PC to see if a process was creating a scheduled task, executing it, and then deleting it — but found nothing.  Microsoft seemingly doesn’t make any kind of debug-level task scheduling software, so it was remarkably difficult to uncover what these tasks were doing, but I really thought they might be the culprit as the times/dates of their execution matched the times I was being kicked out of full-screen gaming.

Unfortunately, there’s really no happy ending to this story — I couldn’t uncover what in the world was causing this and ultimately ended up doing a full clean install of Windows 10 and rebuilding my desktop from scratch, which did resolve the issue.  To my surprise though, the GUID tasks existed in Task Scheduler on a completely clean Windows 10 install from known good install media — so I’m still somewhat curious what those tasks are and why they exist.  You probably have them as well, every Windows 10 PC I’ve looked at since has had them.  Just open up Task Scheduler, ensure you’ve enabled “All Tasks History”, and then wait a day or so and look at the last 24 hours of tasks.  I expect that you’ll see a lot of tasks that are either currently running or have completed with names like “{00cb6656-b9a9-4545-9fd0-dc538765be9e}”.  I have yet to find a way to uncover what these tasks are doing, as they only appear in the running tasks pane, don’t seem to correlate to any actual scheduled tasks, don’t send any network traffic that Glasswire could see, and don’t allow any kind of click-through from the Running Tasks interface to the task definition.

I figured that since I post all the time about problems I found a solution to, I’d make a post pointing out something I really never figured out.  Re-installing did fix my alt-tabbing issue, but now I’m deeply curious about these weird Scheduled Tasks.

Cisco AnyConnect – Cryptic Temp Folder Error

As my tagline states, I broke it so you don’t have to.  Recently my Cisco AnyConnect Secure Mobility VPN Client completed an upgrade to the 4.5.00058 version, and after the upgrade any attempt to connect to a VPN would fail with the following error:

Failed to determine valid temporary file folder. Contact your system administrator.

Not the most descriptive of errors.  I tried the simple fixes like removing my preferences .xml and removing any custom profiles, but that didn’t fix it.  I also checked the preferences to see where it was telling Cisco to go for a temp folder, but didn’t find anything pertinent there either.

I resorted to the rip/replace and did a full uninstall, then cleaned all Cisco paths in ProgramData/%AppData%/%LocalAppData%, but the issue persisted even on reinstall of the client after that cleanup.

Since the error did say “temporary file folder”, I went to %temp% and deleted the Cisco directory — an action that requested elevation for some reason.  After deleting the %temp%\Cisco directory, everything worked again.

At some point during the upgrade, the %temp%\Cisco folder was modified so that only elevated processes could successfully read/write — something that broke the AnyConnect VPN client until I resolved it.

Since I googled this error a whole lot and only uncovered a couple of posts referring to an old Mac version of the client, I thought I’d document this in case anyone else had this issue.  It’s a pretty quick fix, all things considered.

Petya/Nyetya and the future of Ransomware

Not to get too soapboxy, but with Petya/Nyetya ransomware hammering the news I’d like to take the time to recommend that anyone in any position of IT authority make sure the following things are in place:

Patch your servers and endpoints consistently — do not lag behind patches by months. The primary (but not only) mechanism for this ransomware spreading is an exploit that Microsoft patched in March of 2017.

Make consistent backups and do not for one second believe that “to another hard drive on the same computer” is a safe place to back up.

Run antivirus or anti-malware software. It’s not a ‘nice to have’ anymore, it’s a requirement for keeping your data secure in the current internet climate. Keep it updated.

Utilize proper role based access controls. Do not grant people Domain Admin rights. Create specialized roles once and apply them as necessary. Domain Admin rights may as well be keys to the full kingdom and are a perfect example of “quick and easy” not being “the right way”.

Never rely on a single thing to protect yourself or your environment. True protection requires multiple layers of defense — e-mail malware protection, network exploit protection, endpoint malware protection, and proper training.

I hope no one I know or their respective employers got hit by this — just like WannaCry, this is a wake up call that spending the time to secure yourself is not an option any more, it is a requirement if you want to protect yourself and your data.

Windows 10 Mail App – Crash at Startup

Last Thursday I (seemingly) randomly started having problems with the Windows 10 Mail application, where it would launch and then crash immediately within 1-3 seconds.  I didn’t recall any changes I had made that could have impacted it, so I started doing some troubleshooting.  First thing was to look at the AppCrash itself:

Faulting application name: HxTsr.exe, version: 16.0.6965.4090, time stamp: 0x5758b3c9
Faulting module name: hxcomm.dll, version: 16.0.6965.4090, time stamp: 0x5758b43f
Exception code: 0xc0000005
Fault offset: 0x000000000035436d
Faulting process id: 0x24e8
Faulting application start time: 0x01d1d2174050de8f
Faulting application path: C:\Program Files\WindowsApps\microsoft.windowscommunicationsapps_17.6965.40901.0_x64__8wekyb3d8bbwe\HxTsr.exe
Faulting module path: C:\Program Files\WindowsApps\microsoft.windowscommunicationsapps_17.6965.40901.0_x64__8wekyb3d8bbwe\hxcomm.dll
Report Id: 322aa185-f761-430a-8e67-211cfc97e616
Faulting package full name: microsoft.windowscommunicationsapps_17.6965.40901.0_x64__8wekyb3d8bbwe
Faulting package-relative application ID: ppleae38af2e007f4358a809ac99a64a67c1

HxTsr.exe is apparently a background process (incorrectly, I believe) associated with Microsoft Office 2016, depending on where you look.  In my experience it’s one of the background processes required for the Windows 10 Mail application — not directly related to Office 2016.  Arguably, that doesn’t really matter for the purpose of this post anyway.

Doing some forum searching, I was able to find 10-15 cases of other people having this problem, but most solutions included refreshing the OS — something I consider to be admitting defeat and use only as an absolute last resort.

I was able to find one forum post that pointed me in the right direction, however, by pointing to the privacy settings.  This reminded me that I had just restricted some privacy settings in the Control Panel.

First thing I did was re-enable app based access to my Contacts, which immediately stopped Mail from crashing at launch.  Now, it put a banner across the top telling me that my Privacy Settings were stopping the App from reading my Calendar.  I then let Apps access my Calendar, and was then informed that my Privacy Settings were stopping the App from accessing / sending / receiving Mail.  I then realized I had somehow decided it would be good to disallow Apps from having Mail access, while using the Mail app as my primary method for sending and receiving e-mail.  I then toggled that back on.

This fixed everything, my Mail app stopped crashing, and everything is back to normal.

The reason this blog post exists is because if you have turned your privacy settings up to the max, Mail no longer generates any level of useful information to inform you as to why it is crashing.  It’s very possible that you’ve taken away the privileges it needs in order to do its job.  Why it required Contact access in order to tell me it had privacy problems, I’ll never know — but at least I got it fixed, and if you’re having this problem as well, at least you know what the cause was.


100% Free SSL Certs

The Linux Foundation has been working on a free SSL certificate generating tool for a while with the assistance of Cisco, Akamai, the EFF, Mozilla, and others.  The key about this is that it is a legitimate SSL certificate generated by a trusted root CA, all for free!

The install process was ridiculously painless and took me less than about 15 minutes from start to finish.  I can’t recommend this highly enough.  It is imperative that people learn about encryption and cryptography and protect their sites and their content with encryption.

What are you waiting for?

Get to it!

E-mail Attachment Security, AKA I shouldn’t have to say this …

But, I do.

Here’s how you can prevent ~90% of malware attacks in your organization.  You, yes you.  The very person reading this.  Regardless of your position or your access, regardless of your function in the business — this absolutely applies to you.  It’s also super easy.

  1. If you get an e-mail with an attachment to it and you didn’t expect it, EVEN if you know the person sending it, DON’T OPEN IT.

Seriously, that’s it.  Call them, confirm it’s legitimate, whatever, just don’t open the e-mail.  It’s crazy how many malware variants ONLY spread by you opening that e-mail attachment.

Remember in the 80s they had the “Don’t Copy That Floppy” tagline?  We need one for the new world.  I can’t come up with anything great that rhymes, so I’ll leave you with a simple question:

“Am I willing to stake my company’s data confidentiality and perhaps reputation on the guess that this unexpected attachment is legitimate?  Or is it easier to just pick up the phone and call the person who sent it to me to validate that it is legitimate?”

I appreciate that it doesn’t quite roll off the tongue, but it’s far more real than people expect!

DISCLAIMER:  I obviously can’t guarantee this will stop 90% of malware attacks in YOUR organization, but I can guarantee it will notably reduce your exposure!  The actual percentage depends on what kind of malware your organization gets hit with on a regular basis.  With that said, most of the deepest impacting malware (ransomware, the T5000/T9000 Skype recording malware) does not spread by itself, it requires user intervention to begin the infection process, and this practice will do wonders to minimizing the potential for impact from that type of malware.

SourceFire IPS/IDS – Automatic Blacklist

One of the things I wanted to automate recently was blacklisting IP addresses outright that attempt exploits and vulnerabilities against a network I am protecting with the Cisco SourceFire IPS/IDS device.  After spending some time working with their correlation rules, I realized that what I wanted to happen was not really available.  Here’s what I’d like the workflow to be:

  1. Someone attempts to exploit vulnerabilities against the public IP address routed through the Cisco SourceFire and generates an Impact 1 or Impact 2 severity intrusion event.
  2. If the same source IP attempts a second exploit vulnerability within 5 minutes that generates an Impact 1 or Impact 2 severity intrusion event, blacklist the source IP address.

This seems like something that should be reasonable to expect the device to inherently support — unfortunately, that seems not to be the case.

I was able to work around the lack of functionality to get somewhat close to the desired outcome by doing the following:

  1. Install the IP Blacklist Remediation module available for the Cisco SourceFire, located here on your SourceFire Defense Center.  NOTE:  This is a third party extension/module to the Cisco SourceFire platform.  Use this at your own risk.  I didn’t write it, I accept no liability whatsoever if you implement it and it sets your data center on fire, sends your corporate secrets to China, etc.
  2. Follow the instructions in the README file to configure the remediation action, instance, security intelligence feed, and access control policy.
    1. Make sure you use full https:// link when you’re providing the .HTML file in the security intelligence feed.  When configuring the remediation instance, you can just say ‘custom_blacklist.html’, but when configuring the security intelligence feed, you need to use ‘https://your.sourcefire.domainorip/custom_blacklist.html’

Once this is done, I got very close to what I wanted:

  1. Someone attempts to exploit vulnerabilities against the public IP address routed through the Cisco SourceFire and generates an Impact 1 or Impact 2 severity intrusion event.
  2. The IP address is added to the Local Blacklist and synchronized at the next Security Intelligence Feed update cycle.

My concern (and what I’m hoping someone out there can comment on) is that this seems overzealous, as it does blacklist every IP that ever tries a single exploit against any of the public IPs, and over time that seems unsustainable.  I’d love to have threshold capability so that it only added IP addresses if they tried multiple exploits.  I mean, the SourceFire *is* dropping the traffic anyway, so blacklisting the IP of anyone who has attempted a single exploit does seem like it will end up with a tremendous amount of IP addresses over time, which will generate unnecessary load on the system.

I also think it doesn’t add up that the SourceFire can’t do this internally with correlation rules and remediation actions, but after hours of searching, I could not come up with another way to achieve this.

Anyone have any ideas?

Ransomware in 2015

As I presently work with a security focus, one of the things I wrote recently is a high level white-paper about ransomware and some information about what it is, where it comes from, and a few key ways to stop it.  The full white paper and content should be published soon at,  but until then I wanted to get the info out all the same.

The persistent threat of ransomware

The last few months have seen a resurgence of the CryptoLocker/Cryptowall ransomware malware across many IT organizations.  This malware is particularly impacting and has cost many companies significant time and money, and in some cases has caused the permanent destruction of business critical information and documents.


Where did it come from and what does it do?

This malware primarily preys on uninformed or untrained security behavior, as it arrives via a Trojan dropper primarily in an e-mail attachment.  For example, the current version masquerades as a resume, “”.

Once executed, the Trojan dropper runs, connects to a command and control server, then downloads the actual encrypting ransomware and executes it.  The ransomware then encrypts all files it has access to (both locally and on explicitly mapped network drives with drive letter associations), and then generates a dialog that informs the user that their files have been encrypted and that they can only decrypt the files if they send an amount of money via Bitcoin to a specific Bitcoin address.  At present, very few of the ransomware variants use encryption that can be decrypted without the purchase of the private key from the ransomware vendor, and as such in most cases the encrypted files and documents must be recovered from backup.  Additionally, there is no guarantee that the ransomware vendor will actually provide the decryption key if the ransom is paid, and the method of payment they request is unable to be cancelled or refunded, and in most cases, unable to be traced.


Persistent, but largely predictable…

The behavior of the existing ransomware variants is all very similar, and as such, simple security steps can largely mitigate the attack risk in an organization.  Ensuring security against these types of threats requires a metered and thoughtful security approach that manages each of the possible ingress points and should be viewed end to end to ensure the confidentiality, integrity, and availability of your organization’s information.


What can you do?

One of the most effective methods of addressing these issues relates to managing the primary ingress point for these types of malware – your user base.  Proper security training and spear phishing training for users will substantially reduce company infection likelihood by limiting the malware’s ingress point via user action and should be completed on a quarterly basis with checks in place to ensure compliance.  Additional means for mitigating the possibility of infection without requiring the purchase of additional software include the implementation of file security policies via GPO that block the execution of specific types of files in malware specific locations.  IT organizations should also use these occurrences as a reason to reassess their backup and recovery process, as utilizing a proper backup regime with defined RPO and RTO that is tested on a frequent basis will ensure that if your environment is infected and ransomware is executed, you will have recent state in time backups to restore from to minimize data loss.  Lastly, malware detection platforms with advanced persistent threat analysis, deep malware protection and packet inspection tools such as Damballa or Cisco SourceFire with AMP can block the execution of the dropper, the execution of the encryption ransomware, and even the command and control connection to the malware vendor at a network and endpoint level.


Windows 10 will help!

Changes in the security behavior of Microsoft Windows in the upcoming Windows 10 release will also take tremendous steps towards removing many of the vulnerabilities and insecure file interaction behaviors that allow for this type of exploit and infection to happen.  New technologies such as the file container model and the virtualization of the primary authentication system that manages Active Directory access tokens severely limit or even fully remove the capabilities of rogue software.  These features work in concert with drive encryption to help protect the confidentiality and integrity of your company’s data by placing each individual file in a sandboxed container that uses Windows as the broker of access control between the file and any other file on the filesystem.  This means that ransomware applications like CryptoLocker will be unable to modify files or folders if explicit access has not been granted via established corporate policy.  The virtualization of the Active Directory authentication layer further protects your organization by ensuring that even if Windows 10 becomes infected with malware, rootkit, or botnet software, the unauthorized application will not have access to any mechanism to retrieve information about or forge authentication against your corporate network.

As mentioned above, administrators can implement a few group policies fairly quickly to help address the ingress points for this type of malware.  Obviously, high level solutions include deep advanced malware protection software, but if you’re on a budget and can’t afford that yet you can still help minimize the likelihood of infection beyond just simple end-user training.  Below you’ll see outlined the steps to take to implement group policy that blocks the execution of the current strands of ransomware by disallowing execution from the temporary directories that it deploys to.

GPO Creation Instructions 

1)      Log in to DC as a Domain Admin

2)      Run GPMC.MSC

3)      Create a new GPO Object and provide a descriptive name (such as AppData Restriction Policy)

4)      Navigate to Computer Configuration -> Policies -> Windows Settings -> Security Settings -> Software Restriction Policies -> Additional Rules

5)      From the Action menu, select “New Path Rule” and enter the following information:

  • Path:     %AppData%\*.exe
  • Security Level:   Disallowed
  • Description:        Block execution of applications from the %AppData% folder

6)      Do the same for the following locations:

  • Path:     %AppData%\*\*.exe
  • Path:     %LocalAppData%\*.exe
  • Path:     %LocalAppData%\*\*.exe
  • Path:     %LocalAppData%\Temp\*.zip\*.exe      (Optional) Blocks the execution of compressed .EXE files from a .ZIP compressed file
  • Path:     %LocalAppData%\Temp\7z*\*.exe        (Optional) Blocks the execution of compressed .EXE files from a .7Z compressed file
  • Path:     %LocalAppData%\Temp\Rar*\*.exe       (Optional) Blocks the execution of compressed .EXE files from a .RAR compressed file
  • Path:     %LocalAppData%\Temp\wz*\*.exe        (Optional) Blocks the execution of compressed .EXE files from a .ZIP compressed file on machines with WinZip installed

7)      Save the GPO and link to the OU that contains the target computer objects.


This policy blocks the execution of applications in a single or double nested subfolder in %AppData% and %LocalAppData%, blocking almost all current ransomware execution locations.  It does, however, impact a few legitimate programs.  We have detailed our known whitelist applications which should also be reviewed and whitelisted in your environment as necessary.


Whitelist Instructions:

  1. Have the user provide you the full path of the .EXE file that is not executing –OR- review the Event Log on the client machine as it will be indicated in the event that records the blocked software execution.
  2. Open the GPO in gpmc.msc (right click -> edit)
  3. Expand Computer Configuration -> Polices -> Windows Settings -> Security -> Software Restriction Policies -> Additional Rules
  4. Right-Click to create a new Path rule.
    1. Path should be the actual EXE file, using the %AppData% or %LocalAppData% variable.  For example “%AppData%\Spotify\Spotify.exe”
    2. Security level should be “Unrestricted”
    3. (Optional, recommended) Description should include what program is being allowed, what user requested it, and on what date it was requested.
  5. Click OK to save the policy, then close out of the GPO.
  6. (If whitelisting in response to user request) Have the end-user complete a gpupdate to receive the latest policy.


Known applications to whitelist:

Office Source Engine Updates (Office 2010 – Office 2013 Click to Run Updates):

  • %LocalAppData%\Temp\ose00000.exe
  • %LocalAppData%\Temp\ose00001.exe
  • %LocalAppData%\Temp\ose00002.exe
  • %LocalAppData%\Temp\ose00003.exe
  • %LocalAppData%\Temp\ose00004.exe
  • %LocalAppData%\Temp\ose00005.exe
  • %LocalAppData%\Temp\ose00006.exe
  • %LocalAppData%\Temp\ose00007.exe
  • %LocalAppData%\Temp\ose00008.exe
  • %LocalAppData%\Temp\ose00009.exe
  • %LocalAppData%\Temp\ose00010.exe

Adobe Flash 12 – 18 updates:

  • %LocalAppData%\Temp\install_flashplayer_12x32ax_gtbd_chrd_dn_aaa_aih.exe
  • %LocalAppData%\Temp\install_flashplayer_13x32ax_gtbd_chrd_dn_aaa_aih.exe
  • %LocalAppData%\Temp\install_flashplayer_14x32ax_gtbd_chrd_dn_aaa_aih.exe
  • %LocalAppData%\Temp\install_flashplayer_15x32ax_gtbd_chrd_dn_aaa_aih.exe
  • %LocalAppData%\Temp\install_flashplayer_16x32ax_gtbd_chrd_dn_aaa_aih.exe
  • %LocalAppData%\Temp\install_flashplayer_17x32ax_gtbd_chrd_dn_aaa_aih.exe
  • %LocalAppData%\Temp\install_flashplayer_18x32ax_gtbd_chrd_dn_aaa_aih.exe
  • %LocalAppData%\Adobe\gccheck.exe
  • %LocalAppData%\Adobe\gtbcheck.exe
  • %LocalAppData%\Adobe\install_flash_player_ax.exe

Microsoft System Center Pre-requisites (Client Push):

  • %LocalAppData%\Temp\vcredist_x86.exe

GoToMeeting Installer:

  • %LocalAppData%\Temp\G2MInstallerExtractor.exe

Mozilla Firefox:

  • %LocalAppData%\Mozilla Firefox\firefox.exe

Cisco WebEx Installer/Uninstaller:

  • %LocalAppData%\atcliun.exe


Powershell Dynamic IP Helper

As an IT guy, it’s very helpful for me to be able to remote to a machine outside of the current network in order to do testing — e.g., if the client is having weird DNS issues or routing issues, or if I’m doing work on a public facing web site.  I’ve got my home machine set up in such a manner that after jumping through a few hoops, I can remotely control it from wherever I am.

I don’t pay for a static IP address on a monthly basis, it seems pretty exorbitantly priced — my present ISP wants $15/mo for the privilege.  That said, I’ve been fairly lucky in that they don’t change my IP address much.  When they do, however, it messes up a few things — as I self-host this blog (among other things), the name server needs to be updated with the new IP address.  It used to be that you could use things like and the like, but at this point all of those have ceased being free, and I never liked the suffix on any of the domain names anyways.

What I did to overcome this was write a small Powershell script that uses one of the public IP check websites, grabs the current IP, and if it has changed since the last time it grabbed it, sends it to me via e-mail.  The next incarnation may make use of my hosting provider’s API to automatically update the DNS entry, but I haven’t gotten that far yet.

I set this script to run as a scheduled task every 30 minutes and it has been serving me well now for over a year and a half, so I figured it may be helpful to someone else.  See below.  If there’s anything odd you feel I did and are curious about, drop a comment and I’ll explain.  Alternately, if there’s a better way to do anything I’ve done, I’d love to learn it — drop some knowledge in the comments section to help me out!

Two prerequisites — first being you must make a credential file and put it in the same directory that the script is executing from, and this file can *easily* be reversed by anyone who grabs a copy of the file.  As such, I don’t recommend using your primary personal e-mail account for this.  This is a pretty minor step, and you only have to do it once — here’s how you do it.  Run powershell and input the following commands:

"Your E-mail Password Goes Here" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "$pwd\credentials.txt"

Second prerequisite is that if you need to create the Event Log source that the script is going to write to — OR comment out the event logging portion of the script as it will throw errors if the log doesn’t exist.  The reason this isn’t in the script is that the script was written to run in non-elevated user context, and creating an event log requires an elevated session.  So, run the following from an elevated/administrator Powershell session to prepare your event log for the events or comment out with a # before each Write-EventLog line:

new-eventlog -source "IP Checker" -logname Application

Then, once you’ve gotten all of the pre-requisites completed, put your username, credential file location, and e-mail address info into the script below and you’ll be off to the races.

#Define credentials for e-mail later on
$username = "your_email_address@goes_here"
$password = cat $pwd\credentials.txt | convertto-securestring
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password

#Remove username and password from memory as they are no longer needed and I'm paranoid.
Clear-Variable username
Clear-Variable password

#Get the old IP from the text file in this directory
$OLDIP = Get-Content $pwd\IP.txt -totalcount 1

#Provide a somewhat useful event to indicate whether the IP.txt was blank or not.
If (!$OLDIP) {
  Write-EventLog -Logname Application -Source "IP Checker" -EntryType Information -EventId 3001 -Message "IP Address not received from IP.txt.  Script will behave as though IP address has changed."

#Get the current IP from
$NEWIP_DIRTY = (Invoke-WebRequest

#If IP was not retrieved, sleep 180 seconds and retry repeatedly until an IP is retrieved.
  Do {
    Write-EventLog -Logname Application -Source "IP Checker" -EntryType Information -EventId 3001 -Message "IP Address not received from  Sleeping for 180 seconds and trying again."
    Start-Sleep -s 180
    $NEWIP_DIRTY = (Invoke-WebRequest
  } while(!$NEWIP_DIRTY)

#Remove the trailing newline character to sanitize the content of the variable for the upcoming test
$NEWIP = $NEWIP_DIRTY.TrimEnd("`n")

#Write information to Event Log for Tracking/troubleshooting
Write-EventLog -Logname Application -Source "IP Checker" -EntryType Information -EventId 3000 -Message "Retrieved old IP from IP.txt: $OLDIP`nCurrent IP after sanitization is: $NEWIP"

#If the IP has changed, e-mail it to me
If($NEWIP -ne $OLDIP) {
  Write-EventLog -Logname Application -Source "IP Checker" -EntryType Information -EventId 3999 -Message "IP flagged as having changed.  Previous IP: $OLDIP, Current IP: $NEWIP"
  Send-MailMessage -SmtpServer -Port 587 -To "target@email.address" -Subject "New IP Address!" -Body "IP Address has changed.  Previous IP: $OLDIP, current IP: $NEWIP" -From "from@email.address" -UseSsl -Credential $cred
  Out-File -filepath $pwd\IP.txt -InputObject $NEWIP

© 2019 TJ in IT

Theme by Anders NorénUp ↑