Add extra file to database, path is wrong

133 views Asked by At

I am creating a website using Python Django and the main purpose of the website is to modify XML files. I have uploaded the files to the hosting server and when I try to perform the conversion, I need to add another file to the database record that was created. On my local server, the process works smoothly without any issues, but when I try to do it on the hosting server, I get an error message:

"SuspiciousFileOperation at /test/ Detected path traversal attempt in '/home/t/tkor470gma/converter/new_CUST.xml".

My models.py looks like this:

class Document(models.Model):
    document = models.FileField(verbose_name='Document (old structure with settings)',upload_to='documents/')
    document1 = models.FileField(verbose_name='Document (new structures without settings)',upload_to='documents/')
    author = models.ForeignKey(User,on_delete=models.CASCADE)
    resdocument = models.FileField(upload_to='documents/',blank=True)
    transaction_date = models.DateTimeField(auto_now_add=True)

forms.py

class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ['document','document1']

views.py - this form uploads files to the database

def model_form_upload(request):
    form = DocumentForm()
    pathresdoc = ''
    if request.method == 'POST':
        user = request.user
        form = DocumentForm(request.POST, request.FILES)
        obj = Document.objects.filter(author_id=user).order_by('-id')
        if obj.count() >= 1:
            return HttpResponse('it is impossible to convert first <button>Pay</button>')
    else:
        if form.is_valid():
            instance = form.save(commit=False)
            instance.author = user
            form.save()
            create_file(request.user.id)
            respeople = instance.id
            add_file_to_database('/home/t/tkor470gma/converter/new_CUST.xml',respeople)
            pathresdoc = Document.objects.get(id=respeople).resdocument.path
else:
    form = DocumentForm()
return render(request, 'model_form.html', {'form': form,'pathresdoc': str(pathresdoc)})

This one adds the resulting file to the database:

def add_file_to_database(file_path,idtransaction):
    my_file = File(open(file_path, 'rb'))
    model_instance = Document.objects.get(id=idtransaction)
    model_instance.resdocument = my_file
    model_instance.save_base()

This one creates the file itself:

def create_file(request):
    obj = Document.objects.filter(author_id=request).order_by('-id')[0]
     converterfile(str(obj.document.path),str(obj.document1.path),r"/home/t/tkor470gma/converter/new_CUST.xml")

This calls the program which converts the files:

def converterfile(file1,file2,file3):

     call(['python',"/home/t/tkor470gma/converter/backend/New_file.py", file1, file2, file3], shell=True)

How can I resolve this issue? I have tried using both the relative and absolute path, but the same error keeps appearing.

SuspiciousFileOperation at /test/
Detected path traversal attempt in 
'/home/t/tkor470gma/converter/new_CUST.xml'
Request Method: POST
Request URL:     
https://sapxmlversionup.ru/test/
Django Version: 4.0
Exception Type: SuspiciousFileOperation
Exception Value:    
Detected path traversal attempt in 
'/home/t/tkor470gma/converter/new_CUST.xml'
Exception Location:/home/t/tkor470gma/.djangovenv/lib/python3.8/sit 
e-packages/django/core/files/utils.py, line 
18, in validate_file_name
Python Executable:  /usr/bin/python3
Python Version: 3.8.5
Python Path:    
['/usr/lib/python38.zip',
 '/usr/lib/python3.8',
 '/usr/lib/python3.8/lib-dynload',
 '/home/t/tkor470gma/converter/public_html',
 '/home/t/tkor470gma/converter',

Error photo

This is my hosting settings.py

from pathlib import Path
import os
from django.utils.translation import gettext_lazy as _

# Build paths inside the project like this: 
BASE_DIR / 'subdir'.
BASE_DIR = 
Path(__file__).resolve().parent.parent

MEDIA_ROOT = os.path.join(BASE_DIR, 'documents')
DEBUG = True

ALLOWED_HOSTS = ['sapxmlversionup.ru']

AUTH_USER_MODEL = 'users.User'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
# Application definition
SITE_ID = 1

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'MainConv',
    'users',

]


MIDDLEWARE = [
   'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'Converter.urls'

TEMPLATES = [
    {
        'BACKEND':'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},
]

 WSGI_APPLICATION = 'Converter.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 
'django.db.backends.postgresql_psycopg2',
        'NAME': 'tkor470gma',
        'USER': 'tkor470gma',
        'PASSWORD': '***',
        'HOST': 'pg2.sweb.ru',
        'PORT': '5432',
}
}

AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend']
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'ru'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

USE_L10N = True


DATE_INPUT_FORMATS = ( "%d/%m/%Y", )
DATETIME_INPUT_FORMATS = ( "%d/%m/%Y %H:%M", )


LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'
MEDIA_URL = '/media/'

And this local settings:

from pathlib import Path
import os
from django.utils.translation import gettext_lazy as _

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


DEBUG = True

ALLOWED_HOSTS = []

AUTH_USER_MODEL = 'users.User'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
SITE_ID = 1

INSTALLED_APPS = [
    'modeltranslation',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'MainConv',
    'users',

]


MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'Converter.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'Converter.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'tkor470gma',
        'USER': 'postgres',
        'PASSWORD': '***',
        'HOST': 'localhost',
        'PORT': '',
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'ru'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

USE_L10N = True

MODELTRANSLATION_DEFAULT_LANGUAGE = 'en'

DATE_INPUT_FORMATS = ( "%d/%m/%Y", )
DATETIME_INPUT_FORMATS = ( "%d/%m/%Y %H:%M", )


LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'
MEDIA_URL = '/media/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
0

There are 0 answers