Administration système, Debian, Linux
PSAD top ports et top sigs attaqués sur deux mois
Voici les ports les plus attaqués et protégés par PSAD sur deux mois, c’est intéressant de voir quels services sont le plus attaqués en général. Il y a beaucoup d’attaques malgré que ce serveur n’héberge pas beaucoup de services… # Top scanned TCP ports: tcp 22 1544 tcp 3128 1266 tcp 23 452 tcp 4321 410 tcp 1433 394 tcp 8080 324 tcp 3306 324 tcp 3389 209 tcp 445 196 tcp 9999 163 tcp 5000 138 tcp 80 129 tcp 139 125 tcp 25 104 tcp 21320 93 tcp 21 90 tcp 18186 89 tcp 0 88 tcp 4899 68 tcp 5900 59 tcp 135 43 tcp 110 39 tcp 1080 34 tcp 8081 32 tcp 9090 25 tcp 8088 25 tcp 1521 24 tcp 1723 22 tcp 808 22 tcp 8180 20 tcp 8181 20 tcp 7778 17 tcp 5901 16 tcp 8022 16 tcp 2222 16 tcp 8443 16 tcp 8888 16 tcp 11211 12 tcp 79 11 tcp 49152 11 tcp 84 10 tcp 9200 9 tcp 8089 9 tcp 2244 9 tcp 102 9 tcp 502 9 tcp 6305 9 tcp 1998 9 tcp 8834 9 tcp 465 8 tcp 771 8 tcp 8000 7…
Read MorePowershell, Windows
Powershell encryption decryption
Deux méthodes pour encrypter/decrypter une variable: $MyPswd = « password1234 » ConvertTo-SecureString $MyPswd -AsPlainText -Force | ConvertFrom-SecureString | Out-File -FilePath « $chemin\pass.txt » $password = Get-Content « $chemin\pass.txt » | ConvertTo-SecureString $bPswd = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password) $pswd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bPswd) Write-Host $pswd rm « $chemin\pass.txt » Add-Type -assembly System.Security $passwordBytes = [System.Text.Encoding]::Unicode.GetBytes(« Open Sesame ») $entropy = [byte[]](1,2,3,4,5) $encrytpedData = [System.Security.Cryptography.ProtectedData]::Protect($passwordBytes, $entropy, ‘CurrentUser’) $encrytpedData | Set-Content -enc byte .\password.bin $encrytpedData = Get-Content -enc byte .\password.bin $unencrytpedData = [System.Security.Cryptography.ProtectedData]::Unprotect( $encrytpedData, $entropy, ‘CurrentUser’) $password = [System.Text.Encoding]::Unicode.GetString($unencrytpedData) $password function Set-Key { param([string]$string) $length = $string.length $pad = 32-$length if (($length -lt 16) -or ($length -gt 32)) {Throw « String must be between 16 and 32 characters »} $encoding = New-Object System.Text.ASCIIEncoding $bytes = $encoding.GetBytes($string + « 0 » * $pad) return $bytes } function Set-EncryptedData { param($key,[string]$plainText) $securestring = new-object System.Security.SecureString $chars = $plainText.toCharArray() foreach ($char in $chars) {$secureString.AppendChar($char)} $encryptedData = ConvertFrom-SecureString -SecureString $secureString -Key $key return $encryptedData } function Get-EncryptedData { param($key,$data) $data | ConvertTo-SecureString -key $key | ForEach-Object {[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($_))} } #Encrypt $plainText = « Some Super Secret Password » $key = Set-Key « AGoodKeyThatNoOneElseWillKnow » $encryptedTextThatIcouldSaveToFile = Set-EncryptedData -key $key -plainText $plaintext $encryptedTextThatIcouldSaveToFile #Decrypt $DecryptedText = Get-EncryptedData -data $encryptedTextThatIcouldSaveToFile -key $key $DecryptedText Voilà vous pouvez encrypter vos données sensibles…
Read MoreAdministration système, Asterisk, Linux
Asterisk Installation à partir sources + meetme sur Debian 7
Installation d’une Debian 7 classique On fait un update du système et un upgrade avant toute opération : apt-get update apt-get upgrade On installe les outils nécessaires à la compilation d’Asterisk : apt-get install gcc make pkg-config build-essential wget libssl-dev libncurses5-dev libnewt-dev libxml2-dev linux-headers-$(uname -r) uuid-dev libsqlite3-dev libjansson-dev On installe un serveur de temps : apt-get install ntp On installe mpg123 pour jouer les musiques d’attentes en mp3 : apt-get install mpg123 On installe subversion pour la compatibilité avec le script “get_mp3_source.sh” : apt-get install subversion On installe un serveur mail pour l’envoi des messages : apt-get install postfix On crée un dossier pour accueillir les sources : mkdir /usr/src/asterisk cd /usr/src/asterisk On commence par installer DAHDI pour le support des conférences (meetme) : Téléchargement de l’archive : wget http://downloads.asterisk.org/pub/telephony/dahdi-linux-complete/dahdi-linux-complete-current.tar.gz On décompresse : tar –xvzf dahdi-linux-complete-current.tar.gz cd dahdi-linux-complete-2.9.1.1+2.9.1/ Et on compile: make make install make config On fini par démarrer le driver dahdi /etc/init.d/dahdi start Installation Asterisk cd /usr/src/asterisk/ Téléchargement de l’archive: wget http://downloads.asterisk.org/pub/telephony/asterisk/asterisk-12-current.tar.gz On décompresse : tar –xvzf asterisk-12-current.tar.gz cd asterisk-12.0.0/ Support MP3 on lance le script « get_mp3_source.sh » (le script utilise svn) : ./contrib/scripts/get_mp3_source.sh ./configure Ensuite « make menuselect » va permettre d’ajouter ces composants : make…
Read MoreAdministration système, Asterisk, Linux
Asterisk Securisation Minimale OBLIGATOIRE
Lorsque votre serveur Asterisk se retrouve sur internet il ne faut pas attendre une heure pour voir ce type de logs: [May 13 06:55:20] NOTICE[24030][C-0000002f] chan_sip.c: Call from » (195.154.181.177:5070) to extension ‘0972599900664’ rejected because extension not found in context ‘default’. [May 13 07:01:55] NOTICE[24030][C-00000030] chan_sip.c: Call from » (5.11.40.147:10020) to extension ‘00972595797509’ rejected because extension not found in context ‘default’. [May 13 07:01:56] NOTICE[24030][C-00000031] chan_sip.c: Call from » (5.11.40.147:10025) to extension ‘900972595797509’ rejected because extension not found in context ‘default’. [May 13 07:01:57] NOTICE[24030][C-00000032] chan_sip.c: Call from » (5.11.40.147:10027) to extension ‘000972595797509’ rejected because extension not found in context ‘default’. Ce sont des tentatives d’appel à des numéros sûrement surtaxés. Les attaquants utilisent le contexte “default” donc en première sécurité il convient de ne pas utiliser ce contexte (les appels échouent) Donc on met un petit pare feu pour éviter tout ça (changer xx par votre port SSH et l’IP de votre provider SIP): # Vider les tables actuelles iptables -t filter -F iptables -t filter -X # Interdire toute connexion entrante iptables -t filter -P INPUT DROP iptables -t filter -P OUTPUT DROP iptables -t filter -P FORWARD DROP # Ne pas casser les connexions établies iptables -A…
Read MorePowershell, Windows
Powershell envoyer un email
Envoyer un email avec Powershell: $attachfile = New-Item -type file -force « $chemin\attachment.txt » Write-Output « attachment file example » | Out-File -Append $attachfile $to = « name@domain.com » $from = « name@domain.com » $smtp = « 192.168.1.1 » $subject = « Subject » $body = « Body » Send-MailMessage -to $to -From $from -Attachments « $chemin\attachment.txt » -SmtpServer $smtp -Subject $subject -Body $body rm « $chemin\attachment.txt » Assez simple finalement !
Read MorePowershell, Windows
Powershell comparaison de fichier
Une petie comparaison de fichier pour faire apparaître les différences et similitudes: $file1 = « $chemin\left.txt » $file2 = « $chemin\right.txt » Write-Output « equalite » | Out-File -Append $file1 Write-Output « equal » | Out-File -Append $file1 Write-Output « diff1 » | Out-File -Append $file1 Write-Output « equalite » | Out-File -Append $file2 Write-Output « equal » | Out-File -Append $file2 Write-Output « diff2 » | Out-File -Append $file2 Compare-Object $(Get-Content « left.txt ») $(Get-Content « right.txt ») -IncludeEqual | Where {$_.SideIndicator -eq ‘==’} | ForEach-Object {$_.InputObject} | Out-File « result_equal.txt » Compare-Object $(Get-Content « left.txt ») $(Get-Content « right.txt ») -IncludeEqual | Where {$_.SideIndicator -eq ‘=>’} | ForEach-Object {$_.InputObject} | Out-File « result_right.txt » Compare-Object $(Get-Content « left.txt ») $(Get-Content « right.txt ») -IncludeEqual | Where {$_.SideIndicator -eq ‘<=’} | ForEach-Object {$_.InputObject} | Out-File « result_left.txt » $compequal = gc « result_equal.txt » $compleft = gc « result_left.txt » $compright = gc « result_right.txt » $context = Get-Content $file1 | Select-String equalite -Context 2 Write-host $context Write-Host « Comparaison ==: » $compequal Write-Host « Comparaison:=> » $compleft Write-Host « Comparaison:<= » $compright rm « left.txt » rm « right.txt » rm « result_equal.txt » rm « result_right.txt » rm « result_left.txt » Très pratique !
Read MorePowershell, Windows
Powershell sorting de fichier
Petit aperçu du sorting de fichier: $createsortfile = New-Item -type file -force « $chemin\sort.txt » Write-Output « chiffre;lettre;date » | Out-File -Append $createsortfile Write-Output « 10;a;2012-04-05 » | Out-File -Append $createsortfile Write-Output « 11;z;2012-04-01 » | Out-File -Append $createsortfile Write-Output « 13;b;2012-04-02 » | Out-File -Append $createsortfile Import-csv « $chemin\sort.txt » -delimiter « ; » | sort-object date,lettre | export-csv « $chemin\sort.csv » $resultsort = gc « $chemin\sort.csv » Write-Host $resultsort rm « $chemin\sort.* » ça reste simple comme exemple, on est d’accord…
Read MoreAdministration système, Linux
Bash sécuriser un site web rapidement
Tout simplement; on set les droits et les propriétaires récursivement sur le dossier /var/www chown www-data:www-data /var/www -R cd /var/www/ find . -type f -exec chmod 0644 {} \; && find . -type d -exec chmod 0755 {} \; Voilà avec mod-security en plus, et vos fichiers de configuration en dehors de /var/www comme dans /var/mesfichiersdeconf ça devrait aller…
Read MoreAdministration système, Powershell, Windows
Lancer un pool de 100 ping (ou autre ou +/-…)
Lancer des Threads en background avec powershell $job = @(0..100) for ($i =0; $i -lt 100; $i++){ $job[$i] = start-job { ping 127.0.0.1 } }
Read MoreAdministration système, Powershell, Windows
Variables Réservées
Variables inutilisables car réservées par le système: $PID $Profile $NestedPromptLevel $MyInvocation $LastExitCode $Host $Home $ExecutionContext $Event $Error $ConsoleFileName $^ $? $$
Read MoreAdministration système, Powershell, Windows
Parsing Ping Results
Exemple pour parser le résultat d’un ping; $a = ping 127.0.0.1 | Select-String « Paquets » $b = $a.ToString() $c= $b.Substring($b.IndexOf(« envoyés = « )+10,1) $d= $b.Substring($b.IndexOf(« reçus = « )+8,1) $e= $b.Substring($b.IndexOf(« perdus = « )+9,1) Write-Host « nombre de ping OK = $c » Write-Host « nombre de ping KO = $d » Write-Host « nombre de ping Perdu = $e » TTL moyen: $a2 = ping 127.0.0.1 | Select-String « Réponse » $i = 0 $total = 0 foreach ($ligne in $a2) { Write-Host $ligne; $ttl = $ligne.ToString().Substring($ligne.ToString().IndexOf(« TTL= »)+4,3) -as [int]; $total = $total + $ttl; $i++; Write-Host $ttl } $ttlmedium = $total/$i Write-Host « TTL medium = $ttlmedium » Enjoy !!
Read MoreAdministration système, Powershell, Windows
Information sur l’OS
Quelques informations intéressantes: $result = Get-WmiObject Win32_OperatingSystem -computer localhost $resultsvc = Get-WmiObject win32_service -computer localhost $servicepack = $result.servicepackmajorversion $version = $result.Version Write-Host $version Write-Host $servicepack Write-Host $resultsvc Dernier boot: Get-WmiObject Win32_OperatingSystem | select @{Name= »BootTime » Expression={$_.ConvertToDateTime($_.LastBootUpTime)}} Taille de tous les disques: $dsk= Get-WmiObject Win32_LogicalDisk « Drive Letter Size GB » foreach ( $drive in $dsk ) { « Drive = » + $drive.Name + ` » Size = » + [int]($drive.Size/1073741824)} Date d’installation de l’OS: ([WMI] »).ConvertToDateTime((Get-WmiObject Win32_OperatingSystem).InstallDate) Enjoy !!
Read MoreAdministration système, Powershell, Windows
Envoyer un email
Voilà comment envoyer un Email avec pièce jointe: $attachfile = New-Item -type file -force « C:\attachment.txt » Write-Output « attachment file example » | Out-File -Append $attachfile $to = « admin@exatek.fr » $from = « admin2@exatek.fr » $smtp = « 127.0.0.1 » $subject = « Subject » $body = « Body » Send-MailMessage -to $to -From $from -Attachments « C:\attachment.txt » -SmtpServer $smtp -Subject $subject -Body $body Enjoy !!
Read MoreAdministration système, Powershell, Windows
Lecteur réseau
Monter/Démonter un lecteur réseau: $net = new-object -ComObject WScript.Network $net.MapNetworkDrive(« L: », « \\NOM_MACHINE\d$ », $false, « User », « Password ») Set-Location L: $dir = gci . Write-Host $dir Set-Location $chemin $lectest = Get-PSDrive | Where {$_.Name -eq « L »} if ($lectest -ne $null) { $net = new-object -ComObject WScript.Network $net.RemoveNetworkDrive(« L: », $true) } Enjoy !!
Read MoreAdministration système, Powershell, Windows
PoSH substring
Exemples différents d’utilisation de « substring » $install =”foo_Install” $pos = $install.IndexOf(« Install ») $leftPart = $install.Substring(0, $pos) Write-Host $leftPart $rightPart = $install.Substring($pos+1) $leng = $install.Length $installtrimbylenght = $install.Substring($leng-7) Write-Host $installtrimbylenght $split = $install.Split(« _ ») Write-Host « partie 1: « $split[0] Write-Host « partie 2: « $split[1] $installreplace = $install.Replace(« _ », »@ ») Write-Host $installreplace
Read MoreAdministration système, Powershell, Windows
Encryption des mots de passe
Première méthode : $MyPswd = « password1234 » $chemin = « C:\ » ConvertTo-SecureString $MyPswd -AsPlainText -Force | ConvertFrom-SecureString | Out-File -FilePath « $chemin\pass.txt » $password = Get-Content « $chemin\pass.txt » | ConvertTo-SecureString $bPswd = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password) $pswd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bPswd) Write-Host $pswd rm « $chemin\pass.txt » Deuxième méthode: # Stick password into DPAPI storage once – accessible only by current user Add-Type -assembly System.Security $passwordBytes = [System.Text.Encoding]::Unicode.GetBytes(« Open Sesame ») $entropy = [byte[]](1,2,3,4,5) $encrytpedData = [System.Security.Cryptography.ProtectedData]::Protect($passwordBytes, $entropy, ‘CurrentUser’) $encrytpedData | Set-Content -enc byte .\password.bin # Retrieve and decrypted password $encrytpedData = Get-Content -enc byte .\password.bin $unencrytpedData = [System.Security.Cryptography.ProtectedData]::Unprotect( $encrytpedData, $entropy, ‘CurrentUser’) $password = [System.Text.Encoding]::Unicode.GetString($unencrytpedData) $password Troisième méthode: function Set-Key { param([string]$string) $length = $string.length $pad = 32-$length if (($length -lt 16) -or ($length -gt 32)) {Throw « String must be between 16 and 32 characters »} $encoding = New-Object System.Text.ASCIIEncoding $bytes = $encoding.GetBytes($string + « 0 » * $pad) return $bytes } function Set-EncryptedData { param($key,[string]$plainText) $securestring = new-object System.Security.SecureString $chars = $plainText.toCharArray() foreach ($char in $chars) {$secureString.AppendChar($char)} $encryptedData = ConvertFrom-SecureString -SecureString $secureString -Key $key return $encryptedData } function Get-EncryptedData { param($key,$data) $data | ConvertTo-SecureString -key $key | ForEach-Object {[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($_))} } #Encrypt $plainText = « Some Super Secret Password » $key = Set-Key « AGoodKeyThatNoOneElseWillKnow » $encryptedTextThatIcouldSaveToFile = Set-EncryptedData -key $key -plainText $plaintext $encryptedTextThatIcouldSaveToFile #Decrypt $DecryptedText = Get-EncryptedData -data $encryptedTextThatIcouldSaveToFile -key…
Read MoreAdministration système, Powershell, Windows
Comparaison de fichiers
Petits exemples de comparaisons de fichiers: $chemin = « C:\ » $file1 = « $chemin\left.txt » $file2 = « $chemin\right.txt » Write-Output « equalite » | Out-File -Append $file1 Write-Output « equal » | Out-File -Append $file1 Write-Output « diff1 » | Out-File -Append $file1 Write-Output « equalite » | Out-File -Append $file2 Write-Output « equal » | Out-File -Append $file2 Write-Output « diff2 » | Out-File -Append $file2 Compare-Object $(Get-Content « left.txt ») $(Get-Content « right.txt ») -IncludeEqual | Where {$_.SideIndicator -eq ‘==’} | ForEach-Object {$_.InputObject} | Out-File « result_equal.txt » Compare-Object $(Get-Content « left.txt ») $(Get-Content « right.txt ») -IncludeEqual | Where {$_.SideIndicator -eq ‘=>’} | ForEach-Object {$_.InputObject} | Out-File « result_right.txt » Compare-Object $(Get-Content « left.txt ») $(Get-Content « right.txt ») -IncludeEqual | Where {$_.SideIndicator -eq ‘<=’} | ForEach-Object {$_.InputObject} | Out-File « result_left.txt » $compequal = gc « result_equal.txt » $compleft = gc « result_left.txt » $compright = gc « result_right.txt » $context = Get-Content $file1 | Select-String equalite -Context 2 Write-host $context Write-Host « Comparaison ==: » $compequal Write-Host « Comparaison:=> » $compleft Write-Host « Comparaison:<= » $compright rm « left.txt » rm « right.txt » rm « result_equal.txt » rm « result_right.txt » rm « result_left.txt »
Read MoreAdministration système, Powershell, Windows
Traiter des dates
Formatage de date: $datestring = Get-Date -uformat « Date: %d-%m-%Y Heure: %H:%M:%S Millis: %s » Write-Host $datestring Fonction pour faire des timestamp pendant le traitement (avec exemple d’utilisation) ######fonction temps function GetElapsedTime() { $runtime = $(get-date) – $script:StartTime $retStr = [string]::format(« {0} days, {1} hours, {2} minutes, {3}.{4} seconds », ` $runtime.Days, ` $runtime.Hours, ` $runtime.Minutes, ` $runtime.Seconds, ` $runtime.Milliseconds) $retStr } #on récupère le temps courant $script:startTime = get-date #on affiche le temps écoulé $(GetElapsedTime) Ajouter jours/mois à une date $currentdate = [datetime]::now $currentdate.AddDays(10) $currentdate.AddMonths(2)
Read MoreAdministration système, Powershell, Windows
Fonctions Requêtes AD Powershell
Quelques fonctions pour extraire des informations de l’AD : Liste d’une catégorie d’objet: function ListADCategoryArg { $filtre = « (objectCategory=$args) » $domaine = New-Object System.DirectoryServices.DirectoryEntry $chercheur = New-Object System.DirectoryServices.DirectorySearcher $chercheur.SearchRoot = $domaine $chercheur.PageSize = 10 $chercheur.Filter = $filtre $prop = « name » foreach ($i in $prop){$chercheur.PropertiesToLoad.Add($i)} $colResults = $chercheur.FindAll() foreach ($objResult in $colResults) { $objItem = $objResult.Properties # Sortie vers l’écran write-host $objItem.name } } ListADCategoryArg Group Lister les membres de : function ListmemberOf { $Dom = ‘LDAP://OU=$args,dc=xxxx,dc=zzzz »‘ $Root = New-Object DirectoryServices.DirectoryEntry $Dom $i=0 # Create a selector and start searching from the Root of AD $selector = New-Object DirectoryServices.DirectorySearcher $selector.SearchRoot = $root $adobj= $selector.findall() |` where {$_.properties.objectcategory -match « CN=computer »} foreach ($person in $adobj){ $prop=$person.properties $i++ Write-host « Le poste $args est membre de $($prop.memberof) »} } ListmemberOf ComputerName Liste des membres d’une OU: function ListOUCNMemberOf { $strFilter = « (&(objectCategory=computer)) » $objDomain = New-Object System.DirectoryServices.DirectoryEntry(« LDAP://OU=$args,dc=xxxx,dc=zzzz ») $objSearcher.SearchRoot = $objDomain $objSearcher.PageSize = 1000 $objSearcher.Filter = $strFilter $objSearcher.SearchScope = « OneLevel » $colProplist = « name » foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)} $colResults = $objSearcher.FindAll() foreach ($objResult in $colResults) {$objItem = $objResult.Properties; $objItem.name} } ListOUCNMemberOf Serveurs Recherhce d’un objet spécifique: Function SearchObject { param([string]$arg1, [string]$arg2) $searcher = New-Object DirectoryServices.DirectorySearcher([ADSI] » ») $searcher.filter = « (&(objectClass=$arg2)(sAMAccountName= $arg1)) » $searcher.findall() } SearchObject NOM_USER user Enjoy !!
Read MoreAdministration système, Debian, Linux
File Integrity
Voici un script cron pour vérifier l’intégrité des fichiers (surveille la modification par un hack par exemple…). Principe : création d’un hashage (une signature) des binaires présents dans /bin/ et /sbin/, puis à intervalles régulier vérifier si les signatures correspondes. Il faut donc faire une signature de référence. Création de la signature de référence : /usr/bin/sha256sum /bin/* >> listsum.ref /usr/bin/sha256sum /sbin/* >> listsum.ref /usr/bin/sha256sum /bin/* >> listsum.ref /usr/bin/sha256sum /sbin/* >> listsum.ref Création d’un script de vérification : #!/bin/bash /usr/bin/sha256sum /bin/* >> listsum /usr/bin/sha256sum /sbin/* >> listsum diff listsum listsum.ref > resulsum if test -s resulsum then echo ‘Attention – Les binaires sont différents le `date` | mail -s `Modification dans Bin ou Sbin` mon_email@mon_domaine.com else Il ne vous reste plus qu’a rendre exécutable le script et de créer une entré dans le cron… Voilà !!
Read More