【MondoDB】パスワード暗号化

 

import hashlib
from passlib.hash import pbkdf2_sha256


print(hashlib.algorithms_available)
print(hashlib.algorithms_guaranteed)

password ='abcd1234'

# hash
_hash = pbkdf2_sha256.encrypt(password, rounds=200000, salt_size=16)
print(_hash)

 #save hash
# verify
if pbkdf2_sha256.verify(password, _hash):
  resp['status']='OK'
else:
  resp['status']='NG'

 

【MongoDB】 検索

検索

cli = MongoClient()
db = cli.sample

_datas = list(_col.find())
_datas = list(_col.find({}))   #上に同じ
_datas = list(_col.find({'temp':'10'}))     # temp=10
_datas = list(_col.find({},{'_id':False}))   # _idは、表示しない

 

$exist    特定のフィールドを持つデータのみ

  _datas = list(_col.find({
    'temp':{'$exists':True},
    'temp_water':{'$exists':True},
    'water_level':{'$exists':True},
    'apikey':{'$exists':True}}) )

 

nginx+uWSGI+bottle

ubuntu 14.04

【install】

sudo apt-get -y update
sudo apt-get -y upgrade
sudo apt-get dist-upgrade -y
sudo apt-get -y install build-essential
sudo apt-get -y install python3-dev
sudo apt-get install python3
wget https://pypi.python.org/packages/source/d/distribute/distribute-0.7.3.zip
sudo apt-get install unzip
unzip distribute-0.7.3.zip
cd distribute-0.7.3
sudo python3 setup.py install
sudo easy_install pip
sudo pip install uwsgi
sudo apt-get install nginx
sudo pip install bottle

セキュリティパッチ自動更新
sudo dpkg-reconfigure --priority=low unattended-upgrades

SSH総当たり攻撃予防
sudo apt-get install -y fail2ban

 
nginxの設定
/etc/nginx/conf.d/app.conf

一旦、http版

server {
    listen       80;
    server_name  mknod.server;
    access_log   /var/log/nginx/mknod.server.log;

    location / {
        include     uwsgi_params;
        uwsgi_pass  unix:///tmp/uwsgi.sock;
    }
}

nginx起動
sudo service nginx start
app.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-

from bottle import route, run, default_app

@route('/')
def hello():
    return 'Hello World! abc'

if __name__ == '__main__':
    run(host='mknod.server', port=1234)
else:
    application = default_app()

通常のbottleアプリとして起動するときは

python3 app.py

動作確認は、

curl http://mknod.server:1234/

uwsgi経由で起動するときは下記のように設定。

uwsgiの設定と起動

mkdir ~/app
cd ~/app
touch uwsgi.ini    

# uwsgi.iniを下記のように編集

sudo uwsgi uwsgi.ini

uwsgi.ini

[uwsgi]
socket       = /tmp/uwsgi.sock
pidfile      = /tmp/uwsgi/mknod.server.pid
daemonize    = /tmp/uwsgi/mknod.server.log
master       = True
file         = app.py

chmod-socket = 666

uwsgiの停止

sudo kill -QUIT `cat /tmp/uwsgi/mknod.server.pid`

 

REST test script

from bottle import route, run, template,get,post,put,delete,request,response
import json
import os


def secure_response_headers(response):
    response.set_header('Content-Type', 'application/json')
    response.set_header('X-XSS-Protection', '1; mode=block')
    response.set_header('X-Frame-Options', 'deny')
    response.set_header('Content-Security-Policy', "default-src 'none'")
    response.set_header('Strict-Transport-Security', 'max-age=31536000')
    response.set_header('X-Content-Type-Options', 'nosniff')
    return response

def debug_request():

  print('--- QUERY ---')
  for k,v in request.query.items():
    print( k+"="+v )

  print('--- COKKIE ---')
  for k,v in request.cookies.items():
    print( k+"="+v )

  print('--- HEADER ---')
  for k,v in request.headers.items():
    print( k+"="+v )

  print('--- FORM ---')
  for k,v in request.forms.allitems():
    print( k+"="+v )


@get('/gettest')
def gettest():

  debug_request()

  _a = request.query['a']  # same as request.query.get('a')
  _b = request.query['b']  # same as request.query.get('b')

  secure_response_headers(response)
  return json.dumps({'staus':'ok'})

@post('/posttest')
def posttest():

  debug_request()
  secure_response_headers(response)
  return json.dumps({'staus':'ok'})

@put('/puttest')
def puttest():

  debug_request()

  secure_response_headers(response)
  return json.dumps({'staus':'ok'})

@delete('/deletetest')
def deletetest():

  debug_request()

  secure_response_headers(response)
  return json.dumps({'staus':'ok'})


@post('/post_multipart_test')
def post_multipart_test():

  debug_request()

  # make image folder
  _dir = 'user/image/123/'
  os.makedirs(_dir, exist_ok=True)

  # save file.
  _file = request.files.get('image')

  upload_file = _dir + _file.filename
  _file.save(upload_file)


  print('file uploaded :' + str(os.path.isfile(upload_file)))

  secure_response_headers(response)
  return json.dumps({'staus':'ok', 'filename':_file.filename})


@route('/hello')
def hello():
  _msg = "World!"
  return template('Hello {{a}}!', a=_msg)


if __name__ == '__main__':
  run(host='192.168.111.102', port=8888, debug=True, reloader=True)