Search code examples
djangodjango-formsheader-injection

why does Django returns BadHeaderError when adding a new line in my 'Contact' page's 'message' field


Everything works except when I add a new line via 'enter' in the "Message" field. It goes through if I don't add new lines in the message textfield.

What am i missing here? Tried to solve this problem for 2 days, nothing similar on google.

I feel like there could be the problem of my views.py config:

def success(request):
    return render(request, 'home/success.html')

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            # send email code goes here
            sender_name = form.cleaned_data['name']
            sender_email = form.cleaned_data['email']
            sender_phone = form.cleaned_data['phone']
            sender_message = form.cleaned_data['message']
            subject = "Enquiry: {0}".format(sender_message[:50])
            message = "New message from {0}\n phone number: {1}\n email: {2}\n\n{3}".format(sender_name, sender_phone, sender_email, sender_message)
            recipients = ['john.smith@gmail.com']
            sender = "{0}<{1}>".format(sender_name, sender_email)
            try:
                send_mail(subject, message, sender, recipients, fail_silently=False)
            except BadHeaderError:
                return HttpResponse('Invalid header found')
            return HttpResponseRedirect('success')
    else:
        form = ContactForm()

    return render(request, 'home/contact.html', {'form': form})

Any ideas?


Solution

  • As described in the documentation, a BadHeaderError is raised to "protect against header injection by forbidding newlines in header values".

    Since you're copying part of sender_message directly into the subject header, you may be including newlines as well. The simple solution is to strip them out first.

    sender_message = form.cleaned_data['message']
    clean_message = sender_message.replace('\n', '').replace('\r', '')
    subject = "Enquiry: {0}".format(clean_message[:50])