mirror of
https://github.com/GNS3/gns3-server.git
synced 2026-11-06 15:21:13 +02:00
Secure controller to compute communication using HTTP basic authentication
This commit is contained in:
1 parent
55e50dae4b
commit
38388f7ae5
24 files changed
+483
-416
No files matched your search
@@ -15,13 +15,15 @@
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi import FastAPI, Request, Depends
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
from gns3server.controller.gns3vm.gns3_vm_error import GNS3VMError
|
||||
from gns3server.compute.error import ImageMissingError, NodeError
|
||||
from gns3server.compute.ubridge.ubridge_error import UbridgeError
|
||||
|
||||
from .dependencies.authentication import compute_authentication
|
||||
|
||||
from gns3server.compute.compute_error import (
|
||||
ComputeError,
|
||||
ComputeNotFoundError,
|
||||
@@ -49,9 +51,9 @@ from . import virtualbox_nodes
|
||||
from . import vmware_nodes
|
||||
from . import vpcs_nodes
|
||||
|
||||
|
||||
compute_api = FastAPI(
|
||||
title="GNS3 compute API",
|
||||
dependencies=[Depends(compute_authentication)],
|
||||
description="This page describes the private compute API for GNS3. PLEASE DO NOT USE DIRECTLY!",
|
||||
version="v3",
|
||||
)
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,37 @@
|
||||
#
|
||||
# Copyright (C) 2021 GNS3 Technologies Inc.
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import secrets
|
||||
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
||||
from gns3server.config import Config
|
||||
from typing import Optional
|
||||
|
||||
security = HTTPBasic()
|
||||
|
||||
|
||||
def compute_authentication(credentials: Optional[HTTPBasicCredentials] = Depends(security)) -> None:
|
||||
|
||||
server_settings = Config.instance().settings.Server
|
||||
username = secrets.compare_digest(credentials.username, server_settings.compute_username)
|
||||
password = secrets.compare_digest(credentials.password, server_settings.compute_password.get_secret_value())
|
||||
if not (username and password):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid compute username or password",
|
||||
headers={"WWW-Authenticate": "Basic"},
|
||||
)
|
||||
@@ -18,7 +18,11 @@
|
||||
API routes for compute notifications.
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
||||
import base64
|
||||
import binascii
|
||||
|
||||
from fastapi import APIRouter, WebSocket, WebSocketDisconnect, status, HTTPException
|
||||
from fastapi.security.utils import get_authorization_scheme_param
|
||||
from websockets.exceptions import ConnectionClosed, WebSocketException
|
||||
|
||||
from gns3server.compute.notification_manager import NotificationManager
|
||||
@@ -37,6 +41,32 @@ async def notification_ws(websocket: WebSocket) -> None:
|
||||
"""
|
||||
|
||||
await websocket.accept()
|
||||
|
||||
# handle basic HTTP authentication
|
||||
invalid_user_credentials_exc = HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid authentication credentials",
|
||||
headers={"WWW-Authenticate": "Basic"},
|
||||
)
|
||||
|
||||
try:
|
||||
authorization = websocket.headers.get("Authorization")
|
||||
scheme, param = get_authorization_scheme_param(authorization)
|
||||
if not authorization or scheme.lower() != "basic":
|
||||
raise invalid_user_credentials_exc
|
||||
try:
|
||||
data = base64.b64decode(param).decode("ascii")
|
||||
except (ValueError, UnicodeDecodeError, binascii.Error):
|
||||
raise invalid_user_credentials_exc
|
||||
username, separator, password = data.partition(":")
|
||||
if not separator:
|
||||
raise invalid_user_credentials_exc
|
||||
except invalid_user_credentials_exc as e:
|
||||
websocket_error = {"action": "log.error", "event": {"message": f"Could not authenticate while connecting to "
|
||||
f"compute WebSocket: {e.detail}"}}
|
||||
await websocket.send_json(websocket_error)
|
||||
return await websocket.close(code=1008)
|
||||
|
||||
log.info(f"New client {websocket.client.host}:{websocket.client.port} has connected to compute WebSocket")
|
||||
try:
|
||||
with NotificationManager.instance().queue() as queue:
|
||||
|
||||
@@ -97,8 +97,8 @@ class Controller:
|
||||
host=host,
|
||||
console_host=console_host,
|
||||
port=port,
|
||||
user=server_config.user,
|
||||
password=server_config.password,
|
||||
user=server_config.compute_username,
|
||||
password=server_config.compute_password,
|
||||
force=True,
|
||||
connect=True,
|
||||
ssl_context=self._ssl_context,
|
||||
@@ -154,8 +154,8 @@ class Controller:
|
||||
"""
|
||||
|
||||
if self._local_server:
|
||||
self._local_server.user = Config.instance().settings.Server.user
|
||||
self._local_server.password = Config.instance().settings.Server.password
|
||||
self._local_server.user = Config.instance().settings.Server.compute_username
|
||||
self._local_server.password = Config.instance().settings.Server.compute_password
|
||||
|
||||
async def stop(self):
|
||||
|
||||
|
||||
@@ -119,6 +119,7 @@ class Compute:
|
||||
"""
|
||||
Set authentication parameters
|
||||
"""
|
||||
|
||||
if user is None or len(user.strip()) == 0:
|
||||
self._user = None
|
||||
self._password = None
|
||||
@@ -468,6 +469,8 @@ class Compute:
|
||||
# FIXME: slow down number of compute events
|
||||
self._controller.notification.controller_emit("compute.updated", self.asdict())
|
||||
else:
|
||||
if action == "log.error":
|
||||
log.error(event.pop("message"))
|
||||
await self._controller.notification.dispatch(
|
||||
action, event, project_id=project_id, compute_id=self.id
|
||||
)
|
||||
|
||||
@@ -131,9 +131,8 @@ class ServerSettings(BaseModel):
|
||||
udp_start_port_range: int = Field(10000, gt=0, le=65535)
|
||||
udp_end_port_range: int = Field(30000, gt=0, le=65535)
|
||||
ubridge_path: str = "ubridge"
|
||||
user: str = None
|
||||
password: SecretStr = None
|
||||
enable_http_auth: bool = False
|
||||
compute_username: str = "admin"
|
||||
compute_password: SecretStr = SecretStr("")
|
||||
default_admin_username: str = "admin"
|
||||
default_admin_password: SecretStr = SecretStr("admin")
|
||||
allowed_interfaces: List[str] = Field(default_factory=list)
|
||||
@@ -164,14 +163,6 @@ class ServerSettings(BaseModel):
|
||||
raise ValueError("vnc_console_end_port_range must be > vnc_console_start_port_range")
|
||||
return v
|
||||
|
||||
@validator("enable_http_auth")
|
||||
def validate_enable_auth(cls, v, values):
|
||||
|
||||
if v is True:
|
||||
if "user" not in values or not values["user"]:
|
||||
raise ValueError("HTTP authentication is enabled but user is not configured")
|
||||
return v
|
||||
|
||||
@validator("enable_ssl")
|
||||
def validate_enable_ssl(cls, v, values):
|
||||
|
||||
|
||||
+12
-3
@@ -30,6 +30,8 @@ import asyncio
|
||||
import signal
|
||||
import functools
|
||||
import uvicorn
|
||||
import secrets
|
||||
import string
|
||||
|
||||
from gns3server.controller import Controller
|
||||
from gns3server.compute.port_manager import PortManager
|
||||
@@ -38,7 +40,7 @@ from gns3server.version import __version__
|
||||
from gns3server.config import Config
|
||||
from gns3server.crash_report import CrashReport
|
||||
from gns3server.api.server import app
|
||||
from pydantic import ValidationError
|
||||
from pydantic import ValidationError, SecretStr
|
||||
|
||||
import logging
|
||||
|
||||
@@ -269,8 +271,15 @@ class Server:
|
||||
if config.Server.local:
|
||||
log.warning("Local mode is enabled. Beware, clients will have full control on your filesystem")
|
||||
|
||||
if config.Server.enable_http_auth:
|
||||
log.info(f"HTTP authentication is enabled with username '{config.Server.user}'")
|
||||
if not config.Server.compute_password.get_secret_value():
|
||||
alphabet = string.ascii_letters + string.digits + string.punctuation
|
||||
generated_password = ''.join(secrets.choice(alphabet) for _ in range(16))
|
||||
config.Server.compute_password = SecretStr(generated_password)
|
||||
log.warning(f"Compute authentication is enabled with username '{config.Server.compute_username}' and "
|
||||
f"a randomly generated password. Please set a password in the config file if this compute "
|
||||
f"is to be used by an external controller")
|
||||
else:
|
||||
log.info(f"Compute authentication is enabled with username '{config.Server.compute_username}'")
|
||||
|
||||
# we only support Python 3 version >= 3.6
|
||||
if sys.version_info < (3, 6, 0):
|
||||
|
||||
@@ -35,6 +35,7 @@ DEFAULT_JWT_SECRET_KEY = "efd08eccec3bd0a1be2e086670e5efa90969c68d07e072d7354a76
|
||||
|
||||
|
||||
class AuthService:
|
||||
|
||||
def hash_password(self, password: str) -> str:
|
||||
|
||||
return pwd_context.hash(password)
|
||||
|
||||
Reference in new issue
Block a user