user3786992
user3786992

Reputation: 167

Would posting my code to github affect the security of my application?

background

I am writing a simple blog application in Django (data passed through templating language). The owner of the blog will have access to the admin page where they will update the db. Now I understand that in production I will have to hide the security key and turn debug off.

question

What I am wandering is will pushing the code to github jeopardize the security of the application?

Upvotes: 4

Views: 2814

Answers (5)

Vinit Raj
Vinit Raj

Reputation: 1910

Yes you can but make sure that you don't keep your secret keys and password in your main settings.py file.Since you are using django,python comes with a package called pytho-decouple which help you to keep your secret files in a .env file.

You can install it by using this command in your django project:

 pip install python-decouple

Now let us consider you have following settings.py file:

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = '3izb^ryglj(bvrjb2_y1fZvcnbky#358_l6-nn#i8fkug4mmz!'
DEBUG = True
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'HELLO_DJANGO',
        'USER': 'U_HELLO',
        'PASSWORD': 'hA8(scA@!fg3*sc&xaGh&6%-l<._&xCf',
        'HOST': '127.0.0.1',
        'PORT': '',
    }
}

So what you need to do is to create a .env file in the root directory of your django project like this:-

SECRET_KEY=3izb^ryglj(bvrjb2_y1fZvcnbky#358_l6-nn#i8fkug4mmz!
DEBUG=True
DB_NAME=HELLO_DJANGO
DB_USER=U_HELLO
DB_PASSWORD=hA8(scA@!fg3*sc&xaGh&6%-l<._&xCf
DB_HOST=127.0.0.1

Since you want to upload your project on github just make sure you include .env file in your .gitignore file. Now the last step:-

import os
from decouple import config

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', cast=bool)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': config('DB_NAME'),
        'USER': config('DB_USER'),
        'PASSWORD': config('DB_PASSWORD'),
        'HOST': config('DB_HOST'),
        'PORT': '',
    }
}

In this way you can use your secret keys without letting anyone know.

Upvotes: 7

J&#233;r&#244;me
J&#233;r&#244;me

Reputation: 14724

This question is twofold. The code and the secret keys are two different issues.

Does publishing the code affect the security of the application?

While posting the code publicly may reach attention of readers who could point security issues, it also exposes those issues to potential malicious individuals. Hiding the code doesn't make it any safer, but at least the security issues wouldn't be that obvious to find. This part of the question has already been debated and could be deemed opinion-based or duplicate.

See Gabor's answser or this SE post linked to in another answer.

How can I publish the code without exposing sensitive information?

Don't put secret stuff (passwords, secret keys,...) in the code. Those should be in a configuration file that is not in the repository. Even if the repository is private, it would be a bit dirty to keep those here.

Think of your code as an application. The website using your code is an instance of this application, with specific settings. You can have several websites sharing the same code with different settings (which makes maintenance easier, BTW).

Flask configuration pattern example

Here's what I do with Flask. I suppose a similar pattern can be used with Django, although it may provide helpers to do it differently (like django-decouple in Vinit's answer).

Put a default_settings.py file in the repository and override a few important settings when instantiating the application. This is a pattern described here : http://flask.pocoo.org/docs/0.12/config/#configuring-from-files.

default_settings.py

class Config():
    DEBUG = False
    TESTING = False
    [...]

class ProductionConfig(Config):
    [...]


class DevelopmentConfig(Config):
    SECRET_KEY = 'dummy_key'
    DEBUG = True
    [...]

class TestingConfig(Config):
    SECRET_KEY = 'dummy_key'
    TESTING = True
    [...]

Notice that I don't set a default secret key in production mode, so that if I forget to override it in the application config file, the application won't run with a dummy key.

application.wsgi

#!/usr/bin/env python3
"""Sample wsgi file

Customize path to virtual environment and you're done
"""

import os
import sys
import runpy

# Working with Virtual Environment
# see http://flask.pocoo.org/docs/0.10/deploying/mod_wsgi/
# and also https://gist.github.com/LeZuse/4032238
# and https://stackoverflow.com/questions/436198/
runpy.run_path('/path/to/venv/bin/activate_this.py')

# Add application to Python path
# Check before adding so as not to add it multiple times
# when reloading the file:
# https://code.google.com/p/modwsgi/wiki/ReloadingSourceCode
PATH = os.path.dirname(__file__)
if PATH not in sys.path:
    sys.path.append(PATH)

# Set environment variable to indicate production mode
os.environ['FLASK_CONFIG'] = 'ProductionConfig'

# Provide path to custom settings file
os.environ['SETTINGS_FILE'] = os.path.join(
    os.path.dirname(os.path.realpath(__file__)),
    'settings.cfg'
)

[...]

settings.cfg

# Flask secret key
# To generate a secret key:
# ''.join([random.choice(string.printable) for i in range(100)])
SECRET_KEY = 

# Other secret keys
[...]

Then in the application

config_class = os.getenv('FLASK_CONFIG')
app.config.from_object(config_class)
app.config.from_envvar('SETTINGS_FILE', silent=True)

 (Multi)Instantiation simplified

Using setuptools, I can easily deploy the application in a virtualenv. Creating an instance of the application just takes the following steps:

  • create virtualenv
  • pip install my_app
  • copy and adapt .wsgi example file
  • copy and adapt local settings.cfg example file
  • configure and activate website in web server (/etc/apache2/sites-available/my_app.conf)

The website directory on the server only contains the virtual env and the two config files that are specific to this instance.

It is fine to store example files in the repo in a docs/ directory (.wsgi, settings.cfg, apache .conf file,...), with placeholders for parameters.

Upvotes: 5

Gabor Lengyel
Gabor Lengyel

Reputation: 15599

I think the important point is that it does not affect the security of your application, ie. the technical vulnerabilities will be the same whether it's posted on GitHub or not (provided that you don't share secrets, but note that secrets should only be cryptographical, things like algorithms or how something works or integrates should not be secrets, see security by obscurity).

However, sharing your code on GitHub does affect your risk, and it's hard to say which way in total, it gets quite opinionated. You will definitely have a different risk profile. Having open source code (as opposed to closed source) modifies the likelihood of certain things in your threat model (some getting less likely, but some getting more likely), which you should acknowledge and manage.

Upvotes: 2

Corey Gumbs
Corey Gumbs

Reputation: 382

I make my repos private if I don't want anyone to see my code and give permission to whomever I want to have access. The nominal fee is worth it, well at least to me.

But overall, my source code for my projects have been open and like Alex stated, its a good opportunity to get input from others.

Upvotes: 1

Alex
Alex

Reputation: 1418

Avoid posting a code to github doesn't make a website safer. I'd say quite the opposite. Why ? Because if a good hacker really wants to find a breach, he will. But if you post your code to github, you will most likely encounter white hats who will tell you if they find a security issue (But still, you shouldn't let obvious security issues).

In my opinion, not posting a code to github just nearly guarantees you that your code won't be stolen. But still, if you put the right license, you could just sue the one that stole your code, I guess.

PS : I'm still not the most experienced developper, so you should maybe take other opinions into account.

Edit : some reading for you https://softwareengineering.stackexchange.com/questions/177030/security-issue-about-making-my-code-public-in-github

Upvotes: 2

Related Questions