Properly use JWT secret key

This commit is contained in:
Matthias 2020-12-27 15:24:49 +01:00
parent 790f833653
commit 1717121f10
4 changed files with 42 additions and 28 deletions

View File

@ -8,34 +8,32 @@ from fastapi.security.http import HTTPBasic, HTTPBasicCredentials
from freqtrade.rpc.api_server2.api_models import AccessAndRefreshToken, AccessToken from freqtrade.rpc.api_server2.api_models import AccessAndRefreshToken, AccessToken
from .deps import get_config from .deps import get_api_config
SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
ALGORITHM = "HS256" ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
router_login = APIRouter() router_login = APIRouter()
def verify_auth(config, username: str, password: str): def verify_auth(api_config, username: str, password: str):
"""Verify username/password""" """Verify username/password"""
return (secrets.compare_digest(username, config['api_server'].get('username')) and return (secrets.compare_digest(username, api_config.get('username')) and
secrets.compare_digest(password, config['api_server'].get('password'))) secrets.compare_digest(password, api_config.get('password')))
httpbasic = HTTPBasic(auto_error=False) httpbasic = HTTPBasic(auto_error=False)
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token", auto_error=False) oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token", auto_error=False)
def get_user_from_token(token, token_type: str = "access"): def get_user_from_token(token, secret_key: str, token_type: str = "access"):
credentials_exception = HTTPException( credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials", detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"}, headers={"WWW-Authenticate": "Bearer"},
) )
try: try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) payload = jwt.decode(token, secret_key, algorithms=[ALGORITHM])
username: str = payload.get("sub") username: str = payload.get("sub")
if username is None: if username is None:
raise credentials_exception raise credentials_exception
@ -47,7 +45,7 @@ def get_user_from_token(token, token_type: str = "access"):
return username return username
def create_token(data: dict, token_type: str = "access") -> str: def create_token(data: dict, secret_key: str, token_type: str = "access") -> str:
to_encode = data.copy() to_encode = data.copy()
if token_type == "access": if token_type == "access":
expire = datetime.utcnow() + timedelta(minutes=15) expire = datetime.utcnow() + timedelta(minutes=15)
@ -60,15 +58,16 @@ def create_token(data: dict, token_type: str = "access") -> str:
"iat": datetime.utcnow(), "iat": datetime.utcnow(),
"type": token_type, "type": token_type,
}) })
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) encoded_jwt = jwt.encode(to_encode, secret_key, algorithm=ALGORITHM)
return encoded_jwt return encoded_jwt
def http_basic_or_jwt_token(form_data: HTTPBasicCredentials = Depends(httpbasic), def http_basic_or_jwt_token(form_data: HTTPBasicCredentials = Depends(httpbasic),
token: str = Depends(oauth2_scheme), config=Depends(get_config)): token: str = Depends(oauth2_scheme),
api_config=Depends(get_api_config)):
if token: if token:
return get_user_from_token(token) return get_user_from_token(token, api_config.get('jwt_secret_key', 'super-secret'))
elif form_data and verify_auth(config, form_data.username, form_data.password): elif form_data and verify_auth(api_config, form_data.username, form_data.password):
return form_data.username return form_data.username
raise HTTPException( raise HTTPException(
@ -78,12 +77,14 @@ def http_basic_or_jwt_token(form_data: HTTPBasicCredentials = Depends(httpbasic)
@router_login.post('/token/login', response_model=AccessAndRefreshToken) @router_login.post('/token/login', response_model=AccessAndRefreshToken)
def token_login(form_data: HTTPBasicCredentials = Depends(HTTPBasic()), config=Depends(get_config)): def token_login(form_data: HTTPBasicCredentials = Depends(HTTPBasic()),
api_config=Depends(get_api_config)):
if verify_auth(config, form_data.username, form_data.password): if verify_auth(api_config, form_data.username, form_data.password):
token_data = {'sub': form_data.username} token_data = {'sub': form_data.username}
access_token = create_token(token_data) access_token = create_token(token_data, api_config.get('jwt_secret_key', 'super-secret'))
refresh_token = create_token(token_data, token_type="refresh") refresh_token = create_token(token_data, api_config.get('jwt_secret_key', 'super-secret'),
token_type="refresh")
return { return {
"access_token": access_token, "access_token": access_token,
"refresh_token": refresh_token, "refresh_token": refresh_token,
@ -97,9 +98,11 @@ def token_login(form_data: HTTPBasicCredentials = Depends(HTTPBasic()), config=D
@router_login.post('/token/refresh', response_model=AccessToken) @router_login.post('/token/refresh', response_model=AccessToken)
def token_refresh(token: str = Depends(oauth2_scheme)): def token_refresh(token: str = Depends(oauth2_scheme), api_config=Depends(get_api_config)):
# Refresh token # Refresh token
u = get_user_from_token(token, 'refresh') u = get_user_from_token(token, api_config.get(
'jwt_secret_key', 'super-secret'), 'refresh')
token_data = {'sub': u} token_data = {'sub': u}
access_token = create_token(token_data, token_type="access") access_token = create_token(token_data, api_config.get('jwt_secret_key', 'super-secret'),
token_type="access")
return {'access_token': access_token} return {'access_token': access_token}

View File

@ -7,3 +7,7 @@ def get_rpc():
def get_config(): def get_config():
return ApiServer._config return ApiServer._config
def get_api_config():
return ApiServer._config['api_server']

View File

@ -86,6 +86,11 @@ class ApiServer(RPCHandler):
logger.warning("SECURITY WARNING - No password for local REST Server defined. " logger.warning("SECURITY WARNING - No password for local REST Server defined. "
"Please make sure that this is intentional!") "Please make sure that this is intentional!")
if (self._config['api_server'].get('jwt_secret_key', 'super-secret')
in ('super-secret, somethingrandom')):
logger.warning("SECURITY WARNING - `jwt_secret_key` seems to be default."
"Others may be able to log into your bot.")
logger.info('Starting Local Rest Server.') logger.info('Starting Local Rest Server.')
uvconfig = uvicorn.Config(self.app, uvconfig = uvicorn.Config(self.app,
port=rest_port, port=rest_port,

View File

@ -23,7 +23,7 @@ from freqtrade.persistence import PairLocks, Trade
from freqtrade.rpc import RPC from freqtrade.rpc import RPC
from freqtrade.rpc.api_server2 import ApiServer from freqtrade.rpc.api_server2 import ApiServer
from freqtrade.state import RunMode, State from freqtrade.state import RunMode, State
from tests.conftest import create_mock_trades, get_patched_freqtradebot, log_has, patch_get_signal from tests.conftest import create_mock_trades, get_patched_freqtradebot, log_has, log_has_re, patch_get_signal
BASE_URI = "/api/v1" BASE_URI = "/api/v1"
@ -91,22 +91,22 @@ def test_api_not_found(botclient):
def test_api_auth(): def test_api_auth():
with pytest.raises(ValueError): with pytest.raises(ValueError):
create_token({'sub': 'Freqtrade'}, token_type="NotATokenType") create_token({'sub': 'Freqtrade'}, 'secret1234', token_type="NotATokenType")
token = create_token({'sub': 'Freqtrade'}, ) token = create_token({'sub': 'Freqtrade'}, 'secret1234')
assert isinstance(token, bytes) assert isinstance(token, bytes)
u = get_user_from_token(token) u = get_user_from_token(token, 'secret1234')
assert u == 'Freqtrade' assert u == 'Freqtrade'
with pytest.raises(HTTPException): with pytest.raises(HTTPException):
get_user_from_token(token, token_type='refresh') get_user_from_token(token, 'secret1234', token_type='refresh')
# Create invalid token # Create invalid token
token = create_token({'sub`': 'Freqtrade'}, ) token = create_token({'sub`': 'Freqtrade'}, 'secret1234')
with pytest.raises(HTTPException): with pytest.raises(HTTPException):
get_user_from_token(token) get_user_from_token(token, 'secret1234')
with pytest.raises(HTTPException): with pytest.raises(HTTPException):
get_user_from_token(b'not_a_token') get_user_from_token(b'not_a_token', 'secret1234')
def test_api_unauthorized(botclient): def test_api_unauthorized(botclient):
@ -279,6 +279,8 @@ def test_api_run(default_conf, mocker, caplog):
"e.g 127.0.0.1 in config.json", caplog) "e.g 127.0.0.1 in config.json", caplog)
assert log_has("SECURITY WARNING - No password for local REST Server defined. " assert log_has("SECURITY WARNING - No password for local REST Server defined. "
"Please make sure that this is intentional!", caplog) "Please make sure that this is intentional!", caplog)
assert log_has_re("SECURITY WARNING - `jwt_secret_key` seems to be default.*", caplog)
# Test crashing flask # Test crashing flask
caplog.clear() caplog.clear()