Monday 9 December 2013

Powershell script to get last login of a host in a readable format for humans


---------Start Script------------------

# Gets host and lastLogonTimestamp in UTC of specified host

# Get hostname
$hostname = Read-host "Enter a hostname"

# find the lastLogonTimestamp attribute
Get-ADComputer $hostname -Properties lastlogontimestamp |

# output hostname and timestamp in human readable format
Select-Object Name,@{Name="Stamp"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp)}}
pause


------------End Script---------------

Wednesday 27 November 2013

Get specific properties with Get-ADUser and exporting to CSV

At some point we all need to obtain specific data of users to further analyze.
With this PS script you can get a specific data from a certain OU and export to csv.

Get-ADUser -Filter * -searchbase 'ou=your_ou_name,dc=yourdomain,dc=yourdomain' -Properties * | Select-Object Name, Pager | export-CSVresults.csv -NoTypeInformation -Encoding UTF8

With this script I can get the user name and the pager number on a CSV.
You can find what the objects you can use by using: Get-ADUser -Filter * -Properties *
Be aware it will display all users. So Ctrl+c in the middle of and search for your desired field. Or restrict your search base.
The file will appear on the path displayed on the powershell cmd when you open it.

Thursday 17 October 2013

CryptoLocker Malware

Since there is allready lots of info about this malware in English I am providing a few info in Portuguese:

Está a circular na internet um novo tipo de malware, neste caso um ramsonware. Entitulado de Cryptolocker.

Como é que fico infectado?

1.      Por emails falsos que fingem ser da UPS, Fedex, DHL, etc a indicar que temos uma encomenda à espera de ser recebida ou algo do género.
2.      Através de sites que estejam vulneráveis a este tipo de infecção.
3.      Através de Trojans que fingem ser programas necessários para ver videos online, típicamente encontrados em sites Porno e de SportTV online.

O que acontece quando fico infectado?

Uma vez activa a infecção no computador vai percorrer as drives (locais e de rede) e encriptar os seguintes tipos de ficheiros com uma mistura de encriptação RSA e AES: *.odt, *.ods, *.odp, *.odm, *.odc, *.odb, *.doc, *.docx, *.docm, *.wps, *.xls, *.xlsx, *.xlsm, *.xlsb, *.xlk, *.ppt, *.pptx, *.pptm, *.mdb, *.accdb, *.pst, *.dwg, *.dxf, *.dxg, *.wpd, *.rtf, *.wb2, *.mdf, *.dbf, *.psd, *.pdd, *.eps, *.ai, *.indd, *.cdr, ????????.jpg, ????????.jpe, img_*.jpg, *.dng, *.3fr, *.arw, *.srf, *.sr2, *.bay, *.crw, *.cr2, *.dcr, *.kdc, *.erf, *.mef, *.mrw, *.nef, *.nrw, *.orf, *.raf, *.raw, *.rwl, *.rw2, *.r3d, *.ptx, *.pef, *.srw, *.x3f, *.der, *.cer, *.crt, *.pem, *.pfx, *.p12, *.p7b, *.p7cThe

Após um tempo, tipicamente o tempo que demora a encriptar os ficheiros aparecerá uma janela semelhante a esta abaixo, que vai pedir um resgate de 100 ou 300 US$. O pagamento pode ser feito por Bitcoins, Moneypack, Ukash ou CashU. E aparecerá uma contagem decrescente para o fazer!



Há alguma forma de recuperar os ficheiros?

Infelizmente não. Desencriptação por força bruta não é possível no tempo que é disponibilizado e todas as ferramentas que têm surgido têm-se revelado ineficazes.

A única forma de não ser infectado por este e outro tipo de malware é usar o bom senso e não abrir emails suspeitos, sites, etc.
No caso de se ter sido infectado a única forma de recuperar os ficheiros é através de backups que tenham sido feitos.



Monday 30 September 2013

VMWare: unable to connect to the mks login (username/password) incorrect

This error can present while opening a console for a virtual machine.
There can be several reasons for this error, but what I have encontered the most is a DNS problem.
Check if you can ping the VMWare hosts and the Vcenter server by their name, if not add them to the DNS.

Just like that, no firewall issues or editing vmware config files.


Tuesday 24 September 2013

Windows 8 Black Screen / Flickering on boot with dual VGA (Intel HD Graphics & Geforce)

This happened to me on my desktop whith a Asus P8Z68-V motherboard.
I have 3 monitors and so I needed a second VGA for the two secondary monitors.
I had an old Geforce 8400GS laying around and so I decided to use it.

I wanted my main VGA to be the onboard Intel that amazingly has better performance. So I setted up on Bios as main VGA.
All went fine until MS did their number... Windows update changed the Graphics adapter driver.
I was unsuspected of that until I rebooted the pc. The log on screen was not to be seen but only a black flickering screen. So after some trial and error here is what I did.

I went to the bios and changed the main VGA to be the Nvidia. Booted normaly. I found out after many tries that Windows keeps getting the Nvidia driver from the internet regardless if I disabled that option in Windows Update.
So you need to Run "gpedit.msc" and go to: Computer Configuration - Administrative Templates - System - Internet Communication Management - Internet Communication Settings - "Turn off Windows Update Device Driver Searching" and set this to ENABLED.

Download the latest Nvidia driver, run the installer, let it extract the driver and then cancel it.
Delete all Nvidia folders on program files.
Go to safe mode, uninstall the device in device management and make sure to tick the option to delete the driver.
In the windows folder search for the usual Nvidia files such as nvdisp.ini, make a search for Nvidia and nv*.* and delete everything related to Nvidia.

Reboot.

On Device Manager, your Display adapter should appear as "Microsoft Display Adapter" instead of the WDDM drivers for your card model. If not you must retrace the steps.

Right click the "Microsoft Display Adapter" and hit "Update Driver Software". Select "Browse my computer for driver software", then "Let me pick from a list of device drivers on my computer" and then select the "Have Disc" option.
Point Windows to the file "nv_disp.inf" that will be in your Nvidia folder, mine was: C:\NVIDIA\DisplayDriver\327.23\Win8_WinVista_Win7_64\International\Display.Driver\nv_disp.inf

Reboot, set your Intel VGA has main adapter once more and pray for uncle Bill for it to work.
And that should be it.

Hope it helps someone lost on the interwebs with the same issue as I.

Thursday 25 July 2013

WARNING: 5 reasons you should never fix a computer for free

(I am not the author of the text but I fully agree with it)

It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul.
We love the accolades. We love to be seen as the digital white knight fixed the server, the computer, the email, and anything else that life depends on.
We love it so much, we sometimes make horrible decisions. Sometimes, we work "FOR FREE."
We've all done it. A friend, a neighbor, a relative, a good client, a bad client, a pretty girl... Whoever it was, and for whatever reason, we all threw them a technological bone and fixed something for free. In rare instances, it can be a rewarding experience. Perhaps your buddy gave you a beer. Maybe someone said thank you. Maybe there was a smile on their face, and that was rewarding enough.
More likely, however, that five minute task you thought you were signing up for turned into 40 minutes, then an hour, then a commitment. Wow. You didn't see that coming.

1 You Break it You Bought it.
When you sit down to fix a problem that presented as a simple one you are creating a contract. Not a legal contract, but a social one. The computer owner is trusting their computer with you. It's their baby, and you're the doctor. So you sit down, and begin to fix a problem.
In the process, something else breaks. You fixed one thing, but something else goes awry. What's the best part? Neither you nor the user notice it is broken until a day later when they call you to blame you for breaking something else.
"I thought you were going to fix it." They complain.
This is the primary reason you charge money to fix something. You break it, you bought it. The user / owner will expect you to warranty your service even though THEY received all the value of your time, and you received nothing in exchange.

2 People don't respect things that are free.
People don't respect things that are free.
I learned that quote from a man who runs a non-profit organization. Image that. A man who solicits donations for a living candidly told me "people don't respect things that are free." You know what? He's right.
Free advice. Free upgrade. Free entry. None are valued. Free advice is seldom wanted. Free upgrade was something you were going to get anyway. Free entry? The band playing tonight must not be any good.
People associate the value of service with the amount of money that is exchanged for it. How else do you think that lawyer can get away with charging $400 an hour? People naturally make the assumption that if it costs an arm and a leg, then it must be worth it.
So, if customers and friends will assume that the most expensive car is the best one, what will they assume of the free car? Do you want the heart surgeon who charges $500,000 per surgery or the one who works for beer to operate on your mother?

3 They will expect it forever.
In law, the concept of a precedent is vitally important. Judges and lawyers look to previous cases to decide what the interpretation of the law was because if a case was settled one way before, chances are, it will be settled that way again.
Gamblers playing craps look at the past behavior of the dice to, mistakenly, assume that the good luck will continue.
Users will figure if you fixed it once for free, you'll do it forever for free. There is no reason why they should respect the thousands of hours you have spent learning and researching the art of computer science. There is no reason that they should respect the certifications you hold. There is no reason that they should honor your abilities by paying your fees. Why? Because you did it for free. Once!
When they come back and you try to get fees, they will meet you with resistance in the form of guilt. "I thought we were friends" they cry. "You didn't charge me anything last time." They argue.
Setup the expectation that they are going to pay (or barter) from the onset. Demand the respect that you deserve. Make sure they understand you are a professional. After all, that is the difference between a professional and an amateur. Professionals get compensated for their skills.

4 The demands will only grow with time.
Give them an inch, and they will take you through three operating system upgrades, two virus infections, and a crashed hard drive. Once you've set the precedent and created the expectation that you are their knight in shining armor, they will begin to call you for everything. They will suck up your time and resources. They will not be grateful. They will involve you in 30 minute hypothetical conversations then disagree with your expertise.

5 It Weakens Your Backbone
Working for free is not only unprofitable, it weakens your constitution as a professional consultant. For many consultants, asking for money is difficult. They email out a silent invoice after the fact and hope they get paid. This practice can lead to unbalanced books, debt, and a going out of business sign. The simple fact is: if you don't ask for your money, you're not going to get paid. No one just hands out checks.
Setting up the expectation, especially when you fix a computer for the first time for a client, is vitally important in establishing boundaries that ensure you are paid in a timely fashion. Working for free, throwing out freebies, "comp"-ing your time hurts your ability to ask for the sale. It hurts your credibility because the client will assume that if you're not charging them for a given task, you didn't know what you were doing or you made mistakes.
It may give you butterflies, but ask for the money. Do it openly and notoriously. Your clients will take it as a sign of confidence.

Wednesday 24 July 2013

Sysadmin day 26-07-2013

Don't forget to hug yours, every year at least


Remote registry edition of Hkey Current User

Lets say you need to edit the registry of a currently logged on user but that user has no administration rights. You would need to grant the local admin rights, log off and log on.
With this simple trick you can edit the current user registry:


1. Open a regedit with domain admin rights




















2. On the File menu, click Connect Network Registry.
















3. In the Select Computer dialog box, type the name of the computer to whose registry you want to connect
4. Navigate to HKEY_USERS and look for the longest key without "_Classes" in front. That will be the current logged on user HKEY_CURRENT_USER.
















This way you can edit the reg keys you need without logging out the non local admin user.

Remove proxy option tick in Internet Explorer

If you had a GPO applying a proxy option, but you no longer use a proxy, by disabling that option in a GPO it wont remove the tick option in Internet Explorer. So run this script on user logon (with a GPO), copy and paste on a notepad and save with .vbs extension.
Place the script on your DC netlogon or a available share.


Option Explicit

dim strRegPath
dim user
dim password
dim sh
dim oWshShell
dim message

strRegPath = "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\"
Set oWshShell = CreateObject("WScript.Shell")
set sh = createobject("wscript.shell")

Call oWshShell.RegWrite(strRegPath & "ProxyEnable", "00000000", "REG_DWORD")

Set oWshShell = Nothing
Set sh = Nothing

Change permissions to NTFS folders using the folder name



I found this script online, but had several bugs and was fixed by me and a coworker.
The purpose is to change the NTFS permissions on several folders using the folder name as basis. 
You must have your username the same as the folder. 
It propagates to the child objects. But you can mess around with the options a bit. 
Please test before, as always, and adjust the folders and options to your enviroment.

You must use powershell in v2 otherwise it wont work.


#############################################################################
# Script: changePermissions.ps1
# Date: 17/07/2013
# Keywords:
# Comments:
# Pre-Requisites: Full Control over destination folder.
#
#
# DISCLAIMER
# ==========
# THIS CODE IS MADE AVAILABLE AS IS, WITHOUT WARRANTY OF ANY KIND. THE ENTIRE
# RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS CODE REMAINS WITH THE USER.
#############################################################################
#############################################################################
#            Variables
#
# Where is the root of the home drives?
$homeDrivesDir="inserthomedrivehere"
# Report only? ($false = fix problems)
$reportMode = $false
# Print all valid directories?
$verbose = $false
# What domain are your users in?
$domainName = "insertdomainhere"
#
#######################################################################
# Save the current working directory before we change it (purely for convenience)
pushd .
# Change to the location of the home drives
set-location $homeDrivesDir
# Warn the user if we will be fixing or just reporting on problems
write-host ""
if ($reportMode) {
 Write-Host "Report mode is on. Not fixing problems"
} else {
 Write-Host "Report mode is off. Will fix problems"
}
write-host ""
# Initialise a few counter variables. Only useful for multiple executions from the same session
$goodPermissions = $unfixablePermissions = $fixedPermissions = $badPermissions = 0
$failedFolders = @()
# For every folder in the $homeDrivesDir folder
foreach($homeFolder in (Get-ChildItem $homeDrivesDir | Where {$_.psIsContainer -eq $true})) {
 # dump the current ACL in a variable
$acl= (Get-Item $homeFolder).GetAccessControl("Access")
 #$Acl = Get-Acl $homeFolder
 # create a permission mask in the form of DOMAIN\Username where Username=foldername
 #    (adjust as necessary if your home folders are not exactly your usernames)
 $compareString = "*" + $domainName + "\" + $homeFolder.Name + " Allow  FullControl*"
 # if the permission mask is in the ACL
 if ($Acl.AccessToString -like $compareString) {
 # everything's good, increment the counter and move on.
 if ($verbose) {Write-Host "Permissions are valid for" $homeFolder.Name -backgroundcolor green -foregroundcolor white}
 $goodPermissions += 1
 } else {
 # Permissions are invalid, either fix or report
 # increment the number of permissions needing repair
 $badPermissions += 1
 # if we're in report mode
 if ($reportMode -eq $true) {
 # reportmode is on, don't do anything
 Write-Host "Permissions not valid for" $homeFolder.Name -backgroundcolor red -foregroundcolor white
 } else {
 # reportmode is off, fix the permissions
 Write-Host "Setting permissions for" $homeFolder.Name -foregroundcolor white -backgroundcolor red
 # Add the user in format DOMAIN\Username
 $username = $domainName + "\" + $homeFolder.Name
 # Grant the user full control
 $accessLevel = "FullControl"
 # Should permissions be inherited from above?
 $inheritanceFlags = "ContainerInherit, ObjectInherit"
 #$inheritanceFlags = "None"
# Should permissions propagate to below?
 $propagationFlags = "None"
 # Is this an Allow/Deny entry?
 $accessControlType = "Allow"
 try {
 # Create the Access Rule
 $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($username,$accessLevel,$inheritanceFlags,$propagationFlags,$accessControlType)
 # Attempt to apply the access rule to the ACL
 $Acl.SetAccessRule($accessRule)
 Set-Acl $homeFolder $Acl
 # if it hasn't errored out by now, increment the counter
 $fixedPermissions += 1
 } catch {
 # It failed!
 # Increment the fail count
 $unfixablePermissions += 1
 # and add the folder to the list of failed folders
 $failedFolders += $homeFolder
 }
 } #/if
 } #/if
} #/foreach
# Print out a summary
Write-Host ""
Write-Host $goodPermissions "valid permissions"
Write-Host $badPermissions "permissions needing repair"
if ($reportMode -eq $false) {Write-Host $fixedPermissions "permissions fixed"}
if ($unfixablePermissions -gt 0) {
 Write-Host $unfixablePermissions "ACLs could not be repaired."
 foreach ($folder in $failedFolders) {Write-Host " -" $folder}
}
# Cleanup

popd

Internet Explorer 10 lost advanced tab in Windows 7 with all users

I had an issue with a IE10 that had no advanced tab available. No GPO was disabling it, no local restriction, user was local admin.
Oh, and every single user that logged on that machine would had no advanced tab as well.

After fiddling with it for hours, the only solution was to import the following registry key from another pc with same operating system (Win7 64bit with IE 10) to that pc.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer

Export from the working registry and import in the problematic pc. No need to mention to backup the registry before.
It worked for me.