diff --git a/mqtt/sec/docker-compose.yml b/mqtt/sec/docker-compose.yml index c98db68..daa81df 100644 --- a/mqtt/sec/docker-compose.yml +++ b/mqtt/sec/docker-compose.yml @@ -1,18 +1,81 @@ services: - eclipse-mosquitto: - stdin_open: true - tty: true - ports: - - "${MQTT_TLS_PORT:-8883}:8883" - - "${MQTT_WSS_PORT:-9443}:9443" - restart: unless-stopped - container_name: ${NAME} - volumes: - - ${VOLUME_ROOT}/config:/mosquitto/config - - ${VOLUME_ROOT}/data:/mosquitto/data - - ${VOLUME_ROOT}/log:/mosquitto/log - - /etc/ssl/certs:/mosquitto/certs:ro - image: ${IMAGE} - dns: - - ${DNS_SERVER} - \ No newline at end of file + mosquitto: + image: eclipse-mosquitto:2 + container_name: ${CONTAINER_NAME:-mosquitto} + restart: unless-stopped + + environment: + TZ: ${TZ:-Europe/Berlin} + MQTT_HOSTNAME: ${MQTT_HOSTNAME:-mqtt.local} + MQTT_USER: ${MQTT_USER:-mqttuser} + MQTT_TLS_PORT: ${MQTT_TLS_PORT:-8883} + + volumes: + - ${CONFIG_PATH:-./config}:/mosquitto/config + - ${DATA_PATH:-./data}:/mosquitto/data + - ${LOG_PATH:-./log}:/mosquitto/log + - /etc/ssl/certs:/mosquitto/certs:ro + + ports: + - "${MQTT_TLS_PORT:-8883}:8883" + + dns: + - ${DNS_SERVER} + + command: > + sh -c ' + CERT_DIR=/mosquitto/certs; + CONF=/mosquitto/config/mosquitto.conf; + PASSWD=/mosquitto/config/passwd; + + echo "=== Checking certificates ==="; + + if [ ! -f "$CERT_DIR/server.crt" ]; then + echo "Generating self-signed certificates..."; + openssl genrsa -out $CERT_DIR/ca.key 4096; + openssl req -x509 -new -nodes -key $CERT_DIR/ca.key -sha256 -days 3650 \ + -out $CERT_DIR/ca.crt -subj "/CN=LocalMQTT-CA"; + + openssl genrsa -out $CERT_DIR/server.key 4096; + openssl req -new -key $CERT_DIR/server.key -out $CERT_DIR/server.csr \ + -subj "/CN=$MQTT_HOSTNAME"; + + openssl x509 -req -in $CERT_DIR/server.csr -CA $CERT_DIR/ca.crt \ + -CAkey $CERT_DIR/ca.key -CAcreateserial \ + -out $CERT_DIR/server.crt -days 3650 -sha256; + else + echo "Certificates already exist."; + fi; + + echo "=== Checking mosquitto.conf ==="; + + if [ ! -f "$CONF" ]; then + echo "Generating default mosquitto.conf..."; + cat < $CONF +listener ${MQTT_TLS_PORT:-8883} +protocol mqtt +cafile /mosquitto/certs/ca.crt +certfile /mosquitto/certs/server.crt +keyfile /mosquitto/certs/server.key +allow_anonymous false +password_file /mosquitto/config/passwd +EOF + else + echo "Existing mosquitto.conf found."; + fi; + + echo "=== Checking user ==="; + + if [ ! -f "$PASSWD" ]; then + echo "Generating random password for user: $MQTT_USER"; + RANDOM_PASS=$(openssl rand -base64 32); + echo "Generated password (save this!):"; + echo "$RANDOM_PASS"; + mosquitto_passwd -c -b "$PASSWD" "$MQTT_USER" "$RANDOM_PASS"; + else + echo "Password file exists — skipping user creation."; + fi; + + echo "=== Starting Mosquitto ==="; + mosquitto -c $CONF + '