SnakeNET

Utilisateur principal de ce site web.

Nov 272017
 

create administrative account

useradd MyUsername -s /bin/bash -G sudo -m
echo MyUsername:MyVerySecurePassword | chpasswd

Prevent root from login using SSH

sed -i ‘s/PermitRootLogin yes/PermitRootLogin no/g’ /etc/ssh/sshd_config
service ssh restart

Install programs

apt-get update
apt-get install -y xrdp mate-core mate-desktop-environment mate-notification-daemon tigervnc-standalone-server

/etc/init.d/xrdp stop
/etc/init.d/xrdp start

Tune XRDP tu use XVNC in priority

vi /etc/xrdp/xrdp.ini and permut Xorg and Xvnc block’s in the config file.

[Xvnc]
name=Xvnc
lib=libvnc.so
username=ask
password=ask
ip=127.0.0.1
port=-1
#xserverbpp=24
#delay_ms=2000

[Xorg]
name=Xorg
lib=libxup.so
username=ask
password=ask
ip=127.0.0.1
port=-1
code=20

Sécuriser le tout

apt-get install fail2ban

Install Firefox and test performance…

apt-get install firefox-esr firefox-esr-l10n-fr

Faire de la place sur le disque

On a un petit VPS, autant économiser la place…

apt-get clean

Tuning

xrdp.ini :

ls_background_image à doit indiquer un fichier present dans /usr/share/xrdp/
ls_top_window_bg_color=1a4384
ls_height=350
ls_bg_color=e4e3e8
ls_btn_ok_y_pos=300
ls_btn_cancel_y_pos=300

/etc/init.d/xrdp stop && /etc/init.d/xrdp start

openVPN

sudo apt-get install curl
curl -O https://raw.githubusercontent.com/Angristan/openvpn-install/master/openvpn-install.sh
chmod +x openvpn-install.sh
./openvpn-install.sh

Sécuriser

cat > /etc/fail2ban/filter.d/openvpn.local <<EOF
# Fail2Ban filter for selected OpenVPN rejections
#
#

[Definition]

# Example messages (other matched messages not seen in the testing server’s logs):
# Fri Sep 23 11:55:36 2016 TLS Error: incoming packet authentication failed from [AF_INET]59.90.146.160:51223
# Thu Aug 25 09:36:02 2016 117.207.115.143:58922 TLS Error: TLS handshake failed

failregex = ^ TLS Error: incoming packet authentication failed from \[AF_INET\]<HOST>:\d+$
^ <HOST>:\d+ Connection reset, restarting
^ <HOST>:\d+ TLS Auth Error
^ <HOST>:\d+ TLS Error: TLS handshake failed$
^ <HOST>:\d+ VERIFY ERROR

ignoreregex =
EOF

cat > /etc/fail2ban/jail.d/openvpn <<EOF
# Fail2Ban configuration fragment for OpenVPN

[openvpn]
enabled = true
port = 1194
protocol = udp
filter = openvpn
logpath = /var/log/openvpn.log
maxretry = 3
EOF

To effect the configuration change:
service fail2ban restart

Wireshark

apt-get -y install wireshark
gpasswd -a MyUsername wireshark

Oct 072017
 

Analogie avec le déplacement physique classique

Pour se déplacer dans le monde physique, on applique une force sur le monde physique par rapport à nous même.

Exemple : quand on marche, on appuie sur nos jambes qui sont fixées sur le sol: on se déplace

Pour se déplacer dans le temps, c’est la même idée. Il faut appliquer une force sur le temps.

1ère question: qu’est ce qui peut manipuler le temps.

Einstein nous l’a expliqué, le temps est déformé par la gravitation. Elle permet au temps de s’écouler plus ou moins vite. (Astronautes dans l’espace n’ont pas vu le même temps s’écouler)

2ème question: comment manipuler la gravitation.

Ce serait sympa de savoir car ça permettrait aussi de faire des voitures volantes 🙂

-> je ne sais pas encore… mais je cherche

Sep 062017
 

Avec ça, vous aurez les dernières erreurs et leurs causes possibles.

 

$NpsServers=('DC01','DC02')
$ReturnArray=@()

$NPS_Filter="<QueryList>
 <Query Id=`"0`" Path=`"System`">
 <Select Path=`"System`">*[System[Provider[@Name='NPS']]]</Select>
 <Select Path=`"System`">*[System[Provider[@Name='HRA']]]</Select>
 <Select Path=`"System`">*[System[Provider[@Name='Microsoft-Windows-HCAP']]]</Select>
 <Select Path=`"Security`">*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and Task = 12552]]</Select>
 </Query>
</QueryList>"

foreach ( $NpsServer in $NpsServers ) {
 foreach ( $Event in (Get-WinEvent -MaxEvents 800 -ComputerName $NpsServer -FilterXml ([xml]$NPS_Filter) | where {$_.message -like "*denied*"} ) ){
 $Message=$Event.Message.Split("`n")

$Retour = [PSCustomObject]@{
 TimeCreated =$Event.TimeCreated
 MachineName =$Event.MachineName
 AccountName =((($Message |Select-String -Pattern "Account Name" -CaseSensitive)[0]).ToString().split(':')[1]).trim()
 AuthType =((($Message |Select-String -Pattern "Authentication Type" -CaseSensitive)[0]).ToString().split(':')[1]).trim()
 Reason =''
 }
 if ($Message |Select-String -Pattern "Reason" ){
 $Retour.Reason =((($Message |Select-String -Pattern "Reason:" -CaseSensitive)[0]).ToString().split(':')[1]).trim()
 }

$ReturnArray+=$Retour
 }
}
$ReturnArray| ft -autosize

 

Juil 162017
 

A lancer en PowerShell

mkdir wifi
 cd wifi

netsh wlan export profile key=clear

$retour=@()

dir *.xml |% {
 $xml=[xml] (get-content $_)
 $tmp='' |select SSID,Password
 $tmp.SSID=$xml.WLANProfile.SSIDConfig.SSID.name
 $tmp.password=$xml.WLANProfile.MSM.Security.sharedKey.keymaterial
 $retour+=$tmp
 }

cd ..
 rmdir -recurse wifi

$retour | format-table -autosize
Et voilà…
Fév 242017
 

Autant le savoir tout de suite, j’ai attendu 6 mois de trouver la solution à ce problème.

Pré-requis :

  • Avoir le fichier d’installation MSI (Battez-vous pendant 6 mois avec le support Epson, ou, téléchargez-le ICI)EPSON Easy MP MSI
  • Se créer un fichier avec la liste des projecteurs par site

La GPO :

  • Déploiement classique d’application MSI, rien de particulier (Vérifiez que ca s’installera bien sous 32bit/64bit : case est bien cochée)
  • Script a executer par la machine (startup script) pour faire les ouvertures firewall qui vont bien
netsh advfirewall firewall show rule name="EasyMP Network Projection Ver.2.87" >NUL

if ERRORLEVEL 1 (
 netsh advfirewall firewall add rule name="EasyMP Network Projection Ver.2.87" dir=in  action=allow program="%ProgramFiles(x86)%\EPSON Projector\EasyMP Network Projection V2\EMP_NSC.exe" enable=yes EDGE=yes
 netsh advfirewall firewall add rule name="EasyMP Network Projection Ver.2.87" dir=out action=allow program="%ProgramFiles(x86)%\EPSON Projector\EasyMP Network Projection V2\EMP_NSC.exe" enable=yes

  netsh advfirewall firewall add rule name="EasyMP Network Projection Ver.2.87" dir=in  action=allow program="%ProgramFiles%\EPSON Projector\EasyMP Network Projection V2\EMP_NSC.exe" enable=yes EDGE=yes
 netsh advfirewall firewall add rule name="EasyMP Network Projection Ver.2.87" dir=out action=allow program="%ProgramFiles%\EPSON Projector\EasyMP Network Projection V2\EMP_NSC.exe" enable=yes
 )
  • Ecrasez le fichier contenant la liste des projecteurs dans %ProgramData%\SEIKO EPSON CORPORATION\EMP NS Connection\Profile_s.plist
  • Créez le raccourci qui créera une belle petite icône sur le bureau qui pointe vers « C:\Program Files (x86)\EPSON Projector\EasyMP Network Projection V2\EMP_NSC.exe » (attention 32/64bit)
  • Créez ces entrées dans la base de registre pour éviter d’avoir les popup dérangeantes au démarrage :
[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\SEIKO EPSON CORPORATION\EMP NS Connection\2.87]
"ConnectType"=dword:00000000
"StartUpAction"=dword:00000001
"FullScreenStream"=dword:00000001
"ApplicationRunningStatus"=dword:00000001
"NoInterruptConnect"=dword:00000000
"UseMultiDisplay"=dword:00000000
"ConnectedType"=dword:00000001

Et voilààààà ! 6 mois pour ça !

Fév 102017
 

Installer openVPN

apt-get install openvpn

Creer un fichier de connexion <MyHouse.conf>

dev tun
tls-client
remote MYHOME.FQDN.NET 1194
#float
redirect-gateway def1
pull
proto udp
script-security 2
comp-lzo 
reneg-sec 0 
auth-user-pass 
auth-nocache 
script-security 2 
up /root/MyHouse.script
 <ca> -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- </ca>

Créer un fichier avec le user et mot de passe <MyHouse.pass>

MyUsername
MySecurePassword

Et pour se connecter ??? openvpn –config MyHouse.conf  –auth-user-pass MyHouse.pass

MyHouse.script ::
sysctl -w net.ipv4.ip_forward=1
sysctl -p /etc/sysctl.conf
/sbin/iptables -t nat -A POSTROUTING -o tun0 -j MASQUERADE
Mais avec ca, je n’ai pas accès a mon réseau local… a creuser.
J’ai accès à tout le reste sauf mon réseau local…
root@chip:~# cat check_internet.sh
 #!/bin/bash
 echo This script will check if an internet connection is available. if Yes : Bring OpenVPN up
 echo if NOT, check if openvpn is UP. if yes, kill it.

let google=0
 for i in { 0..5 }
 do
 ping -c 4 8.8.8.8 > /dev/null 2>&1
 if [ $? -eq 0 ] ; then
 let google++
 fi

done

if [ $google -gt 2 ] ; then
 echo Google is available... at least 2/5
 openvpn=` ps -ef | grep -i openvpn |grep -v grep| wc -l`
 if [ $openvpn -eq 0 ] ; then
 /usr/sbin/openvpn --config /root/maison.openvpn.conf  --auth-user-pass /root/maison.openvpn.pass  2>&1 &
 else
 echo OpenVPN is allready UP. Do not touch it
 fi
 else
 echo Google is not available. Kill tunnel
 killall openvpn
 fi

crontab

* * * * * /root/check_internet.sh > /root/check_internet.log
Nov 242016
 

$Session = New-Object -ComObject « Microsoft.Update.Session »
$Searcher = $Session.CreateUpdateSearcher()
$historyCount = $Searcher.GetTotalHistoryCount()
$Searcher.QueryHistory(0, $historyCount) | Select-Object Date,
@{name= »Operation »; e={switch($_.operation){
1 {« Installation »}; 2 {« Uninstallation »}; 3 {« Other »}}}},
@{name= »Status »; e={switch($_.resultcode){
1 {« In Progress »}; 2 {« Succeeded »}; 3 {« Succeeded With Errors »}; 4 {« Failed »}; 5 {« Aborted »}}}},
@{name= »KB »;E={$_.title.split(« (« )[1].split(« ) »)[0]} },
Title | Export-Csv -NoType « $Env:userprofile\Desktop\Windows Updates.csv »
Source : https://social.technet.microsoft.com/wiki/contents/articles/4197.how-to-list-all-of-the-windows-and-software-updates-applied-to-a-computer.aspx

 

Oct 172016
 

Amusant. Si vous faites « enregistrer sous » et choisissez le format « CSV » et que vous avez des caractères bizarres ( Comme é,è,&,..) Excel les détruira lors de l’enregistrement (pas sympa)

Si vous faites « fichier > exporter » et choisissez le format CSV, ca va mieux! mais c’est pas encore ça.. (les champs ne sont pas entre guillemets et on ne peux pas choisir le caractère de séparation…

Voici donc un script PowerShell qui fait le boulot…

Et pour que ce soit GENIAL, faites un raccourci windows avec cette commande:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe  -ExecutionPolicy Bypass   -file  « H:\Scripts\XLS to CSV.ps1 »
(pensez à changer le chemin du script)
Ainsi, il vous suffira de faire un drag’n drop de votre fichier excel sur ce raccourci et HOP! converti !
(on pourait aussi envisager de le mettre dans « send to » mais, ca, je vous laisse faire)

param([string]$xlFile=’nothing’)
$debugMode=$false
$ErrorActionPreference=’Stop’
if ($debugMode) { $xlFile= »H:\Book1.xlsx » }
$csvFile=$xlfile.Replace(‘.xlsx’,’.csv’).replace(‘.xls’,’.csv’)
## Checking…
if ( $xlFile -eq ‘nothing’ ) { Write-Host « No Excel file given. aborting… »                                                     -foregroundcolor red ;$tmp=Read-Host « Press ENTER key to exit »;exit }
if ( test-path($xlFile -eq $false)  ) { Write-Host « Specified Excel file does not exist. »                                        -foregroundcolor red ;$tmp=Read-Host « Press ENTER key to exit »;exit }
if ( test-path($csvFile)   ) { Write-Host « Old converted CSV file exist. Please, delete it before trying to convert it again. »   -foregroundcolor red ;$tmp=Read-Host « Press ENTER key to exit »;exit }
# http://stackoverflow.com/questions/687891/exception-automating-excel-2007-with-powershell-when-calling-workbooks-add
& {
[threading.thread]::CurrentThread.CurrentCulture = ‘en-US’
$xl = New-Object -COM « Excel.Application »
$xl.Visible = $debugMode
Write-Host « Opening source file » -foregroundcolor green
$wb = $xl.Workbooks.Open($xlFile)
$ws = $wb.Sheets.Item(1)
  $i=1
while( $ws.Cells.Item(1, $i).value2 -ne $null ) { if ( $debugMode) {Write-host « Debug 1 : counting column $i »}; $i++ }
$maxColonne=$i-1
  $i=1
while( $ws.Cells.Item($i, 1).value2 -ne $null ) { if ( $debugMode) {Write-host « Debug 1 : counting row $i »}; $i++ }
$maxLigne=$i
  Write-Host « There will be $maxColonne columns and $MaxLigne lines to convert. » -foregroundcolor green
$object=@()
$ligne=2   # ligne 1 = titre
$colonne=1
  while( $ws.Cells.Item($ligne,1).value2 -ne $null ) {
$line=New-Object PSObject
$colonne=1
while( $colonne -le $maxColonne) {
$cell=$ws.Cells.Item($ligne,$colonne).value2
if ($cell -eq $null) { $cell = «  » }
Add-Member -InputObject $line -MemberType NoteProperty -Name $ws.Cells.Item(1, $colonne).value2 -Value $cell
if ( $debugMode) {Write-host « debug2  » + $ws.Cells.Item($ligne,$colonne).value2 }
$colonne++
}
$ligne++
$object += $line
write-host -NoNewline « `r                                              `r Progres : $ligne/$maxLigne »
}
  $wb.Close() | out-null
$xl.Quit() | out-null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl) | out-null
  Write-Host « `r`n$ligne rows where converted. » -foregroundcolor green
Write-Host « Saving datas to $csvFile. Please, wait… » -foregroundcolor cyan
$object | Export-Csv $csvFile -NoTypeInformation -Delimiter ‘;’ -Encoding UTF8
Write-Host « Save completed. » -foregroundcolor green
sleep 3
}
Tadaaaaa…
Oct 142016
 

Vous allez dans Azure? Vous voulez utiliser un mot de passe super complexe? et bien non !
En effet, les règles de Microsoft sont : entre 8 et 16 caractères et pas de caractères spéciaux trop spéciaux.

Selon mes tests, ces caractères ne passent pas : ù, µ, £, €, à, é, §, è, ç, à, ², ³

Pire! Si vous faites un reset password, et que lors du changement de mot de passe, vous en mettez un « trop » sécurisé, vous saurez vous connecter une fois, mais plus les fois suivantes!

Par contre, ABCdef123 est considéré par MS comme un mot de passe « fort » !

Merci Microsoft !!!!!

Sep 152016
 

Pré-requis :

Un share réseau sur lequel l’objet COMPUTER de la machine VEEAM a les droits en écriture.
Le soft ignore les paramètres de credentials créés pour l’occasion, alors, autant s’en passer complètement 🙂
Le script doit être lancé en tant qu’administrateur !!

J’ai préféré créer un script qui fait tout plutôt que de faire de la config dans l’application et dans le script.

Le script :

# Author: Vladimir Eremin
# Created Date: 3/24/2015
# http://forums.veeam.com/member31097.html
#
# Adapted by Myself
# Must be run as administrator !
# backup everything except VMs defined

##################################################################
#                   User Defined Variables
##################################################################

$ExceptionVMNames = @('DSVA-VM01','VM-VEEAM-01')           # Theses VMs will NOT be backuped.
$HostName = "ESXNAME01"
$Directory = "\\NAS01.DOMAIN.COM\VEEAM"
$CompressionLevel = "5"              # Desired compression level (Optional; Possible values: 0 - None, 4 - Dedupe-friendly, 5 - Optimal, 6 - High, 9 - Extreme)
$EnableQuiescence = $True            # Quiesce VM when taking snapshot (Optional; VMware Tools are required; Possible values: $True/$False)
$Retention = "In3days"               # Possible values: Never , Tonight, TomorrowNight, In3days, In1Week, In2Weeks, In1Month)

$EnableNotification = $True          # Send an eMail about the backup when completed.
$SMTPServer = "smtp.domain.com"
$EmailFrom = "veeam.site1@domain.com"
$EmailTo = "myself@domain.com"
$EmailSubject = "VM backup of SITE 1"




# Pour la création des objets nécessaires au backup. Il n'est pas nécessaire de les créer dans l'interface graphique.
$ESX_name='ESXNAME01.domain.com'
$ESX_User='root'
$ESX_password='MemePasEnReve:-)'
$NAS_name='NAS01'

# Get-Command -Module VeeamPSSnapIn           # pour lister les commandes possibles...

##################################################################
#                   End User Defined Variables
##################################################################

Add-PSSnapin VeeamPSSnapin

Connect-VBRServer -server localhost

if ( Find-VBRViEntity -name $ESX_name -HostsAndClusters ) {
  Write-Host "ESX exist" -foregroundcolor GREEN
} else {
  Write-Host "ESX does not exist. Create it" -foregroundcolor CYAN
  Add-VBRESXi -Name $ESX_name -User $ESX_User -Password $ESX_password
}

$Server = Get-VBRServer -name $HostName

# Création du repository.
# Attention, les droits NTFS du share doivent autoriser l'objet COMPUTER a modifier les fichiers sur le NAS.
if (Get-VBRBackupRepository -name $NAS_name ) {
  Write-Host "Repository exist" -foregroundcolor GREEN
} else {
  Write-Host "Repository does not exist. Create it"  -foregroundcolor CYAN
  Add-VBRBackupRepository -Name $NAS_name -Type CifsShare -RotatedDrive -Description "Synology NAS" -Server $server -Folder $Directory
}

# Creation du proxy pour backup local
if ( ( Get-VBRViProxy | measure).count -ne 1  ) {
  Write-Host "Proxy does not exist. Create it" -foregroundcolor CYAN
  Get-VBRServer | ? { $_.type -eq "Local" } | Add-VBRViProxy -Description "Local Backup Proxy" -MaxTasks 2
} else {
  Write-Host "Proxy exist"  -foregroundcolor GREEN
}

#################### Main program ################

$MesssagyBody = @()

foreach ($VM in Find-VBRViEntity -Server $Server | ? {$_.type -eq "vm" -and $_.name -notin $ExceptionVMNames -and $_.name -notlike "*_clone_*" }){

  Write-Host "Starting backup of " $VM.name -nonewline -foregroundcolor cyan
  $ZIPSession = Start-VBRZip -Entity $VM -Folder $Directory -Compression $CompressionLevel -DisableQuiesce:(!$EnableQuiescence) -AutoDelete $Retention
  if ( $ZIPSession.Result -eq 'Failed' ) {
    Write-Host ". statut : " $ZIPSession.Result -foregroundcolor RED
  } else {
    Write-Host ". statut : " $ZIPSession.Result -foregroundcolor GREEN
  }


  If ($EnableNotification){
    $TaskSessions = $ZIPSession.GetTaskSessions().logger.getlog().updatedrecords
    $FailedSessions =  $TaskSessions | where {$_.status -ne "ESucceeded"}

    if ($FailedSessions -ne $Null){
      $MesssagyBody = $MesssagyBody + ($ZIPSession | Select-Object @{n="Name";e={($_.name).Substring(0, $_.name.LastIndexOf("("))}} ,@{n="Start Time";e={$_.CreationTime}},@{n="End Time";e={$_.EndTime}},Result,@{n="Details";e={$FailedSessions.Title}})
    }Else{
      $MesssagyBody = $MesssagyBody + ($ZIPSession | Select-Object @{n="Name";e={($_.name).Substring(0, $_.name.LastIndexOf("("))}} ,@{n="Start Time";e={$_.CreationTime}},@{n="End Time";e={$_.EndTime}},Result,@{n="Details";e={($TaskSessions | sort creationtime -Descending | select -first 1).Title}})
    }
  }
}

If ($EnableNotification){
  #                   Email formatting
  $style = "<style>BODY{font-family: Arial; font-size: 10pt;}"
  $style+=   "TABLE{border: 1px solid black; border-collapse: collapse;}"
  $style+=   "TH{border: 1px solid black; background: #ddddff; padding: 5px; }"
  $style+=   "TD{border: 1px solid black; padding: 5px; }"
  $style+= "</style>"

  $Message = New-Object System.Net.Mail.MailMessage $EmailFrom, $EmailTo
  $Message.Subject = $EmailSubject
  $Message.IsBodyHTML = $True
  $message.Body = $MesssagyBody | ConvertTo-Html -head $style | Out-String
  $SMTP = New-Object Net.Mail.SmtpClient($SMTPServer)
  $SMTP.Send($Message)
}
La commande pour la tache planifiée :
schtasks /create /SC daily /TN Daily_VM_backup /TR "C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -file C:\Script\Veeam_Zip_SITE1.ps1" /ST 23:00 /RU system
Et voila…