Blog

Hallo zusammen,

in dem heutigen Blogeintrag möchte ich euch zeige wie Ihr unter Ubuntu 16.04 einen einfachen Loadbalancer mit HA-Proxy installieren könnt. Für das Howto habe ich drei Ubuntu 16.04 Server installiert. Zwei Server dienen mir als Webserver und einer als Loadbalancer.

 

 

 

 

 

 

 

Um einen nginx Webserver installieren zu können, benötigt es noch ein paar vorbereitungen.

Nach der Grundinstallation der beiden Webserver, müssen diese auf den neusten Stand gebracht werden.
Nach dem Login, wechselt man zum root Benutzer mit:

sudo -i oder sudo su -
apt update -y && apt upgrade -y

Nach dem das System up to date ist, konfiguriert man den beiden Server einee statischen IP-Adresse.
Hier habe ich mich an den Screenshot gehalten, der Webserver 1 bekommt die IP-Adresse 192.168.xxx.101 und der Webserver 2 die IP-Adresse 192.168.xxx.102.

vim /etc/network/interfaces

auto enp0s3
iface enp0s3 inet static
  address 192.168.xxx.xxx
  netmask 255.255.255.0
  gateway 192.168.xxx.xxx
  dns-search htdom.local
  dns-nameservers 192.168.xxx.xxx

reboot
## nginx Webserver installieren und überprüfen
##
apt-get install nginx apache2-utils ssh
dpkg --get-selections nginx apache2-utils
dpkg -l | grep nginx

Zur besseren Übersicht habe ich die /var/www/html/index.nginx-debian.html angepasst, damit man diese in den Screenshots besser erkennt.

 

 

 

 

 

Nach dem die Webserver fertig installiert sind und man auf diese sauber zugreifen kann, werden wir den Loadbalancer vorbereiten.

Auch der Loadbalancer muss auf den neusten Stand gebracht werden.
Nach dem Login, wechselt man zum root Benutzer mit:

sudo -i oder sudo su -
apt update -y && apt upgrade -y

Nach dem das System up to date ist, konfiguriert man auch dem Loadbalancer eine statischen IP-Adresse. Hier habe ich die IP-Adresse 192.168.xxx.51 benutzt.

vim /etc/network/interfaces

auto enp0s3
iface enp0s3 inet static
  address 192.168.xxx.xxx
  netmask 255.255.255.0
  gateway 192.168.xxx.xxx
  dns-search htdom.local
  dns-nameservers 192.168.xxx.xxx

reboot
## HA-Proxy installieren und überprüfen
##
apt install haproxy -y
dpkg --get-selections haproxy
dpkg -l | grep haproxy
## HA-Proxy Konfigurationsdateien sichern
##
mv /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.old
cp /etc/default/haproxy /etc/default/haproxy.old
## /etc/default/haproxy ##
##
vim /etc/default/haproxy

## Set ENABLED to 1 if you want the init script to start haproxy.
ENABLED=1
## Basis Konfiguration des HAProxy Dienst
##
vim /etc/haproxy/haproxy.cfg

## Basic Settings
##
global
  daemon

defaults
  mode http #tcp

frontend http-incoming
  bind 192.168.178.51:80
  default_backend webservers

backend webservers
  balance roundrobin #leastconn and #source
  server web01 192.168.178.101:80
  server web02 192.168.178.102:80

systemctl restart haproxy.service
systemctl status haproxy.service

Hier ruft man im Webbrowser nun die IP-Adresse (192.168.xxx.51) des Loadbalancer auf, wenn man die Webseite mit F5 refreshed, dann sieht man das Roundrobin verhalten. Wenn man in der /etc/haproxy/haproxy.cfg Konfigurationsdatei den mode auf tcp stellt, dann wird erst dann ein Roundroubin durchgeführt, wenn einer der Webserver down ist.

Dies kann man testen in dem man auf den Webservern den nginx Dienst stoppt. (systemctl stop nginx.service oder service nginx stop)

 

 

 

 

 

## Basis Konfiguration des HAProxy mit Statistics Report
##
vim /etc/haproxy/haproxy.cfg

## Global Settings
##
global
  daemon
  stats socket /run/haproxy/admin.sock mode 660 level admin 
  stats timeout 30s
  user haproxy
  group haproxy

## Default Settings
##
defaults
  log global 
  mode http #tcp
  option httplog

  timeout connect 5000
  timeout client 50000
  timeout server 50000

  retries 3

  errorfile 400 /etc/haproxy/errors/400.http
  errorfile 403 /etc/haproxy/errors/403.http
  errorfile 408 /etc/haproxy/errors/408.http
  errorfile 500 /etc/haproxy/errors/500.http
  errorfile 502 /etc/haproxy/errors/502.http
  errorfile 503 /etc/haproxy/errors/503.http
  errorfile 504 /etc/haproxy/errors/504.http

## Listen Settings
##
listen stats 
  bind 192.168.178.51:12345
  mode http

  maxconn 10

  stats enable
  stats hide-version
  stats refresh 30s
  stats show-node
  stats realm Loadbalanced\ Servers
  stats uri /stats
  stats auth admin:password

## Frontend Settings
##
frontend http-incoming
  bind 192.168.178.51:80
  default_backend webservers

## Backend Settings
##
backend webservers
  balance roundrobin #leastconn and #source
  option httpchk GET /webserver_check
  server web01 192.168.178.101:80 check inter 500 fall 3 rise 2
  server web02 192.168.178.102:80 check inter 500 fall 3 rise 2
## Konfiguration überprüfen
##
haproxy -f /etc/haproxy/haproxy.cfg -c

 

 

 

 

 

## Um die Option httpchk aktiv schalten zu können muss auf allen Webservern
## die webserver_check in das Root Verzeichnis abgelegt werden.
## Nach dieser Datei hällt dann der Loadbalancer ausschau.

touch /var/www/html/webserver_check

 

 

 

 

## HAProxy Statistics Report
##
http://192.168.178.51:12345/stats

Username: admin
Passwort: password

So das war es auch schon wieder von mir, viel Spaß beim konfigurieren.

Gruß Helmut

 

 

 

 

 

 

Wenn man keine CD/DVDs mehr zur Hand hat, kann man sich im eigenen Netzwerk einen PXE Server installieren. Dies funktioniert ganz gut mit einen Raspberry PI oder natürlich in einer Virtuellen Umgebung. Für diesen Blog Eintrag habe ich einen Ubuntu 16.04.2 LTS Server in einer Virtuellen Umgebung installiert.

Nach dem der Ubuntu 16.04.2 LTS Server fertig installiert wurde, installieren wir noch ein paar Grundlegende Pakete und patchen den Server.

sudo apt install vim ssh -y
sudo apt update && apt upgrade -y

Nach dem der Server up to date ist, konfiguriert man eine statischen IP-Adresse.

sudo vim /etc/network/interfaces

## /etc/network/interfaces ##
auto enp0s3
iface enp0s3 inet static
  address 192.168.178.10
  netmask 255.255.255.0
  gateway 192.168.178.1
  dns-search htdom.local
  dns-nameservers 192.168.178.1
#############################

## Damit die Netzwerk Konfiguration sauber funktioniert, starten wir den Server einmal durch.
##
sudo shutdown -r now oder reboot

Nach dem Reboot des Servers, können wir uns mit Putty oder Kitty auf dem Server verbinden.

Oder wir nutzen einen Linux Client (Windows 10 1607) um uns per ssh zu verbinden.
ssh <UserName>@192.168.178.10

Um nun einen PXE Server im Netzwerk zur Verfügung zu stellen, benötigen wir noch folgende Pakete.

apt install dnsmasq syslinux syslinux-common -y

Nach dem die Pakete installiert wurden, beginnen wir mit der konfiguration.

## PXE Verzeichnis anlegen und DHCP/PXE Einstellungen konfigurieren.
##
sudo mkdir /tftpboot

## PXE/DHCP Einstellungen konfigurieren
##
mv /etc/dnsmasq.conf /etc/dnsmasq.conf.old
sudo vim /etc/dnsmasq.conf

## /etc/dnsmasq.conf ##
##
interface=enp0s3
listen-address=127.0.0.1
port=53
domain-needed
bogus-priv
resolv-file=/etc/resolv.dnsmasq

dhcp-range=192.168.178.0,proxy
dhcp-boot=pxelinux.0,192.168.178.10,192.168.178.0
pxe-service=x86PC,"Netzwerk Boot",pxelinux

enable-tftp
tftp-root=/tftpboot
########################

sudo vim /etc/resolv.dnsmasq

## /etc/resolv.dnsmasq ##
##
nameserver 192.168.178.1
#########################

systemctl restart dnsmasq.service
systemctl status dnsmasq.service

Ubuntu Netboot Dateien herunterladen und extrahieren.

cd /tftpboot
wget -c http://archive.ubuntu.com/ubuntu/dists/xenial-updates/main/installer-amd64/current/images/netboot/netboot.tar.gz
tar xzvf netboot.tar.gz
rm -rf netboot.tar.gz

Ab hier ist der PXE Server schon einsatzfähig.

 

 

 

 

 

 

 

Um aber das Ubuntu 16.04.2 Desktop Image per PXE Boot laden zu können, müssen wir dieses noch herunterladen und in das Boot Verzeichnis integrieren/kopieren.

## Ubuntu 16.04 Desktop ISO Image herunterladen
##
cd /tmp
wget -c http://releases.ubuntu.com/16.04/ubuntu-16.04.2-desktop-amd64.iso

## Ubuntu 16.04 Desktop ISO Image mounten und Inhalt in das Boot Verzeichnis kopieren
##
mkdir -p /tftpboot/ubuntu/amd64
mount -o loop /tmp/ubuntu-16.04.2-desktop-amd64.iso /mnt
cp -a /mnt/. /tftpboot/ubuntu/amd64/
umount /mnt

Damit das Ubuntu 16.04 Desktop ISO Image geladen werden kann, benötigen wir noch eine Freigabe auf dem Server, dies können wir per NFS realisieren.

## NFS Server installieren
##
apt install nfs-kernel-server -y

sudo vim  /etc/exports
## /etc/exports ##
/tftpboot/ubuntu/amd64  192.168.178.0/24(ro,async,no_root_squash,no_subtree_check)
##################

sudo exportfs -a
systemctl restart nfs-kernel-server.service
systemctl restart nfs-server.service
ps -aux | grep nfs

Die Konfigurationsdatei (default) für das Boot Menü, findet man im Verzeichnis /tftpboot/ubuntu-installer/amd64/pxelinux.cfg/
ls -la /tftpboot/ubuntu-installer/amd64/pxelinux.cfg/default

## Bootmenü anpassen um das Ubuntu 16.04 Desktop ISO Image zu booten
##
mv /tftpboot/ubuntu-installer/amd64/pxelinux.cfg/default /tftpboot/ubuntu-installer/amd64/pxelinux.cfg/default.old
sudo vim /tftpboot/ubuntu-installer/amd64/pxelinux.cfg/default


## default ##
PATH /tftpboot/ubuntu-installer/amd64/boot-screens/
DEFAULT /tftpboot/ubuntu-installer/amd64/boot-screens/vesamenu.c32
PROMPT 0
TIMEOUT 150
ONTIMEOUT local
NOESCAPE 1
ALLOWOPTIONS 1

MENU BACKGROUND /tftpboot/ubuntu-installer/amd64/boot-screens/bootlogo.png
MENU RESOLUTION 800 600
MENU TITLE HTDOM PXE Server
MENU COLOR TITLE 1;37 #ffffffff #00000000 std

MENU WIDTH 98
MENU ROWS 11
MENU MARGIN 15
MENU COLOR BORDER * #00000000 #00000000 std

LABEL Boot from local DISK
  localboot 0
TEXT HELP
  Boot from local DISK
ENDTEXT

LABEL ---------------------------------------------------------------------

LABEL Ubuntu 16.04.2 Desktop Live
  kernel /tftpboot/ubuntu/amd64/casper/vmlinuz.efi
  append vga=normal netboot=nfs boot=casper nfsroot=192.168.178.10:/tftpboot/ubuntu/amd64/ ro initrd=/tftpboot/ubuntu/amd64/casper/initrd.lz locale=de_DE bootkbd=de console-setup/layoutcode=de
TEXT HELP
  Boot Ubuntu 16.04.2 Desktop Live
ENDTEXT
#############

 

 

 

 

 

 

 

 

Download des Bootlogos

 

 

 

 

 

 

 

 

So nun wünsche ich euch viel Spaß mit euren eigenen PXE Server.

Gruß Helmut

 

 

 

 

Hallo zusammen,

um den Nextcloud Server installieren zu können, benötigt es ein paar Vorbereitungen.
In diesen Beispiel verwende wir einen Ubuntu 16.04 LTS Server in einer Virtuellen Umgebung.

Nach der Grundinstallation des Ubuntu Servers, muss der Server auf den neusten Stand gebracht werden.
Nach dem Login, wechselt man zum root Benutzer mit:

sudo -i oder sudo su -
apt install ssh vim
apt update && apt upgrade -y

nginx Webserver installieren und überprüfen

apt install nginx nginx-extras apache2-utils ssh
dpkg -l | grep nginx

MariaDB Server installieren & Konfigurieren

apt install mariadb-server
dpkg -l | grep mariadb

mysql_secure_installation

cp /etc/mysql/my.cnf /etc/mysql/my.cnf.bak
vim /etc/mysql/my.cnf

[server]
skip-name-resolve
innodb_buffer_pool_size = 128M
innodb_buffer_pool_instances = 1
innodb_flush_log_at_trx_commit = 2
innodb_log_buffer_size = 32M
innodb_max_dirty_pages_pct = 90
query_cache_type = 1
query_cache_limit = 2M
query_cache_min_res_unit = 2k
query_cache_size = 64M
tmp_table_size= 64M
max_heap_table_size= 64M
slow-query-log = 1
slow-query-log-file = /var/log/mysql/slow.log
long_query_time = 1

#
[client-server]

# Import all .cnf files from configuration directory
!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mariadb.conf.d/

[client]
default-character-set = utf8mb4
[mysqld]
character-set-server  = utf8mb4
collation-server      = utf8mb4_general_ci
binlog_format = MIXED

systemctl start mysql.service
systemctl status mysql.service

NextCloud Datenbank anlegen

mysql -u root -p

CREATE DATABASE nextcloudDB;
USE nextcloudDB;

CREATE USER nextcloudDB@localhost IDENTIFIED BY 'nextcloudDB';
GRANT ALL PRIVILEGES ON nextcloudDB.* TO 'nextcloudDB'@'localhost' IDENTIFIED BY 'DeinPassword';
FLUSH PRIVILEGES;
quit

mysql -u nextcloudDB -p nextcloudDB
DeinPassword
quit

PHP 7 installieren

apt install libxml2-dev php php-gettext php-pear php-dompdf php-sabre-xml php-apcu php-imagick php7.0-fpm php7.0-gd php7.0-mysql php7.0-curl php7.0-xml php7.0-zip php7.0-bz2 php7.0-intl php7.0-mcrypt php7.0-mbstring php7.0-json php7.0-xsl php7.0-bcmath php7.0-cgi php7.0-cli php7.0-common  php7.0-imap

php.ini Datei anpassen

cp /etc/php/7.0/fpm/php.ini /etc/php/7.0/fpm/php.old
vim /etc/php/7.0/fpm/php.ini

memory_limit = 512M
post_max_size = 200M
cgi.fix_pathinfo=1
upload_max_filesize = 200M
date.timezone = Europe/Berlin

oder

egrep "memory_limit|date.timezone|cgi.fix_pathinfo|upload_max_filesize|post_max_size" /etc/php/7.0/fpm/php.ini

sed -i "s/memory_limit = .*/memory_limit = 512M/" /etc/php/7.0/fpm/php.ini
sed -i "s/;date.timezone.*/date.timezone = Europe\/\Berlin/" /etc/php/7.0/fpm/php.ini
sed -i "s/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=1/" /etc/php/7.0/fpm/php.ini
sed -i "s/upload_max_filesize = .*/upload_max_filesize = 200M/" /etc/php/7.0/fpm/php.ini
sed -i "s/post_max_size = .*/post_max_size = 200M/" /etc/php/7.0/fpm/php.ini

fpm www.conf Datei anpassen

nano /etc/php/7.0/fpm/pool.d/www.conf

...
;listen = /run/php/php7.0-fpm.sock
listen = 127.0.0.1:9000

env[HOSTNAME] = $HOSTNAME
env[PATH] = /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
env[TMP] = /tmp 
env[TMPDIR] = /tmp
env[TEMP] = /tmp

service php7.0-fpm restart
service php7.0-fpm status

NextCloud 11 installieren

cd /tmp
wget https://download.nextcloud.com/server/releases/nextcloud-11.0.1.zip
unzip nextcloud-11.0.1.zip
mv nextcloud /var/www/
chown -R www-data: /var/www/nextcloud

SSL Zertifikat über eigene CA erstellen

cd /opt/ca/IssuingCA

openssl genrsa -aes256 -out private/nextcloud_htdom_local_without_pwd.key 2048 -rand private/.randIssuingCA
chmod 0400 private/nextcloud_htdom_local_without_pwd.key

openssl req -new -key private/nextcloud_htdom_local_without_pwd.key -out newcerts/nextcloud.htdom.local.csr -config ca-config.cnf
Enter pass phrase for private/nextcloud_htdom_local_without_pwd.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [DE]:
State or Province Name (Bayern) [Bayern]:
Locality Name (Muenchen) [Muenchen]:
Organization Name (Company name or your Name) [Helmut Thurnhofer]:
Organizational Unit Name (Department) [IT]:
Common Name (Server FQDN or your Name) []:nextcloud.htdom.local
...

openssl ca -name IssuingCA -in newcerts/nextcloud.htdom.local.csr -out certs/nextcloud.htdom.local.crt -extensions server_cert -config ca-config.cnf
Using configuration from ca-config.cnf
Enter pass phrase for /opt/ca/IssuingCA/private/IssuingCA.key:
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Feb  7 20:10:54 2017 GMT
            Not After : Feb  5 20:10:54 2027 GMT
        Subject:
            countryName               = DE
            stateOrProvinceName       = Bayern
            organizationName          = Helmut Thurnhofer
            organizationalUnitName    = IT
            commonName                = nextcloud.htdom.local
        X509v3 extensions:
            X509v3 Basic Constraints:
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment, Data Encipherment
            X509v3 Extended Key Usage:
                TLS Web Server Authentication
            Authority Information Access:
                CA Issuers - URI:http://nextcloud.htdom.local/cert/IssuingCA.html

            X509v3 CRL Distribution Points:

                Full Name:
                  URI:http://nextcloud.htdom.local/cert/IssuingCA.crl

Certificate is to be certified until Feb  5 20:10:54 2027 GMT (3650 days)
Sign the certificate? [y/n]:y

1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

## Keydatei erstellen mit Passwort (Ansonsten muss bei jeden Neustart des Servers die Passphrase eingegeben werden)
##
openssl rsa -in private/nextcloud_htdom_local_without_pwd.key | cat

-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEArbdXG8+BUxm0NvO2pWXdx/0L3z/Nb+enAWqL59PzOuL63vXv
...
WyYHO6o4iUROOuJ9I0t0KsEDqkgh+VEOtcVfh8/gZ9IXyfXFyRhu09Q=
-----END RSA PRIVATE KEY-----

vim private/nextcloud.htdom.local.key
chmod 0400 private/nextcloud.htdom.local.key

oder man erstellt sich ein.

SelfSign SSL Zertifikat

openssl rand -out /etc/ssl/private/.randServer 8192
chmod 0400 /etc/ssl/private/.randServer

openssl genrsa -aes256 -out /etc/ssl/private/nextcloud_htdom_local_without_pwd.key 4096 -rand /etc/ssl/private/.randServer
chmod 0400 /etc/ssl/private/nextcloud_htdom_local_without_pwd.key

openssl rsa -in /etc/ssl/private/nextcloud_htdom_local_without_pwd.key | cat

-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEArbdXG8+BUxm0NvO2pWXdx/0L3z/Nb+enAWqL59PzOuL63vXv
...
WyYHO6o4iUROOuJ9I0t0KsEDqkgh+VEOtcVfh8/gZ9IXyfXFyRhu09Q=
-----END RSA PRIVATE KEY-----

vim /etc/ssl/private/nextcloud.htdom.local.key
chmod 0400 /etc/ssl/private/nextcloud.htdom.local.key

openssl req -new -key /etc/ssl/private/nextcloud.htdom.local.key -sha256 -out /etc/ssl/certs/nextcloud.htdom.local.csr
openssl x509 -req -days 365 -in /etc/ssl/certs/nextcloud.htdom.local.csr -signkey /etc/ssl/private/nextcloud.htdom.local.key -out /etc/ssl/certs/nextcloud.htdom.local.crt

nginx Webserver Konfiguration

vim /etc/nginx/sites-available/nextcloud.conf

upstream php-handler {
    server 127.0.0.1:9000;
}

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    # enforce https
    return 301 https://$host$request_uri;

    access_log /var/log/nginx/access_nextcloud_htdom_local.log;
    error_log /var/log/nginx/error_nextcloud_htdom_local.log;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    ssl_certificate /etc/ssl/certs/nextcloud.htdom.local.crt;
    ssl_certificate_key /etc/ssl/private/nextcloud_htdom_local.key;

    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;

    ## modern configuration. tweak to your needs.
    ssl_protocols TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256';
    ssl_prefer_server_ciphers on;

    ## HSTS (ngx_http_headers_module is required) (15768000 seconds = 6 months)
    add_header Strict-Transport-Security max-age=15768000;

    # Add headers to serve security related headers
    # Before enabling Strict-Transport-Security headers please read into this
    # topic first.
    # add_header Strict-Transport-Security "max-age=15768000;
    # includeSubDomains; preload;";
    add_header X-Content-Type-Options nosniff;
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Robots-Tag none;
    add_header X-Download-Options noopen;
    add_header X-Permitted-Cross-Domain-Policies none;

    # Path to the root of your installation
    root /var/www/nextcloud/;

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    # The following 2 rules are only needed for the user_webfinger app.
    # Uncomment it if you're planning to use this app.
    #rewrite ^/.well-known/host-meta /public.php?service=host-meta last;
    #rewrite ^/.well-known/host-meta.json /public.php?service=host-meta-json
    # last;

    location = /.well-known/carddav {
      return 301 $scheme://$host/remote.php/dav;
    }
    location = /.well-known/caldav {
      return 301 $scheme://$host/remote.php/dav;
    }

    # set max upload size
    client_max_body_size 512M;
    fastcgi_buffers 64 4K;

    # Disable gzip to avoid the removal of the ETag header
    gzip off;

    # Uncomment if your server is build with the ngx_pagespeed module
    # This module is currently not supported.
    #pagespeed off;

    error_page 403 /core/templates/403.php;
    error_page 404 /core/templates/404.php;

    location / {
        rewrite ^ /index.php$uri;
    }

    location ~ ^/(?:build|tests|config|lib|3rdparty|templates|data)/ {
        deny all;
    }
    location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console) {
        deny all;
    }

    location ~ ^/(?:index|remote|public|cron|core/ajax/update|status|ocs/v[12]|updater/.+|ocs-provider/.+|core/templates/40[34])\.php(?:$|/) {
        include fastcgi_params;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param HTTPS on;

        #Avoid sending the security headers twice
        fastcgi_param modHeadersAvailable true;
        fastcgi_param front_controller_active true;
        fastcgi_pass php-handler;
        fastcgi_intercept_errors on;
        fastcgi_request_buffering off;
    }

    location ~ ^/(?:updater|ocs-provider)(?:$|/) {
        try_files $uri/ =404;
        index index.php;
    }

    # Adding the cache control header for js and css files
    # Make sure it is BELOW the PHP block
    location ~* \.(?:css|js|woff|svg|gif)$ {
        try_files $uri /index.php$uri$is_args$args;
        add_header Cache-Control "public, max-age=7200";
        # Add headers to serve security related headers (It is intended to
        # have those duplicated to the ones above)
        # Before enabling Strict-Transport-Security headers please read into
        # this topic first.
        # add_header Strict-Transport-Security "max-age=15768000;
        #  includeSubDomains; preload;";
        add_header X-Content-Type-Options nosniff;
        add_header X-Frame-Options "SAMEORIGIN";
        add_header X-XSS-Protection "1; mode=block";
        add_header X-Robots-Tag none;
        add_header X-Download-Options noopen;
        add_header X-Permitted-Cross-Domain-Policies none;
        # Optional: Don't log access to assets
        access_log off;
    }

    location ~* \.(?:png|html|ttf|ico|jpg|jpeg)$ {
        try_files $uri /index.php$uri$is_args$args;
        # Optional: Don't log access to other assets
        access_log off;
    }
}

nginx überprüfen und restliche Konfiguration vornehmen

nginx -t

unlink /etc/nginx/sites-enabled/default
mv /etc/nginx/sites-available/default{,.old}

ln -s /etc/nginx/sites-available/nextcloud.conf /etc/nginx/sites-enabled/
systemctl restart nginx.service
systemctl status nginx.service

Memory Cache konfigurieren

apt-cache policy php-apcu
apt install php-apcu

systemctl restart nginx.service

nano /var/www/nextcloud/config/config.php
<?php
$CONFIG = array (
  'memcache.local' => '\OC\Memcache\APCu',
  ...
  'trusted_domains' =>
  array (
    0 => '192.168.178.2',
    1 => 'nextcloud.htdom.local',
  ),

systemctl restart nginx.service
systemctl status nginx.service

 

 

 

 

 

 

Viel Spaß beim konfigurieren

Gruß Helmut

 

 

 

 

 

Hallo zusammen,

um einen nginx Webserver installieren zu können, benötigt es ein paar Vorbereitungen.
In diesen Beispiel verwende wir einen Ubuntu 16.04 LTS Server in einer Virtuellen Umgebung.

Nach der Grundinstallation des Servers, muss der Server auf den neusten Stand gebracht werden.
Nach dem Login, wechselt man zum root Benutzer mit:

sudo -i oder sudo su -
apt update -y && apt upgrade -y
reboot

Nach dem das System up to date ist, konfiguriert man den Server mit einer statischen IP-Adresse.

vim /etc/network/interfaces

auto enp0s3
iface enp0s3 inet static
  address 192.168.xxx.xxx
  netmask 255.255.255.0
  gateway 192.168.xxx.xxx
  dns-search htdom.local
  dns-nameservers 192.168.xxx.xxx 192.168.xxx.xxx

systemctl restart networking.service
systemctl status networking.service

nginx Webserver installation und überprüfen

apt-get install nginx apache2-utils ssh
dpkg -l | grep nginx

Standardverzeichnisse nach der Installation

tree /etc/nginx

/etc/nginx/
├── conf.d
├── fastcgi.conf
├── fastcgi_params
├── koi-utf
├── koi-win
├── mime.types
├── nginx.conf
├── proxy_params
├── scgi_params
├── sites-available
│   └── default
├── sites-enabled
│   └── default -> /etc/nginx/sites-available/default
├── snippets
│   ├── fastcgi-php.conf
│   └── snakeoil.conf
├── uwsgi_params
└── win-utf


tree /var/www

/var/www/
└── html
    └── index.nginx-debian.html

Grundlegende nginx Befehle

## Mit folgenden Befehlen kann man den nginx Server starten/stoppen/reloaden/configtest durchführen bzw. den Status abfragen
##
service nginx {start|stop|restart|reload|force-reload|status|configtest|rotate|upgrade}

## Der wichtigste Befehl nach jeder Konfigurationsanpassung ist immer.
##
nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

oder

service nginx configtest
* Testing nginx configuration
  ...done.

Mit folgenden Befehl überprüft man, ob der nginx Server auf Port 80 lauscht

netstat -antlp | grep nginx
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      4236/nginx -g daemo
tcp6       0      0 :::80                   :::*                    LISTEN      4236/nginx -g daemo

PID File Anpassung in der nginx.service Datei

## Nach jedem Neustart des nginx Services, wird eine Fehlermeldung ausgegeben, das die nginx.pid nicht gelesen/gefunden wird.
## Daher wurde hier eine kleine Anpassung an der nginx.service & nginx.conf Datei vorgenommen.
##
systemctl status nginx.service
● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   ...
Jan 19 16:08:53 web01 systemd[1]: Starting A high performance web server and a reverse proxy server...
Jan 19 16:08:53 web01 systemd[1]: nginx.service: Failed to read PID from file /run/nginx.pid: Invalid argument


vim /lib/systemd/system/nginx.service
[Service]
Type=forking
PIDFile=/var/run/nginx.pid
...
ExecStop=-/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /var/run/nginx.pid
. . .

vim /etc/nginx/nginx.conf
http {
    # pid /var/run/nginx.pid;
    . . .
}

systemctl restart nginx.service
systemctl daemon-reload

systemctl status nginx.service
● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   ...
Jan 19 16:10:00 web01 systemd[1]: Starting A high performance web server and a reverse proxy server...
Jan 19 16:10:00 web01 systemd[1]: Started A high performance web server and a reverse proxy server.

Erste Webseite konfigurieren

## Als erstes entfernen wir den Standardlink unter sites-enabled und machen eine Sicherungskopie der /etc/nginx/default Datei.

unlink /etc/nginx/sites-enabled/default
mv /etc/nginx/sites-available/default{,.old}

mv /var/www/html/index.nginx-debian.html /var/www/html/index.html
mv /var/www/html/ /var/www/mysite_htdom_local

vim /etc/nginx/sites-available/mysite.htdom.local

## Default Server Konfiguration ohne https und rewrite
##
server {
  listen 80;
  listen [::]:80;

  server_name mysite.htdom.local;
  root /var/www/mysite_htdom_local;
  index index.html;

  access_log /var/log/nginx/access_mysite_htdom_local.log;
  error_log /var/log/nginx/error_mysite_htdom_local.log;
}

ln -s /etc/nginx/sites-available/mysite.htdom.local /etc/nginx/sites-enabled/

systemctl reload nginx.service

 

 

 

 

 

Virtuellen Host konfigurieren

mkdir -p /var/www/site1_htdom_local
sudo chown -R root:root /var/www/site1_htdom_local

vim /etc/nginx/sites-available/site1.htdom.local

## Default Server Konfiguration ohne https und rewrite
##
server {
  listen 80;
  listen [::]:80;

  server_name site1.htdom.local;
  root /var/www/site1_htdom_local;
  index index.html;

  access_log /var/log/nginx/access_site1_htdom_local.log;
  error_log /var/log/nginx/error_site1_htdom_local.log;
}

ln -s /etc/nginx/sites-available/site1.htdom.local /etc/nginx/sites-enabled/

systemctl reload nginx.service

ls -la /etc/nginx/sites-enabled/
...
lrwxrwxrwx 1 root root   45 Jan 19 18:45 mysite.htdom.local -> /etc/nginx/sites-available/mysite.htdom.local
lrwxrwxrwx 1 root root   44 Jan 20 15:58 site1.htdom.local -> /etc/nginx/sites-available/site1.htdom.local

 

 

 

 

 

Webserver SSL Zertifikat erstellen

cd /opt/ca/IssuingCA/

openssl genrsa -aes256 -out private/mysite.htdom.local.key 2048 -rand private/.randIssuingCA
chmod 0400 private/mysite.htdom.local.key

openssl req -new -key private/mysite.htdom.local.key -out newcerts/mysite.htdom.local.csr -config ca-config.cnf

Enter pass phrase for private/mysite.htdom.local.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [DE]:
State or Province Name (Bayern) [Bayern]:
Locality Name (Muenchen) [Muenchen]:
Organization Name (Company name or your Name) [HTDOM Company GmbH]:
Organizational Unit Name (Department) [IT]:IT-Support
Common Name (Server FQDN or your Name) []:mysite.htdom.local
...

-----------------------------------------------------------------------
openssl ca -name IssuingCA -in newcerts/mysite.htdom.local.csr -out certs/mysite.htdom.local.crt -extensions server_cert -config ca-config.cnf

Using configuration from ca-config.cnf
Enter pass phrase for /opt/ca/IssuingCA/private/IssuingCA.key:
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Jan 22 13:14:33 2017 GMT
            Not After : Jan 20 13:14:33 2027 GMT
        Subject:
            countryName               = DE
            stateOrProvinceName       = Bayern
            organizationName          = HTDOM Company GmbH
            organizationalUnitName    = IT-Support
            commonName                = mysite.htdom.local
        X509v3 extensions:
            X509v3 Basic Constraints:
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment, Data Encipherment
            X509v3 Extended Key Usage:
                TLS Web Server Authentication
            Authority Information Access:
                CA Issuers - URI:http://mysite.htdom.local/cert/IssuingCA.html

            X509v3 CRL Distribution Points:

                Full Name:
                  URI:http://mysite.htdom.local/cert/IssuingCA.crl

Certificate is to be certified until Jan 20 13:14:33 2027 GMT (3650 days)
Sign the certificate? [y/n]:y

1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

-----------------------------------------------------------------------

## Keydatei erstellen mit Passwort (Ansonsten muss bei jeden Neustart des Servers die Passphrase eingegeben werden)
##
openssl rsa -in private/mysite.htdom.local.key | cat

-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEArbdXG8+BUxm0NvO2pWXdx/0L3z/Nb+enAWqL59PzOuL63vXv
...
WyYHO6o4iUROOuJ9I0t0KsEDqkgh+VEOtcVfh8/gZ9IXyfXFyRhu09Q=
-----END RSA PRIVATE KEY-----

vim private/mysite.htdom.local.with.pwd.key
chmod 0400 private/mysite.htdom.local.with.pwd.key

-----------------------------------------------------------------------

## Zertifikat auslesen und auf dem Webserver importieren
##
cat /opt/ca/IssuingCA/certs/mysite.htdom.local.crt | sed -n -e '/BEGIN\ CERTIFICATE/,/END\ CERTIFICATE/ p'
cat /opt/ca/IssuingCA/private/mysite.htdom.local.with.pwd.key

-----------------------------------------------------------------------

## Ansicht auf dem Webserver
##
ls -la certs/mysite.htdom.local.crt
-rw-r--r-- 1 root root 1866 Jan 22 14:21 certs/mysite.htdom.local.crt

ls -la private/mysite.htdom.local.with.pwd.key
-rw-r----- 1 root root 1675 Jan 22 14:22 private/mysite.htdom.local.with.pwd.key

chmod 0640 /etc/ssl/private/mysite.htdom.local.with.pwd.key

tree /var/www/mysite_htdom_local/
/var/www/mysite_htdom_local/
├── cert
│   ├── IssuingCA.crl
│   ├── IssuingCA.crt
│   ├── RootCA.crl
│   └── RootCA.crt
└── index.html

mysite.htdom.local Konfiguration anpassen

vim /etc/nginx/sites-available/mysite.htdom.local

## Default Server Konfiguration mit https und rewrite
##
server {
  listen 80 default_server;
  listen [::]:80 default_server;

## Redirect all HTTP requests to HTTPS with a 301 Moved Permanently response.
  return 301 https://$host$request_uri;

  access_log /var/log/nginx/access_mysite_htdom_local.log;
  error_log /var/log/nginx/error_mysite_htdom_local.log;
}

server {
  listen 443 ssl http2;
  listen [::]:443 ssl http2;

  root /var/www/mysite_htdom_local;
  index index.html;
    location / {
        try_files $uri $uri/ /index.html;
    }
  
## SSL Zertifikate
  ssl_certificate /etc/ssl/certs/mysite.htdom.local.crt;
  ssl_certificate_key /etc/ssl/private/mysite.htdom.local.with.pwd.key;
}

nginx -t
systemctl restart nginx.service
systemctl status nginx.service

Mit folgenden Befehl überprüft man, ob der nginx Server auf Port 80 und 443 lauscht

netstat -antlp | grep nginx
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      3776/nginx -g daemo
tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      3776/nginx -g daemo
tcp6       0      0 :::80                   :::*                    LISTEN      3776/nginx -g daemo
tcp6       0      0 :::443                  :::*                    LISTEN      3776/nginx -g daemo

 

 

 

 

 

 

Um noch mehr Sicherheit in die TLS Verbindung zu bekommen, sollte man das TLS Protokoll und den Schlüsselaustausch (Chiper) eingrenzen.
Dazu gibt es eine sehr gute Webseite von Mozilla, mit dieser Mozilla SSL Configuration Generator kann man sich die passende Konfiguration für seinen Webserver zusammenklicken.

https://mozilla.github.io/server-side-tls/ssl-config-generator/

Modern: Ist Stand heute die sicherste Einstellung, hier wird nur noch TLSv1.2 verwendet
Intermediate: Ist ein kompromiss aus Sicherheit und Kompatibilität, hier wird noch TLSv1 TLSv1.1 TLSv1.2 verwendet.
Old: Ist die schlechterste Wahl, hier wird sogar noch das veraltete SSLv3 verwendet.

Alle heutigen Browser unterstützen bereits TLSv1.2 daher sollte man, wenn möglich Intermediate oder Modern benutzen.
Um die Konfiguration auf der Webseite vornehmen zu können, müssen wir erst die nginx und openssl Version herausfinden, dies funktioniert mit folgenden Befehl.

nginx -V
nginx version: nginx/1.10.0 (Ubuntu)
built with OpenSSL 1.0.2g  1 Mar 2016

Und so sieht meine Modern Konfiguration aus

## Default Server Konfiguration mit https/rewrite und Modern Konfiguration
##
server {
  listen 80 default_server;
  listen [::]:80 default_server;

## Redirect all HTTP requests to HTTPS with a 301 Moved Permanently response.
  return 301 https://$host$request_uri;

  access_log /var/log/nginx/access_mysite_htdom_local.log;
  error_log /var/log/nginx/error_mysite_htdom_local.log;
}

server {
  listen 443 ssl http2;
  listen [::]:443 ssl http2;

  root /var/www/mysite_htdom_local;
  index index.html;
    location / {
        try_files $uri $uri/ /index.html;
    }
  
## certs sent to the client in SERVER HELLO are concatenated in ssl_certificate
    ssl_certificate /etc/ssl/certs/mysite.htdom.local.crt;
    ssl_certificate_key /etc/ssl/private/mysite.htdom.local.with.pwd.key;

    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;

## modern configuration. tweak to your needs.
    ssl_protocols TLSv1.2;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256';
    ssl_prefer_server_ciphers on;

## HSTS (ngx_http_headers_module is required) (15768000 seconds = 6 months)
    add_header Strict-Transport-Security max-age=15768000;
}

SSL/TLS Verbindungstest kann man auf folgender Webseite durchführen
https://www.ssllabs.com/ssltest/index.html

Wenn man nun die Variante Modern nutzt, könnte die Handshake Simulation wie folgt aussehen.
Alle Browser die kein TLSv1.2 unterstützen, werden abgewiesen, bzw. können keine Verbindung zum Webserver aufbauen.

 

 

 

 

 

 

 

Viel Spaß beim ausprobieren

Gruß Helmut

 

 

 

 

 

In diesen Beitrag möchte ich kurz zeigen, wie man sich für eine Testumgebung oder vielleicht einen späteren Live Betrieb eine zweistufige PKI mit OpenSSL einrichtet.
Hierzu wurde ein Standard Ubuntu 16.04 LTS Server installiert.

Das wichtigste für eine CA ist die OpenSSL-Konfigurationsdatei, diese liegt Standardmäßig jeder openssl Installation bei, diese Datei wurde kopiert und auf die Testumgebung angepasst.
Wenn Ihr andere Installationspfade nutzen wollt, dann bitte dementsprechend die ca-config.cnf Datei nach euren Bedürfnisse anpassen.

locate *.cnf
/etc/ssl/openssl.cnf
/usr/lib/ssl/openssl.cnf

Was sehr wichtig ist, sind die Sektionen. Die URLs müssen unbedingt für die Testumgebung angepasst werden. Damit im Zertifikat später die richtigen URLs stehen.
Die Certification Revocation List (*.crl) muss über http:// erreichbar sein, wenn das nicht der Fall ist, kann es zu unnötigen Fehlern kommen.

[root_ca]
[issuingca_cert]
[user_cert]
[server_cert]

authorityInfoAccess = caIssuers;URI:http://server.domain.de/RootCA.html
crlDistributionPoints=URI:http://server.domain.de/RootCA.crl

authorityInfoAccess = caIssuers;URI:http://server.domain.de/IssuingCA.html
crlDistributionPoints=URI:http://server.domain.de/IssuingCA.crl

ca-config.cnf

# This definition stops the following lines choking if HOME isn't
# defined.
HOME = .
RANDFILE = $ENV::HOME/.rnd

# Extra OBJECT IDENTIFIER info:
oid_section = new_oids

[new_oids]
# Policies used by the TSA examples.
tsa_policy1 = 1.2.3.4.1
tsa_policy2 = 1.2.3.4.5.6
tsa_policy3 = 1.2.3.4.5.7

####################################################################
[ca]
default_ca = RootCA        # The default ca section
####################################################################
[RootCA]

dir = /opt/ca/RootCA                  # Where everything is kept
certs = $dir/certs                    # Where the issued certs are kept
crl_dir = $dir/crl                    # Where the issued crl are kept
database = $dir/index.txt             # database index file.
new_certs_dir = $dir/newcerts         # default place for new certs.
certificate = $dir/RootCA.crt         # The CA certificate
serial    = $dir/serial               # The current serial number
crlnumber = $dir/crlnumber            # the current crl number

# must be commented out to leave a V1 CRL
crl = $crl_dir/RootCA.crl             # The current CRL
private_key = $dir/private/RootCA.key # The private key
RANDFILE = $dir/private/.randRootCA   # private random number file
x509_extensions = user_cert           # The extentions to add to the cert
name_opt = ca_default                 # Subject Name options
cert_opt = ca_default                 # Certificate field options
default_days = 3650                   # how long to certify for
default_crl_days = 30                 # how long before next CRL
default_md = sha512                   # use public key default MD
preserve = no                         # keep passed DN ordering
policy = policy_anything              # CHANGE THIS
####################################################################
[IssuingCA]

dir = /opt/ca/IssuingCA               # Where everything is kept
certs = $dir/certs                    # Where the issued certs are kept
crl_dir = $dir/crl                    # Where the issued crl are kept
database = $dir/index.txt             # database index file.
new_certs_dir = $dir/newcerts         # default place for new certs.
certificate = $dir/IssuingCA.crt      # The CA certificate
serial = $dir/serial                  # The current serial number
crlnumber = $dir/crlnumber            # the current crl number

# must be commented out to leave a V1 CRL
crl = $crl_dir/IssuingCA.crl              # The current CRL
private_key = $dir/private/IssuingCA.key  # The private key
RANDFILE = $dir/private/.randIssuingCA    # private random number file
x509_extensions = user_cert               # The extentions to add to the cert
name_opt = ca_default                     # Subject Name options
cert_opt = ca_default                     # Certificate field options
default_days = 3650                       # how long to certify for
default_crl_days = 30                     # how long before next CRL
default_md = sha512                       # use public key default MD
preserve = no                             # keep passed DN ordering
policy = policy_match
####################################################################
[policy_match]

countryName = match
stateOrProvinceName = match
organizationName = match
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
####################################################################
[policy_anything]

countryName = optional
stateOrProvinceName = optional
localityName  = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
####################################################################
[req]

default_bits = 2048
default_keyfile = privkey.pem
distinguished_name = req_distinguished_name
attributes = req_attributes
x509_extensions = root_ca
string_mask = utf8only
####################################################################
[req_distinguished_name]

countryName = Country Name (2 letter code)
countryName_default = DE
countryName_min = 2
countryName_max = 2
stateOrProvinceName = State or Province Name (Bayern)
stateOrProvinceName_default = Bayern
localityName = Locality Name (Muenchen)
localityName_default = Muenchen
0.organizationName = Organization Name (Company name or your Name)
0.organizationName_default = HTDOM Company GmbH
organizationalUnitName = Organizational Unit Name (Department)
organizationalUnitName_default = IT
commonName = Common Name (Server FQDN or your Name)
commonName_max = 64
emailAddress = Email Address
emailAddress_max = 64
####################################################################
[req_attributes]

challengePassword = A challenge password
challengePassword_min = 4
challengePassword_max = 20
unstructuredName = An optional company name
####################################################################
[v3_req]

# Extensions to add to a certificate request
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment

## Key Usage (Schlüsselverwendung)
# decipherOnly: Ist keyAgreement gesetzt, darf der Public-Key innerhalb eines Schlüsselaustausche zur Entschlüsselung von Daten verwendet werden. Andernfalls undefiniert.
# encipherOnly: Ist keyAgreement gesetzt, darf der Public-Key innerhalb eines Schlüselaustausches zur Verschlüsselung von Daten verwendet werden. Andernfalls undefiniert.
# cRLSign: Public-Key kann verwendet werden, um CRLs zu verifizieren.
# keysCertSign: Public-Key kann verwendet werden, um Zertifikate zu verifizieren.
# keyAgreement: Zur Verwendung beim Schlüsselaustausch.
# dataEncipherment: Zur Verwendung von „normalen“ Daten, also kein Schlüsseln.
# keyEncipherment: Public-Key wird zum Schlüsselmanagement verwendet.
# nonRepudiation: Key zur Prüfung von „bewußten“ Signaturen (außer CRLs und bei Zertifikaten).
# digitalSignature: Key zur Prüfung von „automatischen“ Signaturen (außer CRLs und bei Zertifikaten).
## keyUsage = [critical,] [decipherOnly,] [encipherOnly,] [cRLSign,] [keysCertSign,] [keyAgreement,] [dataEncipherment,] [keyEncipherment,] [nonRepudiation,] [digitalSignature]

## Extended Key Usage (Erweiterte Schlüsselverwendung)
# serverAuth: Authentisierung von Web-Servern durch Web-Clients
# clientAuth: Authentisierung von Web-Clients durch Web-Server
# codeSigning: Key zur Signierung von Programm-Code
# emailProtection: Key zur Verwendung mit S/MIME-Software
# timStamping: Signierung von Objekt-Hashwerten und zugehörigen vertrauenswürdigen Zeitstempeln

## Microsoft-Extensions
# msCodeInd: Individual Code Signing
# msCodeCom: Commercial Code Signing
# msCTLSign: Trust List Sign
# msSGC: Server-Zertifikat mit „Global Server ID“
# msEFS: Verschlüsselung von symmetrischen Keys zur Dateisystem-Verschlüselung

## Netscape-Extensions
# nsSGC: Server-Zertifikat mit "Global Server ID"
## keyUsage = [critical,] [serverAuth,] [clientAuth,] [codeSigning,] [emailProtection,] [timeStamping,] [msCodeInd,] [msCodeCom,] [msCTLSign,] [msSGC,] [msEFS,] [nsSGC,] [OID]

# [v3_req]
# Extensions to add to a certificate request
# basicConstraints = CA:FALSE
# keyUsage = nonRepudiation, digitalSignature, keyEncipherment
# subjectAltName = @alt_names

# [alt_names]
# DNS.1 = servername.domain.de
# DNS.2 = servername
# DNS.3 =
# IP.1 = 192.168.xxx.yyy
# IP.2 = 192.168.yyy.zzz
# IP.3 =
####################################################################
[root_ca]

subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer
basicConstraints = critical, CA:true, pathlen:1
keyUsage = cRLSign, keyCertSign
subjectAltName=email:copy

# URI of the CA certificate 
authorityInfoAccess = caIssuers;URI:http://server.domain.de/RootCA.html
crlDistributionPoints=URI:http://server.domain.de/RootCA.crl
####################################################################
[issuingca_cert]

subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer
basicConstraints = critical, CA:true, pathlen:0
keyUsage = cRLSign, keyCertSign
subjectAltName=email:copy

# URI of the CA certificate 
authorityInfoAccess = caIssuers;URI:http://server.domain.de/IssuingCA.html
crlDistributionPoints=URI:http://server.domain.de/IssuingCA.crl
####################################################################
[user_cert]

basicConstraints=CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer
subjectAltName=email:copy
extendedKeyUsage = clientAuth, emailProtection, codeSigning

# URI of the CA certificate 
authorityInfoAccess = caIssuers;URI:http://server.domain.de/IssuingCA.html
crlDistributionPoints=URI:http://server.domain.de/IssuingCA.crl 
####################################################################
[server_cert]

basicConstraints=CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth

# URI of the CA certificate 
authorityInfoAccess = caIssuers;URI:http://server.domain.de/IssuingCA.html 
crlDistributionPoints=URI:http://server.domain.de/IssuingCA.crl
####################################################################
[crl_ext]

authorityKeyIdentifier=keyid:always
####################################################################

Root Certificate Authority einrichten

## Ordnerstruktur für die RootCA anlegen
##
mkdir -p /opt/ca/RootCA
cd /opt/ca/RootCA

# certs - werden kopien der ausgestellten Zertifikate gespeichert
# crl -  wird eine kopie aller erstellen CRL’s gespeichert
# newcerts - wird eine kopie aller Zertifikats Requeste gespeichert
# private - Wird der private Schlüssel der Zertifizierungsstelle gespeichert
# revoke - hierhin werden alle gesperrten Zertifikate verschoben

mkdir certs crl newcerts private revoke

touch index.txt
echo "01" > serial
echo "01" > crlnumber

chmod 0600 private/

## Hier wird ein Random Nummer für die spätere Schlüsselerstellung generiert
##
openssl rand -out private/.randRootCA 8192
chmod 0400 private/.randRootCA

## Privaten Key für RootCA erstellen
##
openssl genrsa -aes256 -out private/RootCA.key 4096 -rand private/.randRootCA
2 x Passphrase eingeben (Hier sollte in einer Live Umgebung ein sehr komplexes Kennwort von min. 15-20 Stellen verwendet werden)
chmod 0400 private/RootCA.key

## Erstelle das Selbssignierte RootCA Zertifikat
##
openssl req -new -x509 -days 3650 -sha512 -key private/RootCA.key -out RootCA.crt -config ca-config.cnf
2 x Passphrase eingeben

Country Name (2 letter code) [DE]:DE
State or Province Name (Bayern) [Some-State]:Bayern
Locality Name (eg, Muenchen) []:Muenchen
Organization Name (eg, company) [Example Organisation]:HTDOM Company GmbH
Organizational Unit Name (eg, section) []:IT-Security
Common Name (e.g. server FQDN or YOUR name) []:HTDOM Root Certificate Authority
Email Address []:

Issuing Certificate Authority einrichten

## Ordnerstruktur für die IssuingCA anlegen
##
mkdir /opt/ca/IssuingCA
cd /opt/ca/IssuingCA
cp /opt/ca/RootCA/ca-config.cnf .

# certs - werden kopien der ausgestellten Zertifikate gespeichert
# crl -  wird eine kopie aller erstellen CRL’s gespeichert
# newcerts - wird eine kopie aller Zertifikat Requeste gespeichert
# private - wird der private Schlüssel der Zertifizierungsstelle gespeichert
# revoke - hier werden alle gesperrten zertifikate verschoben

mkdir certs crl newcerts private revoke

touch index.txt
echo "01" > serial
echo "01" > crlnumber

chmod 0600 private/

## Hier wird ein Random Nummer für die spätere Schlüsselerstellung generiert
##
openssl rand -out private/.randIssuingCA 8192
chmod 0400 private/.randIssuingCA

## Privaten Key für IssuingCA erstellen
##
openssl genrsa -aes256 -out private/IssuingCA.key 4096 -rand private/.randIssuingCA
2 x Passphrase eingeben (Hier sollte in einer Live Umgebung ein sehr komplexes Kennwort von min. 15-20 Stellen verwendet werden)
chmod 0400 private/IssuingCA.key

## Ertselle einen Zertifikat Request, der von der RootCA signiert wird.
##
openssl req -new -key private/IssuingCA.key -out newcerts/IssuingCA-Request.csr -config ca-config.cnf
2 x Passphrase eingeben

Country Name (2 letter code) [DE]:DE
State or Province Name (Bayern) [Some-State]:Bayern
Locality Name (eg, Muenchen) []:Muenchen
Organization Name (eg, company) [Example Organisation]:HTDOM Company GmbH
Organizational Unit Name (eg, section) []:IT-Security
Common Name (e.g. server FQDN or YOUR name) []:HTDOM Issuing Certificate Authority
Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

Issuing Certificate Request genemigen

cd /opt/ca/RootCA

## Zertifikats Request der IssuingCA bei der RootCA signieren
##
openssl ca -name RootCA -in /opt/ca/IssuingCA/newcerts/IssuingCA-Request.csr -out /opt/ca/RootCA/certs/IssuingCA.crt -extensions issuingca_cert -config ca-config.cnf

Using configuration from ca-config.cnf
Enter pass phrase for /opt/ca/RootCA/private/RootCA.key:
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Sep 19 20:19:10 2016 GMT
            Not After : Sep 17 20:19:10 2026 GMT
        Subject:
            countryName               = DE
            stateOrProvinceName       = Bayern
            localityName              = Muenchen
            organizationName          = HTDOM Company GmbH
            organizationalUnitName    = IT-Security
            commonName                = HTDOM Issuing Certificate Authority
            emailAddress              = 
        X509v3 extensions:
            X509v3 Subject Key Identifier: 
                98:D9:DE:BB:D1:27:44:51:B3:F0:07:BD:95:59:39:3A:24:14:10:29
            X509v3 Authority Key Identifier: 
                keyid:7A:D8:D3:65:45:3F:C6:FF:7D:91:1F:15:53:6D:F8:0D:BA:E7:E3:8F

            X509v3 Basic Constraints: critical
                CA:TRUE, pathlen:0
            X509v3 Key Usage: 
                Certificate Sign, CRL Sign
            X509v3 Subject Alternative Name: 
                email:
            Authority Information Access: 
                CA Issuers - URI:http://server.domain.de/RootCA.html

            X509v3 CRL Distribution Points: 

                Full Name:
                  URI:http://server.domain.de/RootCA.crl

Certificate is to be certified until Sep 17 20:19:10 2026 GMT (3650 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

Webserver Zertifikat erstellen

cd /opt/ca/IssuingCA

openssl genrsa -aes256 -out private/webserver01_htdom_local.key 2048 -rand private/.randIssuingCA
chmod 0400 private/webserver01_htdom_local.key
 
openssl req -new -key private/webserver01_htdom_local.key -out newcerts/webserver01_htdom_local.csr -config ca-config.cnf

openssl ca -name IssuingCA -in newcerts/webserver01_htdom_local.csr -out certs/webserver01_htdom_local.crt -extensions server_cert -config ca-config.cnf

Using configuration from ca-config.cnf
Enter pass phrase for /opt/ca/IssuingCA/private/IssuingCA.key:
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Sep 19 20:54:03 2016 GMT
            Not After : Sep 17 20:54:03 2026 GMT
        Subject:
            countryName               = DE
            stateOrProvinceName       = Bayern
            organizationName          = HTDOM Company GmbH
            organizationalUnitName    = IT-Support
            commonName                = webserver01.htdom.local
            emailAddress              = 
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            X509v3 Key Usage: 
                Digital Signature, Non Repudiation, Key Encipherment, Data Encipherment
            X509v3 Extended Key Usage: 
                TLS Web Server Authentication
            Authority Information Access: 
                CA Issuers - URI:http://server.domain.de/RootCA.html

            X509v3 CRL Distribution Points: 

                Full Name:
                  URI:http://server.domain.de/RootCA.crl

Certificate is to be certified until Sep 17 20:54:03 2026 GMT (3650 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

Certification Revocation List erstellen

## Unabhängig ob gesperrte Zertifikate existieren oder nicht sollte eine Sperrliste für das Root/Issuing Zertifikat erstellt werden
##
cd /opt/ca/RootCA
openssl ca -config ca-config.cnf -gencrl -out RootCA.crl

cd /opt/ca/IssuingCA
openssl ca -config ca-config.cnf -gencrl -out IssuingCA.crl

Zertifikate wiederrufen

## Wird ein Zertifikat gesperrt, so ist die Sperrung in index.txt einzutragen
##
cd /opt/ca/IssuingCA
openssl ca -config ca-config.cnf -revoke certs/webserver01_htdom_local.crt

Nützliche Befehle

## Zertifikate und Private Keys überprüfen
##
## In diesen Beispiel wir der Private Key überprüft ob dieser mit dem Zertifikat zusammenpasst
## In dem Abschnitt modules, sieht man den Privaten Key
##
openssl x509 -noout -text -in /opt/ca/RootCA/RootCA.crt | less
openssl rsa -noout -text -in /opt/ca/RootCA/private/RootCA.key | less
Passphrase

modulus:
  00:ce:50:8a:8d:5e:8b:8d:47:38:b4:b0:25:d2:57:
  ...
  1b:56:ff

Modulus:
  00:ce:50:8a:8d:5e:8b:8d:47:38:b4:b0:25:d2:57:
  ...
  1b:56:ff

openssl x509 -noout -text -in /opt/ca/IssuingCA/IssuingCA.crt | less
openssl rsa -noout -text -in /opt/ca/IssuingCA/private/IssuingCA.key | less
Passphrase

## Zertifikatsrequest überprüfen, ob alle Angaben passen.
##
openssl req -noout -text -in /opt/ca/IssuingCA/newcerts/IssuingCA-Request.csr | less


## RootCA und IssuingCA Zertifikat überprüfen
##
openssl verify -CAfile /opt/ca/RootCA/RootCA.crt /opt/ca/IssuingCA/IssuingCA.crt
/opt/ca/IssuingCA/IssuingCA.crt: OK


## Zertifikat Chain aus RootCA und IssuingCA bilden
##
cat /opt/ca/IssuingCA/IssuingCA.crt /opt/ca/RootCA/RootCA.crt > /opt/ca/IssuingCA/HTDOM_IssuingCA_Chain.crt
chmod 444 /opt/ca/IssuingCA/HTDOM_IssuingCA_Chain.crt


## RootCA Zertifikat auf Windows Rechner downloaden und installieren
##
cat /opt/ca/RootCA/RootCA.crt | sed -n -e '/BEGIN\ CERTIFICATE/,/END\ CERTIFICATE/ p'

-----BEGIN CERTIFICATE-----
MIIGlzCCBH+gAwIBAgIJAMEh+l6C/y+PMA0GCSqGSIb3DQEBDQUAMIGPMQswCQYD
...
GPKo9XOLXNQhcWvo9J4cekWimz8z1Aj1YkEFkwKopY0+549r1W+H+OnZ1u0d77Zt
iw4t1xMigeji4qU=
-----END CERTIFICATE-----

## Zertifikat Chain auf Windows Rechner downloaden und installieren
##
cat /opt/ca/IssuingCA/HTDOM_IssuingCA_Chain.crt | sed -n -e '/BEGIN\ CERTIFICATE/,/END\ CERTIFICATE/ p'

-----BEGIN CERTIFICATE-----
MIIGmDCCBICgAwIBAgIBATANBgkqhkiG9w0BAQ0FADCBjzELMAkGA1UEBhMCREUx
...
Jt3lzRluOVcEZY4m
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIGlzCCBH+gAwIBAgIJAMEh+l6C/y+PMA0GCSqGSIb3DQEBDQUAMIGPMQswCQYD
...
iw4t1xMigeji4qU=
-----END CERTIFICATE-----

Da kein Computer dieser Welt unsere CA kennt, müssen wir natürlich das Root CA Zertifikat und Issuing CA Zertifikat auf jeden Computer installieren.
Dazu lege ich mir eine RootCA.txt und eine IssuingCA.txt Datei lokal auf dem Computer an und hole mir wie oben beschrieben die Zertifikatsinformationen.

Wenn beide Text Dateien gefüllt sind, werden dies in *.crt umbenannt, danach installiere ich diese unter Windows in den passenden Zertifikatsspeicher.
Das RootCA Zertifikat wird in den „Vertrauenswürdige Stammzertifizierungsstelle“ installiert.

 

 

 

 

 

Und das Issuing CA Zertifikat wird unter „Zwischenzertifizierungsstelle“ installiert.

 

 

 

 

 

Wenn beide Zertifikate sauber installiert wurde, kann man sich das Zertifikat ansehen, in dem das man es doppelklickt und sich alle Informationen ansieht.

 

 

 

 

 

Unter Linux ist das ganze ein bisschen einfacher, hierzu kopiert man beide Zertifikate in den Zertifikatsspeicher und lässt ein Update laufen, danach sind dem Linux Server/Client die Zertifikate bekannt.

cp /opt/ca/RootCA/RootCA.crt /usr/local/share/ca-certificates/
cp /opt/ca/IssuingCA/HTDOM_IssuingCA_Chain.crt /usr/local/share/ca-certificates/
update-ca-certificates
Updating certificates in /etc/ssl/certs...
2 added, 0 removed; done.
Running hooks in /etc/ca-certificates/update.d...
done.

ls -la /etc/ssl/certs/RootCA*
lrwxrwxrwx 1 root root 43 Jan 22 12:57 /etc/ssl/certs/RootCA.pem -> /usr/local/share/ca-certificates/RootCA.crt

ls -la /etc/ssl/certs/HTDOM_IssuingCA_Chain.pem
lrwxrwxrwx 1 root root 58 Jan 22 12:57 /etc/ssl/certs/HTDOM_IssuingCA_Chain.pem -> /usr/local/share/ca-certificates/HTDOM_IssuingCA_Chain.crt

So nun viel Spaß beim ausprobieren.

Viele Grüße
Helmut

 

 

 

 

 

Nach der Grundinstallation von Ubuntu 16.04 LTS Desktop, wird das System auf den neusten Stand gebracht.

sudo su - oder sudo -i
apt update -y && apt upgrade -y

Nach dem das System up to date ist, kann man manuell die Netzwerkkarte konfigurieren, wichtig ist hier das der DNS Server vom Domaincontroller angesprochen wird.

cp /etc/hosts{,.old}
nano /etc/hosts

##### /etc/hosts ##################################
127.0.0.1 localhost
192.168.xxx.xxx clienthostname.htdom.local clienthostname
192.168.xxx.xxx ads01.htdom.local ads01 htdom.local
###################################################

dig -t SRV _ldap._tcp.htdom.local | grep -A2 "ANSWER SECTION

;; ANSWER SECTION:
_ldap._tcp.htdom.local. 600 IN SRV 0 100 389 ads01.htdom.local.

apt install fping

fping ads01.htdom.local
fping htdom.local
fping ads01
ads01.htdom.local is alive

Wenn der DNS Server für den Client konfiguriert wurde, installieren wir alle benötigten Pakete um den Client an das AD anzubinden.

apt install realmd sssd sssd-tools samba-common krb5-user packagekit samba-common-bin samba-libs adcli ntp vim -y

NTP Service konfigurieren

cp /etc/ntp.{conf,old}
nano /etc/ntp.conf

##### /etc/ntp.conf ###############################
server ads01.htdom.local
################################################### 

systemctl start ntp.service
systemctl status ntp.service

Realmd konfigurieren

nano /etc/realmd.conf

##### /etc/realmd.conf ############################
[users]
default-home = /home/%D/%U
  ## default-home = /home/%U@%D
  ## default-home = /nfs/home/%D-%U
default-shell = /bin/bash
  ## default-shell = /bin/sh

[active-directory]
default-client = sssd
  ## default-client = winbind
os-name = Ubuntu Linux Desktop
os-version = 16.04

[service]
automatic-install = no
  ## automatic-install = yes

[htdom.local]
computer-ou = OU=Clients,OU=Company,DC=htdom,DC=local
fully-qualified-names = no
automatic-id-mapping = yes
user-principal = yes
manage-system = no
###################################################

 

default-home: set the default homedir for each Active Directory User. In our example it will be something like /home/dom.example.int/domainuser.
default-shell: the default shell used by the users. bash is usually the preferred default shell.

default-client: we are using sssd in our scenario. winbind is also a possible option.
os-name: the operating system name as it will appear in our Active Directory.
os-version: the operating system version as it will appear in our Active Directory.

automatic-install: we want to prevent realmd to try to install its dependencies.

fully-qualified-names: this will allow users to use just their username instead of the combination of domain and username. For example we can use the username domainuser instead of DOM\domainuser or domainuser@dom.example.int. Note, however, that this could cause conflicts with local users, if they have the same username as a domain user.
automatic-id-mapping: this option will auto-generate the user and group ids (UID, GID) for newly created users, if set to yes.
user-principal: this will set the necessary attributes for the Ubuntu machine when it joins the domain.
manage-system: if you don’t want policies from the Active Directory environment to be applied on this machine, set this option to no.

 

Kerberos konfigurieren

cp /etc/krb5.{conf,old} && rm -rf /etc/krb5.conf
nano /etc/krb5.conf

##### /etc/krb5.conf ##############################
[logging]
	default = FILE:/var/log/krb5/krb5.log
	kdc = FILE:/var/log/krb5/krb5kdc.log
	admin_server = FILE:/var/log/krb5/kadmind.log

[libdefaults] 
	default_realm = HTDOM.LOCAL
	clockskew = 300

## The following krb5.conf variables are only for MIT Kerberos. 
	kdc_timesync = 1 
	ccache_type = 4 
	forwardable = true 
	proxiable = true 

[realms] 
	HTDOM.LOCAL = {
	kdc = ads01.htdom.local
  default_domain = htdom.local
  admin_server = ads01.htdom.local
}
 
[domain_realm] 
	.htdom.local = HTDOM.LOCAL
	htdom.local = HTDOM.LOCAL
###################################################

Client zur Domain hinzufügen

realm discover htdom.local
realm --verbose join htdom.local --user-principal=administrator@HTDOM.LOCAL

## Wer darf sich am System anmelden?
realm deny --all
realm permit helmut.thurnhofer
realm list

## Alle Domainadmins dürfen sich am System anmelden.
realm permit --groups Domänen-Admins@htdom.local

## Domain Admins der sudoers hinzufügen
visudo
%Domänen-Admins@htdom.local ALL=(ALL:ALL) ALL

AD Account berechtigen
usermod -a -G adm,cdrom,sudo,dip,plugdev,lpadmin,sambashare username

SSSD konfigurieren

cat /etc/sssd/sssd.conf

## cp /etc/sssd/sssd.{conf,old} && rm -rf /etc/sssd/sssd.conf
## nano /etc/sssd/sssd.conf

### /etc/sssd/sssd.conf ###########################
[sssd]
  domains = htdom.local
  config_file_version = 2
  services = nss, pam

[domain/htdom.local]
  ad_domain = htdom.local
  krb5_realm = HTDOM.LOCAL
  realmd_tags = joined-with-adcli
  cache_credentials = True
  id_provider = ad
  krb5_store_password_if_offline = True
  default_shell = /bin/bash
  ldap_id_mapping = True
  use_fully_qualified_names = False
  fallback_homedir = /home/%d/%u
  simple_allow_users = $
  access_provider = simple
###################################################

ls -la /etc/sssd/sssd.conf
-rw------- 1 root root 486 Sep 18 01:07 /etc/sssd/sssd.conf
## chown root:root /etc/sssd/sssd.conf
## chmod 600 /etc/sssd/sssd.conf

systemctl start sssd.service
systemctl enable sssd.service
systemctl status sssd.service

Pam common-session konfigurieren für das Home Laufwerk

cp /etc/pam.d/common-session /etc/pam.d/common-session.old
nano /etc/pam.d/common-session

session required pam_mkhomedir.so umask=0022 skel=/etc/skel
## echo "session required pam_mkhomedir.so skel=/etc/skel/ umask=0022" | sudo tee -a /etc/pam.d/common-session

Ubuntu 16.04 Login anpassen

nano /usr/share/lightdm/lightdm.conf.d/50-ubuntu.conf

greeter-show-manual-login=true
greeter-hide-users=true

So das war es schon wieder

Viel Spaß damit
Gruß Helmut

Hallo zusammen,

in dem heutigen Howto zeige ich euch ein kleines Powershell Skript, wie Ihr Logdateien in Realtime monitoren könnt.
Folgenden Zeilen im Skript sollten angepasst werden, über diese Variablen könnt Ihr das Monitoring steuern.

Im Header des Skripts habe ich den Ablauf dokumentiert, sollten noch Fragen aufkommen, Ihr wisst wie Ihr mich erreichen könnt.

## $EmailPasswortFile = "D:\PowershellScripte\MailPasswort.txt"
$LogFiletoCheck = "D:\PowershellScripte\MyLogFiles.txt"
$ScriptSleepTimeOut = 10 ## 10 Sekunden Pause in der Skript Schleife
$ScriptLoopTime = 5 ## 5 Minuten Skriptlaufzeit
$EventCheckCount = 15 ## Überprüft das Dienstprotokoll nach der Anzahl der Ereignisse, hier Maximal 15 Einträge
$EventTimeRange = 30 ## Zeitspanne für die Anzahl der Ereignisse, wenn mehr als 15 Einträge in 30 Minuten geschrieben werden, mach irgendwas (z.B. E-Mail versenden)
#########################################################################################################
##
## Name: Log Datei überwachung, Ergebnisse ins Dienstprotokoll schreiben                            
## Ersteller: Helmut Thurnhofer                    
## Erstellungsdatum: 05.01.2016                                                             
## Version: 1.0
##
#######################################################
## Skriptbeschreibung und Vorbereitung auf dem Server:
#######################################################
##
## Um mit dem Skript arbeiten zu können müssen ein paar Vorbereitungen auf dem Server getroffen werden.
## Zum einem muss die ExecutionPolicy für den auszuführenden Benutzer gesetzt werden und zum zweiten wird in der Ereignisanzeige
## ein neues Dienstprotokoll angelegt. (Zu finden unter Anwendungs- und Dienstprotokoll)
##
## Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force 
## (Die Powershell wird keine Skripte ausführen, die aus dem Internet stammen – Für unsere Aufgabe beste Wahl.)
##
## Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force 
## (Die Powershell ignoriert die digitale Signatur, fragt aber nach, ob ein Skript, das aus dem Internet stammt, ausgeführt werden soll.)
##
###################################################
## Dienstprotokoll anlegen mit folgenden Befehlen:
###################################################
##    
## New-EventLog -LogName MeinServerLog -Source Error,Fatal,Warning,Information
## Limit-EventLog -LogName MeinServerLog -MaximumSize 10485760 -OverflowAction OverwriteAsNeeded
##
## -MaximumSize 524288 = 512KB
## -MaximumSize 1048576 = 1024KB = 1MB
## -MaximumSize 10485760 = 10240KB = 10MB
## -MaximumSize 20971520 = 20480KB = 20MB
##
################################################################
## Testeinträge in das neu erstellte Dienstprotokoll schreiben:
################################################################
##
## Write-EventLog -LogName MeinServerLog -Source Information -EntryType Information -EventId 1000 -Message "Information über die PowerShell"
## Write-EventLog -LogName MeinServerLog -Source Warning -EntryType Warning -EventId 2000 -Message "Warning über die PowerShell"
## Write-EventLog -LogName MeinServerLog -Source Error -EntryType Error -EventId 3000 -Message "Error über die PowerShell"
## Write-EventLog -LogName MeinServerLog -Source Fatal -EntryType Error -EventId 4000 -Message "Fatal über die PowerShell"
##
## Für die Events wurde eigene EventIDs verwendet, Information=1000, Warnungen=2000, Error=3000, Fatal=4000
##
#############################################
## Testeinträge im Dienstprotokoll abfragen:
#############################################
##
## Get-EventLog -LogName MeinServerLog -InstanceId 3000,4000 -Newest 20
##
## $DateNow = Get-Date
## $Time30Minutes = (Get-Date).AddMinutes(-30)
## Get-EventLog -LogName MeinServerLog -EntryType Error -Before $DateNow -After $Time30Minutes
##
## Get-EventLog -LogName MeinServerLog -Source Fatal,Error
## Get-EventLog -List
##
##############################################################################################################
## Um das ganze Simulieren zu können, wurde eine leere Log Datei erstellt und mit folgenden Einträgen gefüllt.
## Die Einträge wurden Zeitversetzt über eine zweite Powershell Sitzung ausgeführt.
##############################################################################################################
##
## $Date = Get-Date
## $DateTime = $Date.ToString("yyyy-MM-dd HH:mm:ss")
## Add-Content "D:\PowershellScripte\MyLogFiles.txt" -Value "$DateTime - FATAL: 0x80070490: EvaluateApplicability failed in CCbs::EvaluateApplicability"
##
## $Date = Get-Date
## $DateTime = $Date.ToString("yyyy-MM-dd HH:mm:ss")
## Add-Content "D:\PowershellScripte\MyLogFiles.txt" -Value "$DateTime - ERROR: 0x80070432: Forced install timer expired for AUInstallType = 4"
##
## $Date = Get-Date
## $DateTime = $Date.ToString("yyyy-MM-dd HH:mm:ss")
## Add-Content "D:\PowershellScripte\MyLogFiles.txt" -Value "$DateTime - Information: 0x80000000: Successfully wrote event for AU health state:0"
## 
## $Date = Get-Date
## $DateTime = $Date.ToString("yyyy-MM-dd HH:mm:ss")
## Add-Content "D:\PowershellScripte\MyLogFiles.txt" -Value "$DateTime - Warning: 0x80202000: Warning event for AU health state were 3"
##
######################################################################
## Bitte diese Zeilen vor dem ersten Lauf im Skript ausführen, 
## Hier wird das E-Mail Benutzer Passwort als String in einen Textdatei geschrieben.
## Diese Textdatei wird für den späteren E-Mail versandt benötigt.
######################################################################
##
## (Get-Credential).Password | ConvertFrom-SecureString > $EmailPasswortFile
##
#########################################################################################################
Clear-Host

## Basisparameter für das Skript
##
## $EmailPasswortFile = "D:\PowershellScripte\MailPasswort.txt"
$LogFiletoCheck = "D:\PowershellScripte\MyLogFiles.txt"
$ScriptSleepTimeOut = 10 ## 10 Sekunden Pause in der Skript Schleife
$ScriptLoopTime = 5 ## 5 Minuten Skriptlaufzeit
$EventCheckCount = 15 ## Überprüft das Dienstprotokoll nach der Anzahl der Ereignisse, hier Maximal 15 Einträge
$EventTimeRange = 30 ## Zeitspanne für die Anzahl der Ereignisse, wenn mehr als 15 Einträge in 30 Minuten geschrieben werden, mach irgendwas (E-Mail versenden)
##
#########################################################################################################


## Basis E-Mail Server Konfiguration
##
## $ServerName = "$env:COMPUTERNAME.$env:USERDOMAIN"
## $KundenName = "Musterkunde Deutschland GmbH"
## $SMTPServer = "smtp.domain.de"
## $SMTPUserName = "Benutzername"
## Bitte diese Skriptzeile vorab ausführen damit die EmailPasswort datei erstellt wird.
##
## (Get-Credential).Password | ConvertFrom-SecureString > $EmailPasswortFile
## $SMTPUserPwd = Get-Content -Path $MailPasswortFile | ConvertTo-SecureString
## $Cred = New-Object System.Management.Automation.PSCredential $SMTPUserName, $SMTPUserPwd
##
## Basisinformationen für den E-Mail versandt.
##
## $EmailTo = empfaenger@domain.de
## $EmailFrom = absender@domain.de
## $EmailSubject = "Es wurde beim `"$KundenName`" mehr als 15 Fatal/Error Einträge in den Logs gefunden. Bitte Server: `"$ServerName`" überprüfen!"
## $EmailBody ist weiter unten im Skript definiert, da hier die Auswertung der Variaben benötigt werden.
#########################################################################################################


$LoopStartTime = Get-Date
$LoopStartTimeFormatted = $LoopStartTime.ToString("dd.MM.yyyy HH:mm:ss")

$LoopEndTime = $LoopStartTime.AddMinutes($ScriptLoopTime)
$LoopEndTimeFormatted = $LoopEndTime.ToString("dd.MM.yyyy HH:mm:ss")
## $LoopEndTime = $LoopStartTime.AddHours($ScriptLoopTime)
## $LoopEndTimeFormated = $LoopEndTime.ToString("dd.MM.yyyy HH:mm:ss")

Write-Host "`nRealtime LogFile Monitoring wurde gestartet um: $LoopStartTimeFormatted" -ForegroundColor Gray
write-host "Realtime LogFile Monitoring wird beendet um: $LoopEndTimeFormatted`n" -ForegroundColor Gray
#########################################################################################################

## Alle 10 Sekunden wird die Schleife wiederholt, bei einem Treffer im Log wird ein Ereigniseintrag geschrieben
## Wenn mehr als 15 Einträge in 30 Minuten geschrieben werden, wird eine E-Mail Versand.
## Skript Idee -- http://sion-it.co.uk/tech/powershell/loop-until-a-certain-time

Do { 
     ## Hier wird pro Schleifendurchlauf die Aktuelle Zeit geholt und neu gesetzt
     ##
     $LoopTimeNow = Get-Date
     $LoopTimeNowFormatted = $LoopTimeNow.ToString("dd.MM.yyyy HH:mm:ss")

     ## Diese Zeitangabe wird für die Suche in der Log Datei benötigt, wenn hier Einträge älter/gleich Suchzeit ist.
     ## Wird ein neuer Dienstprotokoll Eintrag geschrieben, diese Zeit sollte mit der Skriptpause übereinstimmen,
     ## ansonsten werden hier wo wöglich neue Einträge in der Log nicht gefunden, das Sie aus der Zeitrange fallen.
     ##
     $SearchTime = (Get-Date).AddSeconds(-$ScriptSleepTimeOut)
     $SearchTimeInLog = $SearchTime.ToString("yyyy-MM-dd HH:mm:ss")

     If ($LoopTimeNow -ge $LoopEndTime) {
        Write-host "Endzeit: `"$LoopEndTimeFormatted`" ist erreicht, Skript wird im nächsten Durchgang beenden."
 
     } Else {
        
        ## Überprüft die Einträge in der Log Datei, sollte was gefunden werden, wird es an die ForEach Schleife übergeben und in das Dienstprotokoll geschrieben.
        ##
        [string[]]$FatalMessages = Get-Content $LogFiletoCheck | Where-Object {($_ -ge $SearchTimeInLog) -and $_ -match "FATAL"}
        [string[]]$ErrorMessages = Get-Content $LogFiletoCheck | Where-Object {($_ -ge $SearchTimeInLog) -and $_ -match "ERROR"}
        [string[]]$WarningMessages = Get-Content $LogFiletoCheck | Where-Object {($_ -ge $SearchTimeInLog) -and $_ -match "Warning"}

        ForEach ($FatalMessage in $FatalMessages) {
        Write-EventLog -LogName enaioServerLog -Source Fatal -EntryType Error -EventId 4000 -Message "$FatalMessage"
        Write-Host "Ereigniseintrag `"$FatalMessage`" wurde erstellt." -ForegroundColor DarkRed     
        }

        ForEach ($ErrorMessage in $ErrorMessages) {
        Write-EventLog -LogName enaioServerLog -Source Error -EntryType Error -EventId 3000 -Message "$ErrorMessage"
        Write-Host "Ereigniseintrag `"$ErrorMessage`" wurde erstellt." -ForegroundColor DarkRed     
        }

        ForEach ($WarningMessage in $WarningMessages) {
        Write-EventLog -LogName enaioServerLog -Source Warning -EntryType Warning -EventId 2000 -Message "$WarningMessage"
        Write-Host "Ereigniseintrag `"$WarningMessage`" wurde erstellt." -ForegroundColor DarkYellow     
        }
            
            ## Überprüfe das Dienstprotokoll, wenn mehr als 15 Einträge in 30 Minuten geschrieben wurden, wird eine E-Mail an den Administrator versendet.
            ##
            $Count = $EventCheckCount
            $DateNow = Get-Date
            $Time30Minutes = (Get-Date).AddMinutes(-$EventTimeRange)
            $EventDate = $Time30Minutes.ToString("yyyy-MM-dd HH:mm:ss")
            $EventCount = (Get-EventLog -LogName enaioServerLog -InstanceId 3000,4000 -Before $DateNow -After $Time30Minutes).Count
            ## $EmailBody = "In den letzten 30 Minuten sind mehr als $Count (Gesamt: $EventCount) Fatal oder Error Ereigniseinträge geschrieben worden."
                    
            If($EventCount -ge $Count) {
                   
                Write-Host "`nIn den letzten 30 Minuten sind mehr als $Count (Gesamt: $EventCount) Fatal oder Error Ereigniseinträge geschrieben worden." -ForegroundColor DarkRed
                Write-Host "E-Mail wird versendet, da mehr als $Count (Gesamt: $EventCount) Fatal oder Error Ereigniseinträge geschrieben worden sind." -ForegroundColor DarkRed
                ## Aktion einfügen wie z.B. Mail versandt
                ##
                ## Send-MailMessage -Credential $Cred -SmtpServer $SMTPServer -To $EmailTo -From $EmailFrom -Subject $EmailSubject -Body $EmailBody -Encoding ([System.Text.Encoding]::UTF8)
            
            } Else {

                Write-Host "`nIn den letzten 30 Minuten sind weniger als $Count (Gesamt: $EventCount) Fatal oder Error Ereigniseinträge geschrieben worden." -ForegroundColor DarkGreen
                Write-Host "E-Mail wird nicht versendet, da weniger als $Count (Gesamt: $EventCount) Fatal oder Error Ereigniseinträge geschrieben worden sind." -ForegroundColor DarkGreen
            }

        ## Statusmeldung, wie lange das Skript noch ausgeführt wird
        ##
        Write-Host "Skript wird noch nicht beendet, es läuft noch bis `"$LoopEndTimeFormatted`"" -ForegroundColor Gray
     }

 ## Skriptpause bis die Schleife wiederholt wird
 ##
 Start-Sleep -Seconds $ScriptSleepTimeOut

}
## Skript wird nach Erreichen der Angegeben Zeit beendet
##
Until ($LoopTimeNow -ge $LoopEndTime)

Wie immer freue ich mich über Kommentare und Anregungen.

Viele Grüße
Helmut

Hallo zusammen,

in dem heutigen Howto zeige ich euch ein kleines Skript, wie Ihr eure Powershell Umgebung auf allen Computern/Server gleich setzen könnt.

Powershell_Konsole

 

 

 

 

 

Powershell_Konsole_2

 

 

 

 

 

Bitte vor der Skript Ausführung eure ExecutionPolicy setzen

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force

Damit Powershell immer ein Startverzeichnis hat, bitte die passende Variable im Skript setzen

$StartFolder="C:\ oder D:\DeinVerzeichnis"

Und hier das Skript

#######################################################################################
## Skript:  Powershell Profil Datei anlegen
## Name:    Helmut Thurnhofer
## Datum:   03.01.2016
## Version: 1.0
##
## Powershell Konsolen Anpassung
## https://tobivnext.wordpress.com/2012/03/07/powershell-konsoleneigenschaften-anpassen/
##
## Bitte vor Skriptausführung ExecutionPolicy setzen
## Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force
##
## Bitte auch einen passenden Startverzeichnis für Powershell setzen 
## $StartFolder="C:\ oder D:\DeinVerzeichnis"
#######################################################################################
 
## Skript Variablen definieren ########################################################
$DateTime = (Get-Date -Format g)
$ProfileFile = $PROFILE.CurrentUserAllHosts
$SplitProfileFile = Split-Path -Path $ProfileFile -Leaf -Resolve
$SplitProfilePath = Split-Path -Path $ProfileFile -Parent -Resolve
$BackupProfileFile = $SplitProfilePath + "\" + "profile.bak"
$CheckProfileFile = Test-Path -PathType Leaf $ProfileFile
$StartFolder="D:\PowershellScripte"
#######################################################################################
 
## Startverzeichnis anlegen wenn noch nicht vorhanden #################################
If (!(Test-Path -Path $StartFolder)){
 
     New-Item -Type Directory -Path $StartFolder
     Write-Host "Der Ordner $StartFolder wurde angelegt" -ForegroundColor Green
} Else {
    Write-Host "Der Ordner $StartFolder existiert bereits." -ForegroundColor Yellow
}
#######################################################################################
 
 
## Überprüfe ob alte profil.ps1 Datei vorhanden ist, wenn ja, wird diese umbenannt und neu angelegt.
If($CheckProfileFile -eq $true) {
    Rename-Item -Path $ProfileFile -NewName $BackupProfileFile
    Write-Host "Powershell Profil Datei (`"$BackupProfileFile`") wurde umbenannt!`n" -ForegroundColor Yellow
 
    New-Item -ItemType File -Force $ProfileFile
    Write-Host "Powershell Profil Datei (`"$ProfileFile`") wurde neu angelegt!`n" -ForegroundColor Green
} Else {
    New-Item -ItemType File -Force $ProfileFile
    Write-Host "Powershell Profil Datei (`"$ProfileFile`") wurde neu angelegt!`n" -ForegroundColor Green
}
#######################################################################################


## Schreibe Inhalt in die profile.ps1 Datei
Add-Content $ProfileFile -Value "#####################################################################################"
Add-Content $ProfileFile -Value "## Name: Windows PowerShell Profil"
Add-Content $ProfileFile -Value "## Ersteller: $env:USERNAME"
Add-Content $ProfileFile -Value "## Erstellungsdatum: $DateTime"
Add-Content $ProfileFile -Value "## Version: 1.0"
Add-Content $ProfileFile -Value "#####################################################################################"
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "## Skript von http://www.zerrouki.com/powershell-profile-example"
Add-Content $ProfileFile -Value "`$IPAddress=@(Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object {`$_.DefaultIpGateway})[0].IPAddress[0]"
Add-Content $ProfileFile -Value "`$PSVersion=(`$PSVersionTable.PSVersion).ToString()"
Add-Content $ProfileFile -Value "Clear-Host"
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "Write-Host `"``r``n:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::`" -ForegroundColor Yellow"
Add-Content $ProfileFile -Value "Write-Host `"::`" -ForegroundColor Yellow -nonewline; Write-Host `"  ComputerName: `$(`$env:COMPUTERNAME)`";"
Add-Content $ProfileFile -Value "Write-Host `"::`" -ForegroundColor Yellow -nonewline; Write-Host `"  IP-Adresse:   `$IPAddress`";"
Add-Content $ProfileFile -Value "Write-Host `"::`" -ForegroundColor Yellow -nonewline; Write-Host `"  UserName:     `$env:UserDomain\`$env:UserName`";"
Add-Content $ProfileFile -Value "Write-Host `"::`" -ForegroundColor Yellow -nonewline; Write-Host `"  Powershell:   `$PSVersion`" -NoNewline;"
Add-Content $ProfileFile -Value "Write-Host `"``r``n:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::`" -ForegroundColor Yellow"
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "`$AllDisk = @()"
Add-Content $ProfileFile -Value "Get-WmiObject Win32_LogicalDisk -filter `"DriveType='3'`" | ForEach-Object {"
Add-Content $ProfileFile -Value "   `$AllDisk += @(`$_ | Select @{n=`"Name`";e={`$_.Caption}},"
Add-Content $ProfileFile -Value "   @{n=`"Bezeichnung`";e={`$_.VolumeName}},"
Add-Content $ProfileFile -Value "   @{n=`"Groesse (GB)`";e={`"{0:N2}`" -f (`$_.Size/1GB)}},"
Add-Content $ProfileFile -Value "   @{n=`"Belegt (GB)`";e={`"{0:N2}`" -f ((`$_.Size/1GB) - (`$_.FreeSpace/1GB))}},"
Add-Content $ProfileFile -Value "   @{n=`"Frei (GB)`";e={`"{0:N2}`" -f (`$_.FreeSpace/1GB)}},"
Add-Content $ProfileFile -Value "   @{n=`"Frei (%)`";e={if(`$_.Size) {`"{0:N2}`" -f ((`$_.FreeSpace/1GB) / (`$_.Size/1GB) * 100 )} else {`"NAN`"} }})"
Add-Content $ProfileFile -Value "}"
Add-Content $ProfileFile -Value "`$AllDisk | Format-Table -AutoSize | Out-String"
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "## Globale Standardvariablen setzen"
Add-Content $ProfileFile -Value "`$ErrorActionPreference = `"Continue`""
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "## Setzen das Startverzeichnis"
Add-Content $ProfileFile -Value "Set-Location -Path $StartFolder"
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "## Angepasster Powershell Titel"
Add-Content $ProfileFile -Value "`$a = (Get-Host).UI.RawUI"
Add-Content $ProfileFile -Value "`$a.WindowTitle = `"HTDOM - Powershell`""
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "## Angepasster PowerShell Prompt"
Add-Content $ProfileFile -Value "function prompt {"
Add-Content $ProfileFile -Value "`$msg = `"HTDOM `$(`$ExecutionContext.SessionState.Path.CurrentLocation)`$(`'>`' * (`$NestedPromptLevel + 1))`""
Add-Content $ProfileFile -Value "Write-Host -ForegroundColor Yellow -NoNewLine `$msg; `" `""
Add-Content $ProfileFile -Value "`}"
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "## Setzt bestimmte Alias und Funktionen"
Add-Content $ProfileFile -Value "function pss{Set-Location -Path $StartFolder}"
Add-Content $ProfileFile -Value "function c{Set-Location -Path C:\}"
Add-Content $ProfileFile -Value "function d{Set-Location -Path D:\}"
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "function ..{cd ..}"
Add-Content $ProfileFile -Value "function ...{cd ..\..}"
Add-Content $ProfileFile -Value "function ....{cd ..\..\..}"
Add-Content $ProfileFile -Value "function .....{cd ..\..\..\..}"
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "function ws{Set-Location -Path C:\Windows\System32}"
Add-Content $ProfileFile -Value "function npp{notepad `$PROFILE.CurrentUserAllHosts}"
Add-Content $ProfileFile -Value "function np{Start-Process -FilePath `"C:\Program Files (x86)\Notepad++\notepad++.exe`" -Verb RunAs}"
Add-Content $ProfileFile -Value "function ise{Start-Process -FilePath `"C:\Windows\System32\WindowsPowerShell\v1.0\powershell_ise.exe`" -Verb RunAs}"
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "function kb(`$id){Start-Process -FilePath `"http://support.microsoft.com/kb/`$id`"}"
Add-Content $ProfileFile -Value "function mwst(`$betrag, `$satz = 19) {`$betrag / 100 * `$satz}"
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "function applog{Get-EventLog -LogName Application -Newest 50}"
Add-Content $ProfileFile -Value "function syslog {Get-EventLog -LogName System -Newest 50}"
Add-Content $ProfileFile -Value ""
Add-Content $ProfileFile -Value "function gco(`$Cmdlet){Get-Command `$Cmdlet -CommandType Cmdlet}"
Add-Content $ProfileFile -Value "function about{Get-Help about_* | Select name, synopsis | Format-Table -AutoSize}"
Add-Content $ProfileFile -Value "function module{Get-Module -ListAvailable | Where-Object {`$_.Path -like `"`$PSHOME*`"}}"
#######################################################################################

## Profil in der aktuellen Sitzung laden
. $PROFILE.CurrentUserAllHosts
#######################################################################################

## Erstelle Regkeys für HKEY_CURRENT_USER\Console
$RegPath1="HKCU:\Console"
Set-Location -Path $RegPath1

## Konsolenfarben setzen
New-ItemProperty . ColorTable00 -type DWORD -value 0x00222827 -Force
New-ItemProperty . ColorTable03 -type DWORD -value 0x00141817 -Force
New-ItemProperty . ColorTable07 -type DWORD -value 0x00f2f8f8 -Force
New-ItemProperty . ColorTable09 -type DWORD -value 0x00efd966 -Force
New-ItemProperty . ColorTable10 -type DWORD -value 0x002ee2a6 -Force
New-ItemProperty . ColorTable12 -type DWORD -value 0x007226f9 -Force
New-ItemProperty . ColorTable14 -type DWORD -value 0x0074dbe6 -Force

## Schriftart und zusätzlich Optionen setzen
New-ItemProperty . CurrentPage -type DWORD -value 0x00000003 -Force
New-ItemProperty . CursorSize -type DWORD -value 0x00000019 -Force
New-ItemProperty . EnableColorSelection -type DWORD -value 0x00000000 -Force
New-ItemProperty . ExtendedEditKey -type DWORD -value 0x00000000 -Force
New-ItemProperty . ExtendedEditKeyCustom -type DWORD -value 0x00000000 -Force
New-ItemProperty . FaceName -type STRING -value "Consolas" -Force
New-ItemProperty . FontFamily -type DWORD -value 0x00000036 -Force
New-ItemProperty . FontSize -type DWORD -value 0x000e0000 -Force
New-ItemProperty . FontWeight -type DWORD -value 0x00000190 -Force
New-ItemProperty . FullScreen -type DWORD -value 0x00000000 -Force
New-ItemProperty . HistoryBufferSize -type DWORD -value 0x00000032 -Force
New-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000 -Force
New-ItemProperty . InsertMode -type DWORD -value 0x00000001 -Force
New-ItemProperty . LoadConIme -type DWORD -value 0x00000001 -Force
New-ItemProperty . NumberOfHistoryBuffers -type DWORD -value 0x00000004 -Force
New-ItemProperty . PopupColors -type DWORD -value 0x000000f5 -Force
New-ItemProperty . QuickEdit -type DWORD -value 0x00000001 -Force
New-ItemProperty . ScreenBufferSize -type DWORD -value 0x270f00c8 -Force
New-ItemProperty . ScreenColors -type DWORD -value 0x0000000f -Force
New-ItemProperty . TrimLeadingZeros -type DWORD -value 0x00000000 -Force
New-ItemProperty . WindowSize -type DWORD -value 0x003600c8 -Force
New-ItemProperty . WordDelimiters -type DWORD -value 0x00000000 -Force
New-ItemProperty . WindowPosition -type DWORD -value 0x003c00dc -Force
#######################################################################################

## Erstelle Regkeys für HKEY_CURRENT_USER\Console\%SystemRoot%_System32_WindowsPowerShell_v1.0_powershell.exe
$RegPath2="HKCU:\Console\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe"
$CheckRegKey2 = Test-Path -Path $RegPath2

if ($CheckRegKey2 -eq $true) {
    Clear-Host
    Remove-Item -Path $RegPath2 -Recurse -Force
    Write-Host "`nRegistrieschlüssel ist vorhanden und wird gelöscht!`n" -ForegroundColor Yellow
    New-Item -Path "HKCU:\Console" -Name "%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe" -Force
    Write-Host "`nRegistrieschlüssel ist nicht vorhanden und wird angelegt.`n" -ForegroundColor Green
} else {
    Clear-Host
    New-Item -Path "HKCU:\Console" -Name "%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe" -Force
    Write-Host "`nRegistrieschlüssel ist nicht vorhanden und wird angelegt.`n" -ForegroundColor Green
}

Set-Location -Path $RegPath2

## Konsolenfarben setzen
New-ItemProperty . ColorTable00 -type DWORD -value 0x00222827 -Force
New-ItemProperty . ColorTable03 -type DWORD -value 0x00141817 -Force
New-ItemProperty . ColorTable07 -type DWORD -value 0x00f2f8f8 -Force
New-ItemProperty . ColorTable09 -type DWORD -value 0x00efd966 -Force
New-ItemProperty . ColorTable10 -type DWORD -value 0x002ee2a6 -Force
New-ItemProperty . ColorTable12 -type DWORD -value 0x007226f9 -Force
New-ItemProperty . ColorTable14 -type DWORD -value 0x0074dbe6 -Force

## Schriftart und zusätzlich Optionen setzen
New-ItemProperty . CurrentPage -type DWORD -value 0x00000003 -Force
New-ItemProperty . CursorSize -type DWORD -value 0x00000019 -Force
New-ItemProperty . EnableColorSelection -type DWORD -value 0x00000000 -Force
New-ItemProperty . ExtendedEditKey -type DWORD -value 0x00000000 -Force
New-ItemProperty . ExtendedEditKeyCustom -type DWORD -value 0x00000000 -Force
New-ItemProperty . FaceName -type STRING -value "Consolas" -Force
New-ItemProperty . FontFamily -type DWORD -value 0x00000036 -Force
New-ItemProperty . FontSize -type DWORD -value 0x000e0000 -Force
New-ItemProperty . FontWeight -type DWORD -value 0x00000190 -Force
New-ItemProperty . FullScreen -type DWORD -value 0x00000000 -Force
New-ItemProperty . HistoryBufferSize -type DWORD -value 0x00000032 -Force
New-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000 -Force
New-ItemProperty . InsertMode -type DWORD -value 0x00000001 -Force
New-ItemProperty . LoadConIme -type DWORD -value 0x00000001 -Force
New-ItemProperty . NumberOfHistoryBuffers -type DWORD -value 0x00000004 -Force
New-ItemProperty . PopupColors -type DWORD -value 0x000000f5 -Force
New-ItemProperty . QuickEdit -type DWORD -value 0x00000001 -Force
New-ItemProperty . ScreenBufferSize -type DWORD -value 0x270f00c8 -Force
New-ItemProperty . ScreenColors -type DWORD -value 0x0000000f -Force
New-ItemProperty . TrimLeadingZeros -type DWORD -value 0x00000000 -Force
New-ItemProperty . WindowSize -type DWORD -value 0x003600c8 -Force
New-ItemProperty . WordDelimiters -type DWORD -value 0x00000000 -Force
New-ItemProperty . WindowPosition -type DWORD -value 0x003c00dc -Force
#######################################################################################

## Kopiere Regkeys für HKEY_CURRENT_USER\Console\Windows PowerShell
$RegPath3="HKCU:\Console\Windows PowerShell"
$CheckRegKey3 = Test-Path -Path $RegPath3

if ($CheckRegKey3 -eq $true) {
    Clear-Host
    Remove-Item -Path $RegPath3 -Recurse -Force
    Write-Host "`nRegistrieschlüssel ist vorhanden und wird gelöscht!`n" -ForegroundColor Yellow
    New-Item -Path "HKCU:\Console" -Name "Windows PowerShell" -Force
    Write-Host "`nRegistrieschlüssel ist nicht vorhanden und wird angelegt.`n" -ForegroundColor Green
} else {
    Clear-Host
    New-Item -Path "HKCU:\Console" -Name "Windows PowerShell" -Force
    Write-Host "`nRegistrieschlüssel ist nicht vorhanden und wird angelegt.`n" -ForegroundColor Green
}

Set-Location -Path $RegPath3

## Konsolenfarben setzen
New-ItemProperty . ColorTable00 -type DWORD -value 0x00222827 -Force
New-ItemProperty . ColorTable03 -type DWORD -value 0x00141817 -Force
New-ItemProperty . ColorTable07 -type DWORD -value 0x00f2f8f8 -Force
New-ItemProperty . ColorTable09 -type DWORD -value 0x00efd966 -Force
New-ItemProperty . ColorTable10 -type DWORD -value 0x002ee2a6 -Force
New-ItemProperty . ColorTable12 -type DWORD -value 0x007226f9 -Force
New-ItemProperty . ColorTable14 -type DWORD -value 0x0074dbe6 -Force

## Schriftart und zusätzlich Optionen setzen
New-ItemProperty . CurrentPage -type DWORD -value 0x00000003 -Force
New-ItemProperty . CursorSize -type DWORD -value 0x00000019 -Force
New-ItemProperty . EnableColorSelection -type DWORD -value 0x00000000 -Force
New-ItemProperty . ExtendedEditKey -type DWORD -value 0x00000000 -Force
New-ItemProperty . ExtendedEditKeyCustom -type DWORD -value 0x00000000 -Force
New-ItemProperty . FaceName -type STRING -value "Consolas" -Force
New-ItemProperty . FontFamily -type DWORD -value 0x00000036 -Force
New-ItemProperty . FontSize -type DWORD -value 0x000e0000 -Force
New-ItemProperty . FontWeight -type DWORD -value 0x00000190 -Force
New-ItemProperty . FullScreen -type DWORD -value 0x00000000 -Force
New-ItemProperty . HistoryBufferSize -type DWORD -value 0x00000032 -Force
New-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000 -Force
New-ItemProperty . InsertMode -type DWORD -value 0x00000001 -Force
New-ItemProperty . LoadConIme -type DWORD -value 0x00000001 -Force
New-ItemProperty . NumberOfHistoryBuffers -type DWORD -value 0x00000004 -Force
New-ItemProperty . PopupColors -type DWORD -value 0x000000f5 -Force
New-ItemProperty . QuickEdit -type DWORD -value 0x00000001 -Force
New-ItemProperty . ScreenBufferSize -type DWORD -value 0x270f00c8 -Force
New-ItemProperty . ScreenColors -type DWORD -value 0x0000000f -Force
New-ItemProperty . TrimLeadingZeros -type DWORD -value 0x00000000 -Force
New-ItemProperty . WindowSize -type DWORD -value 0x003600c8 -Force
New-ItemProperty . WordDelimiters -type DWORD -value 0x00000000 -Force
New-ItemProperty . WindowPosition -type DWORD -value 0x003c00dc -Force
#######################################################################################

## Powershell Verknüpfung erstellen
$ComObj = New-Object -ComObject Wscript.Shell
$Shortcut = $ComObj.CreateShortcut("$env:USERPROFILE\Desktop\Powershell.lnk")
$ShortCut.TargetPath = "$PSHOME\powershell.exe"
$ShortCut.Hotkey = "CTRL+ALT+P"
$ShortCut.Save()
####################################################################################### 

Wie immer freue ich mich über Kommentare und Anregungen.

Viele Grüße
Helmut

VirtualBox_android

 

 

 

 

 

Hallo zusammen,
 
lang, lang ist’s her als ich meinen letzten Blog Eintrag veröffentlicht habe. Da ich derzeit nicht mehr als IT-System und Netzwerkadministration arbeite, gibt es sehr wenig zu berichten das euch interessieren könnte.
 
Trotzdem habe ich hier wieder einmal ein Interessantes Thema, das vielleicht der ein oder andere benötigen könnte.
 
Für meine Firma musste ich einen Android Emulator testen um in internen Netzwerk eine App von uns ansteuern zu können, die Emulatoren Andy, BlueStack haben leider keinen Erfolg gebracht, da diese immer über das Internet kommunizieren, wenn man nun aber einen PC hat der kein Internet Zugang besitzt, hat man ein Problem. Daher habe ich mich nach einer Alternative umgesehen.
 
Und mit den android x86 Projekt eine passende Alternative gefunden. Hier kann man sich ein Android in einer Virtuellen Maschine installieren, bestimmt nicht neu, aber für mich war das Neuland.
 
Hier mein Howto zu dem Thema — Android 4.4 in Oracle VM VirtualBox installieren
 
Viel Spaß damit
Gruß Helmut

freebsd_freenas_logo

 

 

 

 

Hallo zusammen,

in dem heutigen Blogeintrag möchte ich euch zeigen, wie Ihr mit der freien Software FreeNAS ein ISCSI Target einrichtet, um diese wiederum für ein Microsoft Hyper-V Failover Cluster zu verwenden. Da ich mich gerade wieder ein bisschen mit Hyper-V beschäftige, habe ich nach einer alternative Software gesucht die diesen Zweck erfüllt.

Das Tutorial Microsoft Hyper-V 2012 R2 Failover Cluster sollte bis Ende dieser Woche folgen.

Gruß Helmut

Howto findet Ihr wieder hier –> ISCSI Targets mit FreeNAS 9.3 einrichten