├── .github └── workflows │ └── semgrep.yml ├── .gitignore ├── .images ├── create.png └── logs.png ├── API.md ├── BE ├── __pycache__ │ ├── app.cpython-36.pyc │ ├── dns_resources.cpython-36.pyc │ ├── models.cpython-36.pyc │ ├── resources.cpython-36.pyc │ └── run.cpython-36.pyc ├── app.py ├── dns.py ├── dns_resources.py ├── main.py ├── models.py ├── requirements.txt ├── resources.py └── uwsgi.ini ├── CHANGELOG.md ├── FE ├── .DS_Store ├── .env.development ├── .env.production ├── README.md ├── package-lock.json ├── package.json ├── public │ ├── android-chrome-192x192.png │ ├── android-chrome-512x512.png │ ├── apple-touch-icon.png │ ├── bomb.png │ ├── bomb_white.png │ ├── browserconfig.xml │ ├── btc.png │ ├── favicon-16x16.png │ ├── favicon-32x32.png │ ├── favicon.ico │ ├── index.html │ ├── logo.png │ ├── mstile-150x150.png │ └── site.webmanifest └── src │ ├── App.css │ ├── App.js │ ├── App.test.js │ ├── Dashboard.js │ ├── Home.js │ ├── Login.js │ ├── MyBins.js │ ├── NewBin.js │ ├── Settings.js │ ├── Signup.js │ ├── Support.js │ ├── TopBar.js │ ├── index.css │ ├── index.js │ └── logo.svg ├── README.md ├── config.yaml ├── docker-compose.yml └── vulnerableApp ├── app.py └── dns.py /.github/workflows/semgrep.yml: -------------------------------------------------------------------------------- 1 | on: 2 | pull_request: {} 3 | push: 4 | branches: 5 | - main 6 | - master 7 | paths: 8 | - .github/workflows/semgrep.yml 9 | schedule: 10 | # random HH:MM to avoid a load spike on GitHub Actions at 00:00 11 | - cron: 26 20 * * * 12 | name: Semgrep 13 | jobs: 14 | semgrep: 15 | name: Scan 16 | runs-on: ubuntu-20.04 17 | env: 18 | SEMGREP_APP_TOKEN: ${{ secrets.SEMGREP_APP_TOKEN }} 19 | container: 20 | image: returntocorp/semgrep 21 | steps: 22 | - uses: actions/checkout@v3 23 | - run: semgrep ci 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | FE/node_modules 2 | */__pycache__ 3 | .DS_Store 4 | -------------------------------------------------------------------------------- /.images/create.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/makuga01/dnsFookup/43fbeacfa0d16746267e5c773f7dab66229c400a/.images/create.png -------------------------------------------------------------------------------- /.images/logs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/makuga01/dnsFookup/43fbeacfa0d16746267e5c773f7dab66229c400a/.images/logs.png -------------------------------------------------------------------------------- /API.md: -------------------------------------------------------------------------------- 1 | # Api documentation 2 | 3 | For api to work you will need to be signed in - API is using bearer tokens for authentication and `Content-Type` has to be set to `application/json` 4 | 5 | ## Registration `/auth/signup` 6 | 7 | `POST /auth/signup` 8 | *JSON body:* 9 | ``` 10 | { 11 | "username": "marek", 12 | "password": "ffffffff" 13 | } 14 | ``` 15 | *Response:* 16 | ``` 17 | { 18 | "name": "marek", 19 | "access_token": "eyJuYW1lIjoiMTMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzNyBTZUtyM1QgVDBLM24ifQo=" 20 | } 21 | ``` 22 | 23 | ## Login `/auth/login` (it's the same as signup) 24 | 25 | `POST /auth/login` 26 | *JSON body:* 27 | ``` 28 | { 29 | "username": "marek", 30 | "password": "ffffffff" 31 | } 32 | ``` 33 | *Response:* 34 | ``` 35 | { 36 | "name": "marek", 37 | "access_token": "eyJuYW1lIjoiMTMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzNyBTZUtyM1QgVDBLM24ifQo=" 38 | } 39 | ``` 40 | 41 | ## Logout `/auth/logout` 42 | 43 | `POST /auth/logout` 44 | 45 | Json body can be left blank 46 | 47 | *Response:* 48 | ``` 49 | { 50 | "message": "Access token has been revoked" 51 | } 52 | ``` 53 | 54 | ## Get username 55 | 56 | `GET /api/user` 57 | 58 | *Response:* 59 | ``` 60 | { 61 | "name": "marek" 62 | } 63 | ``` 64 | 65 | ## Create new token `/api/fookup/new` 66 | 67 | `POST /api/fookup/new` 68 | *JSON body:* 69 | ``` 70 | { 71 | "name":"dsads", 72 | "ip_props": 73 | { 74 | "1":{ 75 | "ip":"123.0.0.1", 76 | "repeat":13, 77 | "type": "A" 78 | }, 79 | "2":{ 80 | "ip":"google.com", 81 | "repeat": 2, 82 | "type": "CNAME" 83 | }, 84 | "3":{ 85 | "ip":"::1", 86 | "repeat": "4ever", 87 | "type": "AAAA" 88 | } 89 | } 90 | } 91 | ``` 92 | 93 | To get this straight 94 | - `"name"` is the name if the dns bin - it comes handy in frontend app 95 | - `"ip_props"` is where the magic happens 96 | * `"somenumber"` - these numbers have to be in order from 1 to how much you want (max 32), so no random numbers... the dns server will go from "1" and repeat the ip one after another as supplied, when it comes to the last ip, it will reset the counter and go from "1" again, if ``"4ever"`` is supplied in `repeat` field this loop will not continue and domain remains stuck on the 4ever IP 97 | - `"ip"` - this is the ip to resolve 98 | - `"repeat"` - how many times this ip should be resolved - this can be set to any positive integer or "4ever" to never stop resolving this ip after program gets to it 99 | - `"type"` - DNS response type (CNAME, AAAA, A) 100 | 101 | *Response:* 102 | ``` 103 | { 104 | "subdomain": "0dd4d9083d7647e1a5fd5f1444e655ce.gel0.space" 105 | } 106 | ``` 107 | this is the domain that will do the magic 108 | 109 | ### Example 110 | let's say we supplied this 111 | ``` 112 | { 113 | "name":"dsads", 114 | "ip_props": 115 | { 116 | "1":{ 117 | "ip":"1.1.1.1", 118 | "repeat":2, 119 | "type": "A" 120 | 121 | }, 122 | "2":{ 123 | "ip":"2.2.2.2", 124 | "repeat": 1, 125 | "type": "A" 126 | } 127 | } 128 | } 129 | ``` 130 | and we are running `host` command against this domain 131 | ``` 132 | $host {domain} 133 | {domain} has address 1.1.1.1 134 | 135 | $host {domain} 136 | {domain} has address 1.1.1.1 137 | 138 | $host {domain} 139 | {domain} has address 2.2.2.2 140 | 141 | $host {domain} 142 | {domain} has address 1.1.1.1 143 | 144 | $host {domain} 145 | {domain} has address 1.1.1.1 146 | 147 | $host {domain} 148 | {domain} has address 2.2.2.2 149 | ... And this will go on and on 150 | ``` 151 | 152 | ### EXAMPLE 2 with "4ever" 153 | 154 | ``` 155 | { 156 | "name":"dsads", 157 | "ip_props": 158 | { 159 | "1":{ 160 | "ip":"1.1.1.1", 161 | "repeat":2, 162 | "type": "A" 163 | 164 | }, 165 | "2":{ 166 | "ip":"2.2.2.2", 167 | "repeat": "4ever", 168 | "type": "A" 169 | } 170 | } 171 | } 172 | ``` 173 | 174 | Output of `host` 175 | ``` 176 | $host {domain} 177 | {domain} has address 1.1.1.1 178 | 179 | $host {domain} 180 | {domain} has address 1.1.1.1 181 | 182 | $host {domain} 183 | {domain} has address 2.2.2.2 184 | 185 | $host {domain} 186 | {domain} has address 2.2.2.2 187 | 188 | $host {domain} 189 | {domain} has address 2.2.2.2 190 | 191 | $host {domain} 192 | {domain} has address 2.2.2.2 193 | 194 | $host {domain} 195 | {domain} has address 2.2.2.2 196 | 197 | It will never resolve to 1.1.1.1 ...Almost 198 | ``` 199 | 200 | But there is one exception to this 4ever loop 201 | info about what was resolved and what should be resolved next is stored in redis with expiration set to 1 hour, so the domain will resolve to 1.1.1.1 again in 1 hour after creating it. You can change this setting in REDIS_EXP variable in `dns.py` and `dns_resources.py` 202 | 203 | ## Delete token 204 | 205 | `POST /api/fookup/delete` 206 | 207 | *JSON body:* 208 | ``` 209 | { 210 | "uuid": "0dd4d9083d7647e1a5fd5f1444e655ce" 211 | } 212 | ``` 213 | 214 | *Response:* 215 | ``` 216 | { 217 | "success": true 218 | } 219 | ``` 220 | 221 | 222 | ## List all bins `/api/fookup/listAll` 223 | 224 | `GET /api/fookup/listAll` 225 | 226 | *Response:* 227 | ``` 228 | [ 229 | { 230 | "uuid": "0dd4d9083d7647e1a5fd5f1444e655ce", 231 | "name": "dsads" 232 | }, 233 | { 234 | "uuid": "ffffffffffffffffffffffffffffffff", 235 | "name": "someothername" 236 | } 237 | ] 238 | ``` 239 | 240 | This will respond with uuids and names of all the bins you have ever created 241 | 242 | ## Get properties about specific bin `/api/fookup/props` 243 | 244 | `POST /api/fookup/props` 245 | 246 | *JSON body:* 247 | 248 | 249 | ``` 250 | { 251 | "uuid":"0dd4d9083d7647e1a5fd5f1444e655ce" 252 | } 253 | ``` 254 | 255 | *Response:* 256 | 257 | ``` 258 | { 259 | "ip_props": { 260 | "1": { 261 | "ip": "123.0.0.0", 262 | "repeat": 13, 263 | "type": "A" 264 | }, 265 | "2": { 266 | "ip": "0.0.1.77", 267 | "repeat": 3, 268 | "type": "A" 269 | } 270 | }, 271 | "ip_to_resolve": "1", 272 | "turn": 5, 273 | "name": "dsads" 274 | } 275 | ``` 276 | This will return all info about the dnsbin, you already are familiar with the `ip_props` and `name` part so i will explain that other stuff 277 | - `"ip_to_resolve"`: number of ip the program should resolve to right now 278 | - `"turn"` - the number of times `"ip_to_resolve"` was already resolved so when turn == repeat, ip_to_resolve will become "2" and this will reset 279 | 280 | ## All logs `/api/fookup/logs/all` 281 | 282 | This will return all logs from the all bins owned by user 283 | This can be a bit slow if you requested the domains 12321312 times 284 | 285 | `GET /api/fookup/logs/all` 286 | 287 | *Response:* 288 | 289 | ``` 290 | [ 291 | { 292 | "uuid": "0dd4d9083d7647e1a5fd5f1444e655ce", 293 | "resolved_to": "123.0.0.0", 294 | "domain": "0dd4d9083d7647e1a5fd5f1444e655ce.gel0.space", 295 | "origin_ip": "127.0.0.1", 296 | "port": "41095", 297 | "created_date": "2019-09-17 20:38:44.769560" 298 | }, 299 | ...snip... 300 | { 301 | "uuid": "ffffffffffffffffffffffffffffffff", 302 | "resolved_to": "99.123.64.19", 303 | "domain": "0dd4d9083d7647e1a5fd5f1444e655ce.gel0.space", 304 | "origin_ip": "127.0.0.1", 305 | "port": "51515", 306 | "created_date": "2019-09-17 20:38:50.321975" 307 | } 308 | ] 309 | ``` 310 | 311 | ## Logs for certain uuid /api/fookup/logs/uuid 312 | 313 | `POST /api/fookup/logs/uuid` 314 | 315 | *JSON body:* 316 | 317 | ``` 318 | { 319 | "uuid":"0dd4d9083d7647e1a5fd5f1444e655ce" 320 | } 321 | ``` 322 | 323 | 324 | *Response:* 325 | 326 | ``` 327 | [ 328 | { 329 | "uuid": "0dd4d9083d7647e1a5fd5f1444e655ce", 330 | "resolved_to": "123.0.0.0", 331 | "domain": "0dd4d9083d7647e1a5fd5f1444e655ce.gel0.space", 332 | "origin_ip": "127.0.0.1", 333 | "port": "41095", 334 | "created_date": "2019-09-17 20:38:44.769560" 335 | }, 336 | ...snip... 337 | { 338 | "uuid": "0dd4d9083d7647e1a5fd5f1444e655ce", 339 | "resolved_to": "0.0.1.77", 340 | "domain": "0dd4d9083d7647e1a5fd5f1444e655ce.gel0.space", 341 | "origin_ip": "127.0.0.1", 342 | "port": "51515", 343 | "created_date": "2019-09-17 20:38:50.321975" 344 | } 345 | ] 346 | ``` 347 | 348 | ## Statistics `/api/statistics` 349 | 350 | This just gets the statistics for the frontend app 351 | 352 | `GET /api/statistics` 353 | 354 | *Response:* 355 | 356 | ``` 357 | { 358 | "request_count": 420, 359 | "created_bins": 69 360 | } 361 | ``` 362 | 363 | ## Change password `/auth/change_pw` 364 | 365 | `POST /auth/change_pw` 366 | 367 | *JSON body:* 368 | 369 | ``` 370 | { 371 | "old_pw": "password", 372 | "new_pw":"L337P4ssw0rd42069" 373 | } 374 | ``` 375 | 376 | 377 | *Response:* 378 | 379 | ``` 380 | {'success': true} 381 | ``` 382 | 383 | ## Delete all account data `/auth/delete_me` 384 | 385 | `POST /auth/delete_me` 386 | 387 | *JSON body:* 388 | 389 | ``` 390 | { 391 | "password":"L337P4ssw0rd42069" 392 | } 393 | ``` 394 | 395 | 396 | *Response:* 397 | 398 | ``` 399 | { 400 | 'message': 'Access token has been revoked', 401 | 'total_deleted_rows': { 402 | "logs": 420, 403 | "bins": 69, 404 | "user": 1 405 | }, 406 | 'success': true 407 | } 408 | ``` 409 | -------------------------------------------------------------------------------- /BE/__pycache__/app.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/makuga01/dnsFookup/43fbeacfa0d16746267e5c773f7dab66229c400a/BE/__pycache__/app.cpython-36.pyc -------------------------------------------------------------------------------- /BE/__pycache__/dns_resources.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/makuga01/dnsFookup/43fbeacfa0d16746267e5c773f7dab66229c400a/BE/__pycache__/dns_resources.cpython-36.pyc -------------------------------------------------------------------------------- /BE/__pycache__/models.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/makuga01/dnsFookup/43fbeacfa0d16746267e5c773f7dab66229c400a/BE/__pycache__/models.cpython-36.pyc -------------------------------------------------------------------------------- /BE/__pycache__/resources.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/makuga01/dnsFookup/43fbeacfa0d16746267e5c773f7dab66229c400a/BE/__pycache__/resources.cpython-36.pyc -------------------------------------------------------------------------------- /BE/__pycache__/run.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/makuga01/dnsFookup/43fbeacfa0d16746267e5c773f7dab66229c400a/BE/__pycache__/run.cpython-36.pyc -------------------------------------------------------------------------------- /BE/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask_restful import Api 3 | from flask_sqlalchemy import SQLAlchemy 4 | from flask_jwt_extended import JWTManager 5 | import psycopg2 6 | from flask_cors import CORS 7 | import yaml 8 | 9 | app = Flask(__name__) 10 | api = Api(app) 11 | cors = CORS(app, resources={r"/*": {"origins": "*"}}) 12 | 13 | """ 14 | *** CONFIG *** 15 | """ 16 | 17 | config = yaml.safe_load(open("../config.yaml")) 18 | 19 | db_conf = config['sql'] 20 | 21 | app.config['SQLALCHEMY_DATABASE_URI'] = f"\ 22 | {db_conf['protocol']}://\ 23 | {db_conf['user']}:{db_conf['password']}\ 24 | @{db_conf['host']}\ 25 | /{db_conf['db']}\ 26 | " 27 | 28 | app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = db_conf['deprec_warn'] # silence the deprecation warning 29 | 30 | db = SQLAlchemy(app) 31 | 32 | @app.before_first_request 33 | def create_tables(): 34 | db.create_all() 35 | 36 | app.config['JWT_SECRET_KEY'] = config['jwt']['secret_key'] 37 | jwt = JWTManager(app) 38 | 39 | app.config['JWT_BLACKLIST_ENABLED'] = config['jwt']['blacklist_enabled'] 40 | app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = config['jwt']['blacklist_token_checks'] 41 | app.config['JWT_ACCESS_TOKEN_EXPIRES'] = config['jwt']['token_expires'] 42 | 43 | """ 44 | *** CONFIG *** 45 | """ 46 | 47 | @jwt.token_in_blacklist_loader 48 | def check_if_token_in_blacklist(decrypted_token): 49 | jti = decrypted_token['jti'] 50 | return models.RevokedTokenModel.is_jti_blacklisted(jti) 51 | 52 | import models, resources, dns_resources 53 | 54 | api.add_resource(resources.UserRegistration, '/auth/signup') 55 | api.add_resource(resources.UserLogin, '/auth/login') 56 | api.add_resource(resources.UserLogoutAccess, '/auth/logout') 57 | api.add_resource(resources.ChangePw, '/auth/change_pw') 58 | 59 | api.add_resource(dns_resources.iDontWannaBeAnymore, '/auth/delete_me') 60 | 61 | api.add_resource(dns_resources.CreateRebindToken, '/api/fookup/new') 62 | api.add_resource(dns_resources.DeleteUUID, '/api/fookup/delete') 63 | 64 | api.add_resource(resources.UserName, '/api/user') 65 | api.add_resource(dns_resources.GetUserTokens, '/api/fookup/listAll') 66 | api.add_resource(dns_resources.GetProps, '/api/fookup/props') 67 | api.add_resource(dns_resources.GetUserLogs, '/api/fookup/logs/all') 68 | api.add_resource(dns_resources.GetUuidLogs, '/api/fookup/logs/uuid') 69 | api.add_resource(dns_resources.GetStatistics, '/api/statistics') 70 | -------------------------------------------------------------------------------- /BE/dns.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import time 3 | import threading 4 | import traceback 5 | import socketserver as SocketServer 6 | from dnslib import * 7 | import json 8 | from redis import StrictRedis 9 | from app import db 10 | from datetime import datetime 11 | import yaml 12 | 13 | """ 14 | *** CONFIG *** 15 | """ 16 | 17 | config = yaml.safe_load(open("../config.yaml")) 18 | 19 | port = config['dns']['port'] 20 | ip = config['dns']['ip'] 21 | 22 | USE_FAILURE = config['dns']['use_failure_ip'] 23 | FAILURE_IP = config['dns']['failure_ip'] 24 | host_domain = config['dns']['domain'] 25 | use_fail_ns = config['dns']['use_fail_ns'] 26 | fail_ns = config['dns']['fail_ns'] 27 | 28 | redis_config = { 29 | 'host': config['redis']['host'], 30 | 'port': config['redis']['port'], 31 | 'password': config['redis']['password'] 32 | } 33 | REDIS_EXP = config['redis']['expiration'] #seconds 34 | redis = StrictRedis(socket_connect_timeout = config['redis']['timeout'],**redis_config) 35 | 36 | """ 37 | *** CONFIG *** 38 | """ 39 | 40 | """ 41 | SQLAlchemy models for easier access to database 42 | """ 43 | 44 | 45 | class DnsModel(db.Model): 46 | db.metadata.clear() 47 | __tablename__ = "dns_tokens" 48 | extend_existing = True 49 | id = db.Column(db.Integer, primary_key=True) 50 | username = db.Column(db.String(120), unique=False, nullable=False) 51 | uuid = db.Column(db.String(120), unique=True, nullable=False) 52 | props = db.Column(db.String(2056), unique=False, nullable=False) 53 | 54 | @classmethod 55 | def get_props(cls, uuid): 56 | def to_json(x): 57 | return {"username": x.username, "props": x.props} 58 | 59 | return list(map(lambda x: to_json(x), cls.query.filter_by(uuid=uuid)))[0] 60 | 61 | 62 | class LogModel(db.Model): 63 | db.metadata.clear() 64 | __tablename__ = "dns_logs" 65 | extend_existing = True 66 | id = db.Column(db.Integer, primary_key=True) 67 | uuid = db.Column(db.String(64), unique=False, nullable=False) 68 | resolved_to = db.Column(db.String(253), unique=False, nullable=False) 69 | domain = db.Column(db.String(253), unique=False, nullable=False) 70 | ip = db.Column(db.String(120), unique=False, nullable=False) 71 | port = db.Column(db.String(32), unique=False, nullable=False) 72 | created_date = db.Column(db.String(128), unique=False, nullable=False) 73 | 74 | def save_to_db(self): 75 | db.session.add(self) 76 | db.session.commit() 77 | 78 | 79 | """ 80 | Lambda functions used for easier manipulation with redis 81 | """ 82 | 83 | setJson = lambda uid, data: redis.setex(uid, REDIS_EXP, json.dumps(data)) 84 | getJson = lambda uid: json.loads(redis.get(uid)) 85 | 86 | def gen_nxdomain_reply(request): 87 | # Stolen from https://github.com/major1201/dns-router/blob/master/dns-router.py 88 | 89 | reply = request.reply() 90 | reply.header.rcode = getattr(RCODE, 'NXDOMAIN') 91 | return reply 92 | 93 | def getResType(type): 94 | """ 95 | This function returns dnslib function and value of record type necessary for creating valid dns answer 96 | 97 | Note for myself/someone other working on this 98 | Quick script to determine values for dns answer associated with record types 99 | for i in range(255): 100 | try: 101 | print(QTYPE[i], i) 102 | except: pass 103 | """ 104 | types = { 105 | "A": (1,A), 106 | "AAAA": (28, AAAA), 107 | "CNAME": (5, CNAME) 108 | } 109 | return(types[type]) 110 | 111 | def buildResponse(d, ADDR, PORT): 112 | """ 113 | This function is used to look into redis/SQL and by the uuid (3rd level domain) 114 | get the IP the domain should resolve to at the moment 115 | """ 116 | 117 | data = DNSRecord.parse(d) 118 | qtype = QTYPE[data.q.qtype] 119 | domain = str(data.q.qname).split('.') 120 | rtype = 1 # A 121 | reply = DNSRecord(DNSHeader(id=data.header.id, qr=1, aa=1, ra=1), q=data.q) 122 | fail_reply = reply if USE_FAILURE else gen_nxdomain_reply(data) 123 | """ 124 | First check if supplied domain has subdomains (if not resolve to FAILURE_IP) 125 | 126 | Create list containing all subdomains requested and 127 | get uuid from them 128 | Request format: dig some.random.subdomains.{uuid}.gel0.space 129 | """ 130 | 131 | if '.'.join(domain[-3:-1]) != host_domain and use_fail_ns: 132 | print(f'{str(datetime.now())} - {ADDR}:{PORT} {".".join(domain[-3:-1])} is not my thing NS => {fail_ns}') 133 | fail_reply.add_answer(RR(rname = '.'.join(domain), rtype = 2, rclass = 1, rdata = NS(fail_ns))) 134 | return fail_reply.pack() 135 | 136 | if len(domain) < 4: 137 | print(f'{str(datetime.now())} - {ADDR}:{PORT} {".".join(domain[:-1])} => No subdomain, no fun => {FAILURE_IP if USE_FAILURE else "NXDOMAIN"}') 138 | 139 | fail_reply.add_answer(RR(rname = '.'.join(domain), rtype = rtype, rclass = 1, rdata = A(FAILURE_IP))) if USE_FAILURE else 0 140 | return fail_reply.pack() 141 | subs = domain[:-3] 142 | uuid = subs[-1] 143 | 144 | """ 145 | Check for uuid in redis 146 | If uuid is not present (doesn't exist or expired) it checks 147 | if the uuid is in database and tries to load it back to redis 148 | If the uuid doesn't exist the dns query will resolve to 0.0.0.0, 149 | script will print what's happening and the life goes on... 150 | """ 151 | if not redis.exists(uuid): 152 | try: 153 | props = DnsModel.get_props(uuid)["props"] 154 | setJson(uuid, json.loads(props)) 155 | except: 156 | print(f'{str(datetime.now())} - {ADDR}:{PORT} {".".join(domain)[:-1]} (doesn\'t exist) => {FAILURE_IP if USE_FAILURE else "NXDOMAIN"}') 157 | fail_reply.add_answer(RR(rname = '.'.join(domain), rtype = rtype, rclass = 1, rdata = A(FAILURE_IP))) if USE_FAILURE else 0 158 | return fail_reply.pack() 159 | 160 | """ 161 | Get info about uuid from redis 162 | """ 163 | rbnd_json = getJson(uuid) 164 | 165 | """ 166 | Turn value increments everytime request to dns server is made 167 | 168 | repeat = How many times this IP should be repetatively resolved 169 | can be '4ever' or int number of repeats 170 | Then check if repeat is '4ever' or integer 171 | """ 172 | rbnd_json["turn"] += 1 173 | repeat = rbnd_json["ip_props"][rbnd_json["ip_to_resolve"]]["repeat"] 174 | 175 | if repeat == "4ever" or type(repeat) != int: 176 | """ 177 | Do nothing when rebinding forever or 178 | when an invalid repeat value is somehow supplied 179 | """ 180 | pass 181 | elif rbnd_json["turn"] >= repeat: 182 | """ 183 | Reset turn value and move on to next IP 184 | """ 185 | rbnd_json["turn"] = 0 186 | rbnd_json["ip_to_resolve"] = ( 187 | str(int(rbnd_json["ip_to_resolve"]) + 1) 188 | if len(rbnd_json["ip_props"]) != int(rbnd_json["ip_to_resolve"]) 189 | else "1" 190 | ) 191 | setJson(uuid, rbnd_json) 192 | else: 193 | """ 194 | If nothing special is happening just save data with incremented turn back to redis 195 | """ 196 | setJson(uuid, rbnd_json) 197 | 198 | """ 199 | Print what was requested and the ip server responds with 200 | Log this data into db 201 | Aaaand finally return the data 202 | """ 203 | resolve_to = rbnd_json["ip_props"][rbnd_json["ip_to_resolve"]]["ip"] 204 | answer_type = rbnd_json["ip_props"][rbnd_json["ip_to_resolve"]].get("type") 205 | now = str(datetime.now()) 206 | print(f'{now} - {ADDR}:{PORT} {answer_type if answer_type else "A"} {".".join(domain)[:-1]} => {resolve_to}') 207 | 208 | rtype, rfunc = getResType(answer_type) if answer_type else (1, A) 209 | 210 | new_log = LogModel( 211 | uuid=uuid, 212 | domain=".".join(domain)[:-1], 213 | ip=ADDR, 214 | port=PORT, 215 | resolved_to=resolve_to, 216 | created_date=now, 217 | ) 218 | new_log.save_to_db() 219 | 220 | print(resolve_to) 221 | reply.add_answer(RR(rname = '.'.join(domain), rtype = rtype, rclass = 1, rdata = rfunc(resolve_to))) 222 | return reply.pack() 223 | 224 | # Stolen: 225 | # https://gist.github.com/andreif/6069838 226 | 227 | class BaseRequestHandler(SocketServer.BaseRequestHandler): 228 | 229 | def get_data(self): 230 | raise NotImplementedError 231 | 232 | def send_data(self, data): 233 | raise NotImplementedError 234 | 235 | def handle(self): 236 | ADDR, PORT = self.client_address 237 | 238 | try: 239 | data = self.get_data() 240 | self.send_data(buildResponse(data, ADDR, PORT)) 241 | except Exception: 242 | traceback.print_exc(file=sys.stderr) 243 | 244 | 245 | class TCPRequestHandler(BaseRequestHandler): 246 | # A bit modified since the original code errors out in python3.7 247 | def get_data(self): 248 | data = self.request.recv(8192).strip() 249 | sz = int(data[:2].hex(), 16) 250 | if sz < len(data) - 2: 251 | raise Exception("Wrong size of TCP packet") 252 | elif sz > len(data) - 2: 253 | raise Exception("Too big TCP packet") 254 | return data[2:] 255 | 256 | def send_data(self, data): 257 | sz = hex(len(data))[2:].zfill(4) 258 | return self.request.sendall(bytes.fromhex(sz) + data) 259 | 260 | 261 | class UDPRequestHandler(BaseRequestHandler): 262 | 263 | def get_data(self): 264 | return self.request[0].strip() 265 | 266 | def send_data(self, data): 267 | return self.request[1].sendto(data, self.client_address) 268 | 269 | 270 | if __name__ == '__main__': 271 | print("DNS server warming up!") 272 | 273 | servers = [ 274 | SocketServer.ThreadingUDPServer((ip, port), UDPRequestHandler), 275 | SocketServer.ThreadingTCPServer((ip, port), TCPRequestHandler), 276 | ] 277 | for s in servers: 278 | thread = threading.Thread(target=s.serve_forever) # that thread will start one more thread for each request 279 | thread.daemon = True # exit the server thread when the main thread terminates 280 | thread.start() 281 | print("%s server loop running in thread: %s" % (s.RequestHandlerClass.__name__[:3], thread.name)) 282 | 283 | try: 284 | while 1: 285 | time.sleep(1) 286 | sys.stderr.flush() 287 | sys.stdout.flush() 288 | 289 | except KeyboardInterrupt: 290 | pass 291 | finally: 292 | for s in servers: 293 | s.shutdown() 294 | -------------------------------------------------------------------------------- /BE/dns_resources.py: -------------------------------------------------------------------------------- 1 | from flask_restful import Resource, reqparse 2 | from models import UserModel, RevokedTokenModel, DnsModel, LogModel 3 | from flask_jwt_extended import (create_access_token, create_refresh_token, jwt_required, jwt_refresh_token_required, get_jwt_identity, get_raw_jwt) 4 | import json 5 | from uuid import uuid4 6 | from redis import StrictRedis 7 | from validators.ip_address import ipv4, ipv6 8 | from validators.domain import domain as checkDomain 9 | from jsonschema import validate 10 | import jsonschema.exceptions 11 | import yaml 12 | 13 | """ 14 | *** CONFIG *** 15 | """ 16 | 17 | config = yaml.safe_load(open("../config.yaml")) 18 | 19 | DOMAIN = config['dns']['domain'] 20 | 21 | redis_config = { 22 | 'host': config['redis']['host'], 23 | 'port': config['redis']['port'], 24 | 'password': config['redis']['password'] 25 | } 26 | REDIS_EXP = config['redis']['expiration'] #seconds 27 | redis = StrictRedis(socket_connect_timeout = config['redis']['timeout'],**redis_config) 28 | 29 | """ 30 | *** CONFIG *** 31 | """ 32 | 33 | """ 34 | For easier manipulation with redis 35 | """ 36 | setJson = lambda uid, data: redis.setex(uid, REDIS_EXP, json.dumps(data)) 37 | getJson = lambda uid: json.loads(redis.get(uid)) 38 | 39 | 40 | 41 | def checkKeys(lst): 42 | good = True 43 | for i in range(1,len(lst)+1): 44 | if str(i) in lst: 45 | pass 46 | else: 47 | good = good and False 48 | return good 49 | 50 | class CreateRebindToken(Resource): 51 | @jwt_required 52 | def post(self): 53 | """ 54 | This function creates new rebind subdomain from json looking something like this: 55 | { 56 | "ip_props": { 57 | "1":{ # <= Order in which domains will be resolved 58 | "ip": "88.23.99.110", # <= ip to resolve 59 | "repeat": 3 # <= how many times 60 | } 61 | "2":{ 62 | "ip": "169.254.169.254", 63 | "repeat": "4ever" # <= forever can be supplied to never stop resolving this domain 64 | } 65 | }, 66 | "name": "rbnd_test" # <= name (useful in web ui) 67 | } 68 | 69 | And half of the code just checks if input is correct if someone reading this has an 70 | idea how to do it more efficently please contribute 71 | """ 72 | parser = reqparse.RequestParser() 73 | parser.add_argument('ip_props', help = 'This field cannot be blank wtf', required = True, location="json") 74 | parser.add_argument('name', help = 'This field cannot be blank wtf', required = True, location="json") 75 | req_data = parser.parse_args() 76 | 77 | """ 78 | req_data['ip_props'] is a json in string so I need to load it :D 79 | """ 80 | data = json.loads(req_data['ip_props'].replace('\'', '"')) 81 | 82 | """ 83 | Validate input against base_schema 84 | """ 85 | req_data['ip_props'] = data 86 | base_schema = { 87 | "type": "object", 88 | "properties": { 89 | "ip_props": {"type": "object"}, 90 | "name": { 91 | "type": "string", 92 | "maxLength": 120 93 | } 94 | } 95 | } 96 | 97 | try: 98 | validate(instance=req_data, schema=base_schema) 99 | except jsonschema.exceptions.ValidationError: 100 | return {'message': 'Something went wrong, the supplied input doesn\'t seem to be valid'}, 500 101 | 102 | 103 | """ 104 | Check if 105 | - Less than 32 IPs are supplied 106 | - Some retard can't count 107 | """ 108 | if not len(data.keys())<32: 109 | return {'message': 'Something went wrong, max IPs: 32'}, 500 110 | elif not checkKeys(data.keys()): 111 | return {'message': f"Something went wrong, the str(numbers) go like this: ['1','2','3','4',...] and not {[x for x in data.keys()]}"}, 500 112 | 113 | """ 114 | Iterate through every ip_prop and do some checks - details are in comments below 115 | """ 116 | 117 | for i in data.keys(): 118 | """ 119 | This schema checks if 120 | - repeat is "4ever" or integer greater or equal to 1 121 | - ip and type is compatibile with one of A,AAAA and CNAME 122 | """ 123 | 124 | prop_schema = { 125 | "type": "object", 126 | "properties": { 127 | "repeat": { 128 | "anyOf": [ 129 | { 130 | "type": "integer", 131 | "minimum": 1 132 | }, 133 | { 134 | "type": "string", 135 | "pattern": "^4ever$" 136 | } 137 | ] 138 | }, 139 | "ip": { 140 | "type": "string", 141 | "anyOf": [ 142 | {"format": "ipv4"}, 143 | {"format": "ipv6"}, 144 | {"format": "idn-hostname"} 145 | ] 146 | }, 147 | "type": { 148 | "type": "string", 149 | "anyOf": [ 150 | {"pattern": "^A$"}, 151 | {"pattern": "^AAAA$"}, 152 | {"pattern": "^CNAME$"} 153 | ] 154 | } 155 | } 156 | } 157 | 158 | try: 159 | validate(instance=data[i], schema=prop_schema) 160 | except jsonschema.exceptions.ValidationError: 161 | return {'message': f'Something went wrong, the supplied input doesn\'t seem to be valid in [`ip_props`][{int(i)-1}]'}, 500 162 | 163 | """ 164 | Check if supplied record type matches ip 165 | So 127.0.0.1 can't be CNAME 166 | And google.com can't be answer for A :D 167 | """ 168 | record_funcs = { 169 | "CNAME": checkDomain, 170 | "A": ipv4, 171 | "AAAA": ipv6 172 | } 173 | if not record_funcs[data[i]['type']](data[i]['ip']): 174 | return {'message': f"data[{int(i)-1}]['ip'] has to be in {data[{int(i)-1}]['type']} format"}, 500 175 | 176 | 177 | """ 178 | Then put the data together 179 | Generate new uuid4 180 | Put it in database and redis 181 | Then return the whole domain 182 | """ 183 | 184 | # rbnd_json does not need name parameter - it's meant to be stored in redis and in props column in database 185 | rbnd_json = { 186 | 'ip_props': data, 187 | 'ip_to_resolve': '1', 188 | 'turn': -1 189 | } 190 | uuid = uuid4().hex 191 | if DnsModel.find_by_uuid(uuid): 192 | """ 193 | Just in case something bad happens 194 | """ 195 | return {'message': 'An error occured, please try again (REALLY TRY AGAIN, server generated uuid that exists, I didn\'t know it was possible :d) If you get this error please send it to me on twitter @marek_geleta You can follow me too'}, 500 196 | 197 | new_uuid = DnsModel( 198 | username = get_jwt_identity(), 199 | uuid = uuid, 200 | props = json.dumps(rbnd_json), 201 | name = req_data['name'] 202 | ) 203 | 204 | try: 205 | new_uuid.save_to_db() 206 | setJson(uuid, rbnd_json) 207 | return {"subdomain": f"{uuid}.{DOMAIN}"} 208 | except: 209 | return {'message': 'Something went wrong'}, 500 210 | 211 | class GetUserTokens(Resource): 212 | @jwt_required 213 | def get(self): 214 | """ 215 | returns all dns tokens owned by a logged in user 216 | """ 217 | return DnsModel.find_by_user(get_jwt_identity()) 218 | 219 | class GetProps(Resource): 220 | @jwt_required 221 | def post(self): 222 | """ 223 | returns info about dns token 224 | looks something like this: 225 | { 226 | "ip_props": { 227 | "1": { 228 | "ip": "1.0.0.0", 229 | "repeat": 1, 230 | "type": "A" 231 | }, 232 | "2": { 233 | "ip": "2.0.0.0", 234 | "repeat": 1, 235 | "type": "A" 236 | } 237 | }, 238 | "ip_to_resolve": "1", 239 | "turn": -1, # when new webhook is created the turn is on -1 240 | "name": "something" 241 | } 242 | """ 243 | parser = reqparse.RequestParser() 244 | parser.add_argument('uuid', help = 'This field cannot be blank', required = True, location="json") 245 | args = parser.parse_args() 246 | uuid = args['uuid'] 247 | data = DnsModel.get_props(uuid, get_jwt_identity()) 248 | if data: 249 | data['props'] = json.loads(data['props']) 250 | data['props']['name'] = data['name'] 251 | return data['props'] 252 | return {"msg": "An error occured"} 253 | 254 | class GetUserLogs(Resource): 255 | @jwt_required 256 | def get(self): 257 | """ 258 | Returns all user logs :O 259 | """ 260 | return LogModel.return_all(get_jwt_identity()) 261 | 262 | class GetUuidLogs(Resource): 263 | @jwt_required 264 | def post(self): 265 | """ 266 | Returns logs of supplied token 267 | (owner of the token must be logged in :D) 268 | """ 269 | parser = reqparse.RequestParser() 270 | parser.add_argument('uuid', help = 'This field cannot be blank', required = True) 271 | parser.add_argument('page', help = 'This field cannot be blank', required = False) 272 | args = parser.parse_args() 273 | page = int(args['page']) if args['page'] else 1 274 | entries, pages, data = LogModel.uuid_logs(args['uuid'], get_jwt_identity(), page=page) 275 | return {'pages': pages, 'data': data, 'entries': entries} 276 | 277 | class DeleteUUID(Resource): 278 | @jwt_required 279 | def post(self): 280 | parser = reqparse.RequestParser() 281 | parser.add_argument('uuid', help = 'This field cannot be blank', required = True) 282 | uuid = parser.parse_args()['uuid'] 283 | rds_delet = redis.delete(uuid) 284 | print("*"*20) 285 | print(rds_delet) 286 | print("*"*20) 287 | uuid_logs = LogModel.delete_by_uuid(uuid, get_jwt_identity()) 288 | uuid_props = DnsModel.delete_by_uuid(uuid, get_jwt_identity()) 289 | return {'uuid_props': uuid_props , 'uuid_logs': uuid_logs} 290 | 291 | class GetStatistics(Resource): 292 | """ 293 | Returns user statistics 294 | used in /dashboard in FE 295 | 296 | { 297 | "request_count": 1337, 298 | "created_bins": 69 299 | } 300 | 301 | """ 302 | @jwt_required 303 | def get(self): 304 | return LogModel.statistics_count(get_jwt_identity()) 305 | 306 | class iDontWannaBeAnymore(Resource): 307 | """ 308 | Deletes all tokens and logs then finally the user him(or her)self 309 | """ 310 | @jwt_required 311 | def post(self): 312 | parser = reqparse.RequestParser() 313 | parser.add_argument('password', help = 'This field cannot be blank', required = True) 314 | args = parser.parse_args() 315 | 316 | current_user = UserModel.find_by_username(get_jwt_identity()) 317 | 318 | if not current_user or not UserModel.verify_hash(args['password'], current_user.password): 319 | return {'message': 'Wrong credentials','success': False} 320 | 321 | del_logs = LogModel.delete_by_user(get_jwt_identity()) 322 | del_bins = DnsModel.delete_by_user(get_jwt_identity()) 323 | del_user = UserModel.delete_user(get_jwt_identity()) 324 | 325 | 326 | jti = get_raw_jwt()['jti'] 327 | try: 328 | revoked_token = RevokedTokenModel(jti = jti) 329 | revoked_token.add() 330 | return { 331 | 'message': 'Access token has been revoked', 332 | 'total_deleted_rows': { 333 | "logs": del_logs, 334 | "bins": del_bins, 335 | "user": del_user 336 | }, 337 | 'success': True 338 | } 339 | except: 340 | return {'message': 'Something went wrong', 'success': False} 341 | -------------------------------------------------------------------------------- /BE/main.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | -------------------------------------------------------------------------------- /BE/models.py: -------------------------------------------------------------------------------- 1 | from app import db 2 | from passlib.hash import pbkdf2_sha256 as sha256 3 | from sqlalchemy import func, desc 4 | 5 | """ 6 | I think all the names of the functions are self-explaining 7 | but I'll try to write what it does 8 | Future me you're welcome ;) 9 | """ 10 | 11 | class UserModel(db.Model): 12 | __tablename__ = 'users' 13 | 14 | id = db.Column(db.Integer, primary_key = True) 15 | username = db.Column(db.String(120), unique = True, nullable = False) 16 | password = db.Column(db.String(120), nullable = False) 17 | 18 | def save_to_db(self): 19 | db.session.add(self) 20 | db.session.commit() 21 | 22 | @classmethod 23 | def update_pw(cls, username, pw_hash): 24 | """ 25 | Updates password of supplied user 26 | """ 27 | user = cls.query.filter_by(username = username).first() 28 | user.password = pw_hash 29 | return db.session.commit() 30 | 31 | @classmethod 32 | def find_by_username(cls, username): 33 | """ 34 | Returns username, id, password (hash) 35 | of supplied user 36 | """ 37 | return cls.query.filter_by(username = username).first() 38 | 39 | @staticmethod 40 | def generate_hash(password): 41 | """ 42 | I don't know what to write here 43 | """ 44 | return sha256.hash(password) 45 | 46 | @staticmethod 47 | def verify_hash(password, hash): 48 | """ 49 | And here too :( 50 | """ 51 | return sha256.verify(password, hash) 52 | 53 | @classmethod 54 | def delete_user(cls, username): 55 | """ 56 | Deletes the user 57 | How unexpected :O 58 | """ 59 | x = cls.query.filter_by(username = username).delete() 60 | db.session.commit() 61 | return x 62 | 63 | class RevokedTokenModel(db.Model): 64 | __tablename__ = 'revoked_tokens' 65 | id = db.Column(db.Integer, primary_key = True) 66 | jti = db.Column(db.String(120)) 67 | 68 | def add(self): 69 | db.session.add(self) 70 | db.session.commit() 71 | 72 | @classmethod 73 | def is_jti_blacklisted(cls, jti): 74 | """ 75 | blacklist supplied jti token (used on logout) 76 | """ 77 | query = cls.query.filter_by(jti = jti).first() 78 | return bool(query) 79 | 80 | 81 | class DnsModel(db.Model): 82 | __tablename__ = 'dns_tokens' 83 | 84 | id = db.Column(db.Integer, primary_key = True) 85 | username = db.Column(db.String(120), unique = False, nullable = False) 86 | uuid = db.Column(db.String(120), unique = True, nullable = False) 87 | props = db.Column(db.String(2056), unique = False, nullable = False) 88 | name = db.Column(db.String(120), unique = False, nullable = False) 89 | 90 | def save_to_db(self): 91 | db.session.add(self) 92 | db.session.commit() 93 | 94 | @classmethod 95 | def delete_by_user(cls, username): 96 | """ 97 | Deltes every uuid owned by specified user 98 | """ 99 | x = cls.query.filter_by(username = username).delete() 100 | db.session.commit() 101 | return {'deleted': x} 102 | 103 | @classmethod 104 | def delete_by_uuid(cls, uuid, username): 105 | """ 106 | Deletes supplied UUID 107 | """ 108 | x = cls.query.filter_by(uuid = uuid, username = username).delete() 109 | db.session.commit() 110 | success = True if x == 1 else False 111 | return {'success': success} 112 | 113 | @classmethod 114 | def find_by_uuid(cls, uuid): 115 | """ 116 | Used in dns_resources to check if uuid exists 117 | """ 118 | return cls.query.filter_by(uuid = uuid).first() 119 | 120 | @classmethod 121 | def find_by_user(cls, username): 122 | """ 123 | Returns list all tokens that belong to supplied username 124 | """ 125 | def to_json(x): 126 | return {'uuid': x.uuid, 'name': x.name} 127 | return list(map(lambda x: to_json(x), cls.query.filter_by(username = username))) 128 | 129 | @classmethod 130 | def get_props(cls, uuid, username): 131 | """ 132 | Get properties of token (what it should resolve to, stuff like that...) 133 | """ 134 | def to_json(x): 135 | return { 136 | 'props': x.props, 137 | 'name': x.name 138 | } 139 | try: 140 | return list(map(lambda x: to_json(x), cls.query.filter_by(uuid = uuid, username = username)))[0] 141 | except: 142 | return False 143 | 144 | class LogModel(db.Model): 145 | __tablename__ = 'dns_logs' 146 | 147 | id = db.Column(db.Integer, primary_key = True) 148 | uuid = db.Column(db.String(64), unique = False, nullable = False) 149 | resolved_to = db.Column(db.String(253), unique = False, nullable = False) 150 | domain = db.Column(db.String(253), unique = False, nullable = False) 151 | ip = db.Column(db.String(253), unique = False, nullable = False) 152 | port = db.Column(db.String(32), unique = False, nullable = False) 153 | created_date = db.Column(db.String(128), unique = False, nullable = False) 154 | 155 | @classmethod 156 | def statistics_count(cls, username): 157 | """ 158 | Returns statistics for user :O 159 | """ 160 | def get_count(q): 161 | """ 162 | Used for counting rows because SQLAlchemys count is slow af 163 | """ 164 | count_q = q.statement.with_only_columns([func.count()]).order_by(None) 165 | count = q.session.execute(count_q).scalar() 166 | return count 167 | uuids = [x['uuid'] for x in DnsModel.find_by_user(username)] 168 | req_count = 0 169 | 170 | for uuid in uuids: 171 | req_count += get_count(cls.query.filter_by(uuid = uuid)) 172 | 173 | return {'request_count': req_count, 'created_bins': len(uuids)} 174 | 175 | @classmethod 176 | def req_count(cls, uuid): 177 | """ 178 | Returns statistics for user :O 179 | """ 180 | def get_count(q): 181 | """ 182 | Used for counting rows because SQLAlchemys count is slow af 183 | """ 184 | count_q = q.statement.with_only_columns([func.count()]).order_by(None) 185 | count = q.session.execute(count_q).scalar() 186 | return count 187 | 188 | req_count = get_count(cls.query.filter_by(uuid = uuid)) 189 | 190 | return req_count 191 | 192 | @classmethod 193 | def uuid_logs(cls, uuid, username, per_page=10, page=1): 194 | """ 195 | Returns list of All the logs of supplied uuid 196 | I have to implement pagination for this 197 | because nobody wants to wait for eternity for 83298392 entries served over web api 198 | """ 199 | def to_json(x): 200 | return { 201 | 'uuid': x.uuid, 202 | 'resolved_to': x.resolved_to, 203 | 'domain': x.domain, 204 | 'origin_ip': x.ip, 205 | 'port': x.port, 206 | 'created_date': x.created_date 207 | } 208 | if uuid in [y['uuid'] for y in DnsModel.find_by_user(username)]: 209 | uuid_query = cls.query.filter_by(uuid = uuid).order_by(cls.created_date.desc()).paginate(page,per_page,error_out=False) 210 | return (uuid_query.total,uuid_query.pages, list(map(lambda x: to_json(x), uuid_query.items))) 211 | else: 212 | return ("?",0,[]) 213 | 214 | @classmethod 215 | def return_all(cls, username): 216 | """ 217 | Returns *ALL* of tokens that belong to supplied user 218 | I'm probably not gonna use this function 219 | """ 220 | def to_json(x): 221 | return { 222 | 'uuid': x.uuid, 223 | 'resolved_to': x.resolved_to, 224 | 'domain': x.domain, 225 | 'origin_ip': x.ip, 226 | 'port': x.port, 227 | 'created_date': x.created_date 228 | } 229 | uuids = [y['uuid'] for y in DnsModel.find_by_user(username)] 230 | uuid_list = [] 231 | for uuid in uuids: 232 | uuid_list += list(map(lambda x: to_json(x), cls.query.filter_by(uuid = uuid))) 233 | 234 | return uuid_list 235 | 236 | @classmethod 237 | def delete_by_uuid(cls, uuid, username): 238 | """ 239 | Deletes supplied UUID 240 | """ 241 | x = 0 242 | uuids = [y['uuid'] for y in DnsModel.find_by_user(username)] 243 | 244 | if uuid in uuids: 245 | x = cls.query.filter_by(uuid = uuid).delete() 246 | db.session.commit() 247 | 248 | return {'deleted': x} 249 | 250 | @classmethod 251 | def delete_by_user(cls, username): 252 | """ 253 | Deletes all logs of supplied user 254 | """ 255 | uuids = [x['uuid'] for x in DnsModel.find_by_user(username)] 256 | 257 | total_deleted = 0 258 | for cc in uuids: 259 | a = cls.query.filter_by(uuid = cc).delete() 260 | db.session.commit() 261 | total_deleted += a 262 | 263 | return {'deleted': total_deleted} 264 | -------------------------------------------------------------------------------- /BE/requirements.txt: -------------------------------------------------------------------------------- 1 | dnslib 2 | validators 3 | redis 4 | jsonschema 5 | uuid 6 | flask_jwt_extended==3.25.1 7 | flask_restful 8 | datetime 9 | passlib 10 | sqlalchemy 11 | flask_cors 12 | dnslib 13 | Flask-SQLAlchemy 14 | psycopg2-binary 15 | redis 16 | flask==1.1.4 17 | MarkupSafe==2.0.1 18 | -------------------------------------------------------------------------------- /BE/resources.py: -------------------------------------------------------------------------------- 1 | from flask_restful import Resource, reqparse 2 | from flask_jwt_extended import (create_access_token, create_refresh_token, jwt_required, jwt_refresh_token_required, get_jwt_identity, get_raw_jwt) 3 | 4 | 5 | from models import UserModel, RevokedTokenModel 6 | 7 | class UserRegistration(Resource): 8 | def post(self): 9 | parser = reqparse.RequestParser() 10 | parser.add_argument('username', help = 'This field cannot be blank', required = True) 11 | parser.add_argument('password', help = 'This field cannot be blank', required = True) 12 | data = parser.parse_args() 13 | 14 | if UserModel.find_by_username(data['username']): 15 | return {'message': 'User already exists', 'error': True}, 500 16 | elif len(data['password']) <= 7: 17 | return {'message': 'Password has to be at least 8 chars long', 'error': True}, 500 18 | new_user = UserModel( 19 | username = data['username'], 20 | password = UserModel.generate_hash(data['password']) 21 | ) 22 | 23 | try: 24 | new_user.save_to_db() 25 | access_token = create_access_token(identity = data['username']) 26 | #refresh_token = create_refresh_token(identity = data['username']) 27 | return { 28 | 'name': data['username'], 29 | 'access_token': access_token, 30 | #'refresh_token': refresh_token 31 | } 32 | except: 33 | return {'message': 'Something went wrong', 'error': True}, 500 34 | 35 | 36 | class UserLogin(Resource): 37 | def post(self): 38 | parser = reqparse.RequestParser() 39 | parser.add_argument('username', help = 'This field cannot be blank', required = True) 40 | parser.add_argument('password', help = 'This field cannot be blank', required = True) 41 | data = parser.parse_args() 42 | current_user = UserModel.find_by_username(data['username']) 43 | 44 | if not current_user: 45 | return {'message': 'Wrong credentials','error': True}, 500 46 | 47 | if UserModel.verify_hash(data['password'], current_user.password): 48 | access_token = create_access_token(identity = data['username']) 49 | #refresh_token = create_refresh_token(identity = data['username']) 50 | return { 51 | 'name': current_user.username, 52 | 'access_token': access_token, 53 | #'refresh_token': refresh_token 54 | } 55 | else: 56 | return {'message': 'Wrong credentials', 'error': True}, 500 57 | 58 | 59 | class UserLogoutAccess(Resource): 60 | @jwt_required 61 | def post(self): 62 | jti = get_raw_jwt()['jti'] 63 | try: 64 | revoked_token = RevokedTokenModel(jti = jti) 65 | revoked_token.add() 66 | return {'message': 'Access token has been revoked'} 67 | except: 68 | return {'message': 'Something went wrong', 'error': True} 69 | 70 | class UserName(Resource): 71 | @jwt_required 72 | def get(self): 73 | return {"name": get_jwt_identity()} 74 | 75 | class ChangePw(Resource): 76 | @jwt_required 77 | def post(self): 78 | parser = reqparse.RequestParser() 79 | parser.add_argument('old_password', help = 'This field cannot be blank', required = True) 80 | parser.add_argument('new_password', help = 'This field cannot be blank', required = True) 81 | data = parser.parse_args() 82 | user = UserModel.find_by_username(get_jwt_identity()) 83 | if len(data['new_password']) <= 7: 84 | return {'message': 'Password has to be at least 8 chars long', 'success': False} 85 | elif UserModel.verify_hash(data['old_password'], user.password): 86 | try: 87 | UserModel.update_pw(user.username, UserModel.generate_hash(data['new_password'])) 88 | return {'success': True} 89 | except: 90 | return {'success': False, 'message': 'Something went wrong'} 91 | else: 92 | return {'message': 'Wrong password', 'success': False} 93 | 94 | # class UserLogoutRefresh(Resource): 95 | # @jwt_refresh_token_required 96 | # def post(self): 97 | # jti = get_raw_jwt()['jti'] 98 | # try: 99 | # revoked_token = RevokedTokenModel(jti = jti) 100 | # revoked_token.add() 101 | # return {'message': 'Refresh token has been revoked'} 102 | # except: 103 | # return {'message': 'Something went wrong', 'error': True}, 500 104 | # 105 | # 106 | # class TokenRefresh(Resource): 107 | # @jwt_refresh_token_required 108 | # def post(self): 109 | # current_user = get_jwt_identity() 110 | # access_token = create_access_token(identity = current_user) 111 | # return {'access_token': access_token} 112 | # 113 | -------------------------------------------------------------------------------- /BE/uwsgi.ini: -------------------------------------------------------------------------------- 1 | [uwsgi] 2 | module = main:app 3 | 4 | master = true 5 | processes = 5 6 | 7 | socket = myproject.sock 8 | chmod-socket = 660 9 | vacuum = true 10 | 11 | die-on-term = true 12 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html) (at least tries to). 7 | 8 | ## [2.0.1] - 30. July 2020 9 | 10 | ### Added 11 | 12 | - FE 13 | - .env.production and .env.development for easier configuration 14 | 15 | ### Changed 16 | 17 | - FE 18 | - Updated node modules + fix newly-born not-working code 19 | - Deleted buggy/unnecessary "Create new bin" button from dashboard 20 | 21 | - API 22 | - fixed pagination of logs - now sorting by time! 23 | - uWsgi files 24 | 25 | ## [2.0.0] - 6. April 2020 26 | 27 | ### Added 28 | 29 | - Config 30 | - config is now loaded from config.yaml in root of project 31 | 32 | - DNS 33 | - CNAME and AAAA records are now supported! 34 | - Multithreading on DNS server 35 | - TCP is now supported too 36 | - In config.yaml you can set `domain` for which the dns server will work 37 | - Ability to set `use_failure_ip` in config.yaml to false -> dns server returns nxdomain if queried bin doesn't exist 38 | - Ability to set `use_fail_ns` to true -> so when somebody request domain that is not 'gel0.space' or whatever you set, dns server can return ns record with specified ip 39 | 40 | - Settings panel 41 | - Delete all data functionality 42 | - Change password functionality 43 | - Copy JWT token button 44 | 45 | - In `/mybins` 46 | - A brief overview of rebinding flow 47 | - Copy domain name button 48 | - Delete bin button 49 | - Pagination 50 | 51 | - In `/dnsbin` 52 | - Support for CNAME and AAAA 53 | - "4ever" can be supplied to the repeat field now 54 | - When submitted there is functionality to copy generated subdomain 55 | 56 | - "Support me" page ❤️ - If you get a huuuuge bounty using my tool why not donate few bucks 57 | 58 | - Bottom bar buttons 59 | - Star project on github 60 | - Contact me 61 | - About me 62 | - Support me 63 | 64 | - Added basic (and buggy) app vulnerable to TOCTOU/DNS rebinding ssrf so you can try it at home :D 65 | 66 | ### Changed 67 | - D4RK mode is here and it's permanent (for now) 68 | - true 1337 h4xx0rs don't need light mode anyways 69 | 70 | - DNS 71 | - DNS server now runs in [dnslib](https://pypi.org/project/dnslib/) 72 | 73 | - Login 74 | - Weird bug where you were logged but actually weren't should be fixed now 75 | 76 | - API 77 | - json inputs are now validated with [jsonschema](https://pypi.org/project/jsonschema/) 78 | -------------------------------------------------------------------------------- /FE/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/makuga01/dnsFookup/43fbeacfa0d16746267e5c773f7dab66229c400a/FE/.DS_Store -------------------------------------------------------------------------------- /FE/.env.development: -------------------------------------------------------------------------------- 1 | REACT_APP_API="http://localhost:5000" 2 | REACT_APP_REBIND_DOMAIN="gel0.space" 3 | -------------------------------------------------------------------------------- /FE/.env.production: -------------------------------------------------------------------------------- 1 | REACT_APP_API="http://35.246.199.28:5000" 2 | REACT_APP_REBIND_DOMAIN="gel0.space" 3 | -------------------------------------------------------------------------------- /FE/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app). 2 | 3 | Below you will find some information on how to perform common tasks.
4 | You can find the most recent version of this guide [here](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md). 5 | 6 | ## Table of Contents 7 | 8 | - [Updating to New Releases](#updating-to-new-releases) 9 | - [Sending Feedback](#sending-feedback) 10 | - [Folder Structure](#folder-structure) 11 | - [Available Scripts](#available-scripts) 12 | - [npm start](#npm-start) 13 | - [npm test](#npm-test) 14 | - [npm run build](#npm-run-build) 15 | - [npm run eject](#npm-run-eject) 16 | - [Supported Language Features and Polyfills](#supported-language-features-and-polyfills) 17 | - [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor) 18 | - [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor) 19 | - [Debugging in the Editor](#debugging-in-the-editor) 20 | - [Changing the Page ``](#changing-the-page-title) 21 | - [Installing a Dependency](#installing-a-dependency) 22 | - [Importing a Component](#importing-a-component) 23 | - [Adding a Stylesheet](#adding-a-stylesheet) 24 | - [Post-Processing CSS](#post-processing-css) 25 | - [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc) 26 | - [Adding Images and Fonts](#adding-images-and-fonts) 27 | - [Using the `public` Folder](#using-the-public-folder) 28 | - [Changing the HTML](#changing-the-html) 29 | - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system) 30 | - [When to Use the `public` Folder](#when-to-use-the-public-folder) 31 | - [Using Global Variables](#using-global-variables) 32 | - [Adding Bootstrap](#adding-bootstrap) 33 | - [Using a Custom Theme](#using-a-custom-theme) 34 | - [Adding Flow](#adding-flow) 35 | - [Adding Custom Environment Variables](#adding-custom-environment-variables) 36 | - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html) 37 | - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell) 38 | - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env) 39 | - [Can I Use Decorators?](#can-i-use-decorators) 40 | - [Integrating with an API Backend](#integrating-with-an-api-backend) 41 | - [Node](#node) 42 | - [Ruby on Rails](#ruby-on-rails) 43 | - [Proxying API Requests in Development](#proxying-api-requests-in-development) 44 | - [Using HTTPS in Development](#using-https-in-development) 45 | - [Generating Dynamic `<meta>` Tags on the Server](#generating-dynamic-meta-tags-on-the-server) 46 | - [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files) 47 | - [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page) 48 | - [Running Tests](#running-tests) 49 | - [Filename Conventions](#filename-conventions) 50 | - [Command Line Interface](#command-line-interface) 51 | - [Version Control Integration](#version-control-integration) 52 | - [Writing Tests](#writing-tests) 53 | - [Testing Components](#testing-components) 54 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries) 55 | - [Initializing Test Environment](#initializing-test-environment) 56 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests) 57 | - [Coverage Reporting](#coverage-reporting) 58 | - [Continuous Integration](#continuous-integration) 59 | - [Disabling jsdom](#disabling-jsdom) 60 | - [Snapshot Testing](#snapshot-testing) 61 | - [Editor Integration](#editor-integration) 62 | - [Developing Components in Isolation](#developing-components-in-isolation) 63 | - [Making a Progressive Web App](#making-a-progressive-web-app) 64 | - [Deployment](#deployment) 65 | - [Static Server](#static-server) 66 | - [Other Solutions](#other-solutions) 67 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing) 68 | - [Building for Relative Paths](#building-for-relative-paths) 69 | - [Azure](#azure) 70 | - [Firebase](#firebase) 71 | - [GitHub Pages](#github-pages) 72 | - [Heroku](#heroku) 73 | - [Modulus](#modulus) 74 | - [Netlify](#netlify) 75 | - [Now](#now) 76 | - [S3 and CloudFront](#s3-and-cloudfront) 77 | - [Surge](#surge) 78 | - [Advanced Configuration](#advanced-configuration) 79 | - [Troubleshooting](#troubleshooting) 80 | - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes) 81 | - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra) 82 | - [`npm run build` silently fails](#npm-run-build-silently-fails) 83 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku) 84 | - [Something Missing?](#something-missing) 85 | 86 | ## Updating to New Releases 87 | 88 | Create React App is divided into two packages: 89 | 90 | * `create-react-app` is a global command-line utility that you use to create new projects. 91 | * `react-scripts` is a development dependency in the generated projects (including this one). 92 | 93 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`. 94 | 95 | When you run `create-react-app`, it always creates the project with the latest version of `react-scripts` so you’ll get all the new features and improvements in newly created apps automatically. 96 | 97 | To update an existing project to a new version of `react-scripts`, [open the changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md), find the version you’re currently on (check `package.json` in this folder if you’re not sure), and apply the migration instructions for the newer versions. 98 | 99 | In most cases bumping the `react-scripts` version in `package.json` and running `npm install` in this folder should be enough, but it’s good to consult the [changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes. 100 | 101 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly. 102 | 103 | ## Sending Feedback 104 | 105 | We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues). 106 | 107 | ## Folder Structure 108 | 109 | After creation, your project should look like this: 110 | 111 | ``` 112 | my-app/ 113 | README.md 114 | node_modules/ 115 | package.json 116 | public/ 117 | index.html 118 | favicon.ico 119 | src/ 120 | App.css 121 | App.js 122 | App.test.js 123 | index.css 124 | index.js 125 | logo.svg 126 | ``` 127 | 128 | For the project to build, **these files must exist with exact filenames**: 129 | 130 | * `public/index.html` is the page template; 131 | * `src/index.js` is the JavaScript entry point. 132 | 133 | You can delete or rename the other files. 134 | 135 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.<br> 136 | You need to **put any JS and CSS files inside `src`**, or Webpack won’t see them. 137 | 138 | Only files inside `public` can be used from `public/index.html`.<br> 139 | Read instructions below for using assets from JavaScript and HTML. 140 | 141 | You can, however, create more top-level directories.<br> 142 | They will not be included in the production build so you can use them for things like documentation. 143 | 144 | ## Available Scripts 145 | 146 | In the project directory, you can run: 147 | 148 | ### `npm start` 149 | 150 | Runs the app in the development mode.<br> 151 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 152 | 153 | The page will reload if you make edits.<br> 154 | You will also see any lint errors in the console. 155 | 156 | ### `npm test` 157 | 158 | Launches the test runner in the interactive watch mode.<br> 159 | See the section about [running tests](#running-tests) for more information. 160 | 161 | ### `npm run build` 162 | 163 | Builds the app for production to the `build` folder.<br> 164 | It correctly bundles React in production mode and optimizes the build for the best performance. 165 | 166 | The build is minified and the filenames include the hashes.<br> 167 | Your app is ready to be deployed! 168 | 169 | See the section about [deployment](#deployment) for more information. 170 | 171 | ### `npm run eject` 172 | 173 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 174 | 175 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 176 | 177 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 178 | 179 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 180 | 181 | ## Supported Language Features and Polyfills 182 | 183 | This project supports a superset of the latest JavaScript standard.<br> 184 | In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports: 185 | 186 | * [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016). 187 | * [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017). 188 | * [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal). 189 | * [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (stage 2 proposal). 190 | * [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax. 191 | 192 | Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-). 193 | 194 | While we recommend to use experimental proposals with some caution, Facebook heavily uses these features in the product code, so we intend to provide [codemods](https://medium.com/@cpojer/effective-javascript-codemods-5a6686bb46fb) if any of these proposals change in the future. 195 | 196 | Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**: 197 | 198 | * [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign). 199 | * [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise). 200 | * [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch). 201 | 202 | If you use any other ES6+ features that need **runtime support** (such as `Array.from()` or `Symbol`), make sure you are including the appropriate polyfills manually, or that the browsers you are targeting already support them. 203 | 204 | ## Syntax Highlighting in the Editor 205 | 206 | To configure the syntax highlighting in your favorite text editor, head to the [relevant Babel documentation page](https://babeljs.io/docs/editors) and follow the instructions. Some of the most popular editors are covered. 207 | 208 | ## Displaying Lint Output in the Editor 209 | 210 | >Note: this feature is available with `react-scripts@0.2.0` and higher. 211 | 212 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint. 213 | 214 | They are not required for linting. You should see the linter output right in your terminal as well as the browser console. However, if you prefer the lint results to appear right in your editor, there are some extra steps you can do. 215 | 216 | You would need to install an ESLint plugin for your editor first. 217 | 218 | >**A note for Atom `linter-eslint` users** 219 | 220 | >If you are using the Atom `linter-eslint` plugin, make sure that **Use global ESLint installation** option is checked: 221 | 222 | ><img src="http://i.imgur.com/yVNNHJM.png" width="300"> 223 | 224 | 225 | >**For Visual Studio Code users** 226 | 227 | >VS Code ESLint plugin automatically detects Create React App's configuration file. So you do not need to create `eslintrc.json` at the root directory, except when you want to add your own rules. In that case, you should include CRA's config by adding this line: 228 | 229 | >```js 230 | { 231 | // ... 232 | "extends": "react-app" 233 | } 234 | ``` 235 | 236 | Then add this block to the `package.json` file of your project: 237 | 238 | ```js 239 | { 240 | // ... 241 | "eslintConfig": { 242 | "extends": "react-app" 243 | } 244 | } 245 | ``` 246 | 247 | Finally, you will need to install some packages *globally*: 248 | 249 | ```sh 250 | npm install -g eslint-config-react-app@0.3.0 eslint@3.8.1 babel-eslint@7.0.0 eslint-plugin-react@6.4.1 eslint-plugin-import@2.0.1 eslint-plugin-jsx-a11y@4.0.0 eslint-plugin-flowtype@2.21.0 251 | ``` 252 | 253 | We recognize that this is suboptimal, but it is currently required due to the way we hide the ESLint dependency. The ESLint team is already [working on a solution to this](https://github.com/eslint/eslint/issues/3458) so this may become unnecessary in a couple of months. 254 | 255 | ## Debugging in the Editor 256 | 257 | **This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) editor.** 258 | 259 | Visual Studio Code supports live-editing and debugging out of the box with Create React App. This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools. 260 | 261 | You would need to have the latest version of [VS Code](https://code.visualstudio.com) and VS Code [Chrome Debugger Extension](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) installed. 262 | 263 | Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory. 264 | 265 | ```json 266 | { 267 | "version": "0.2.0", 268 | "configurations": [{ 269 | "name": "Chrome", 270 | "type": "chrome", 271 | "request": "launch", 272 | "url": "http://localhost:3000", 273 | "webRoot": "${workspaceRoot}/src", 274 | "userDataDir": "${workspaceRoot}/.vscode/chrome", 275 | "sourceMapPathOverrides": { 276 | "webpack:///src/*": "${webRoot}/*" 277 | } 278 | }] 279 | } 280 | ``` 281 | 282 | Start your app by running `npm start`, and start debugging in VS Code by pressing `F5` or by clicking the green debug icon. You can now write code, set breakpoints, make changes to the code, and debug your newly modified code—all from your editor. 283 | 284 | ## Changing the Page `<title>` 285 | 286 | You can find the source HTML file in the `public` folder of the generated project. You may edit the `<title>` tag in it to change the title from “React App” to anything else. 287 | 288 | Note that normally you wouldn’t edit files in the `public` folder very often. For example, [adding a stylesheet](#adding-a-stylesheet) is done without touching the HTML. 289 | 290 | If you need to dynamically update the page title based on the content, you can use the browser [`document.title`](https://developer.mozilla.org/en-US/docs/Web/API/Document/title) API. For more complex scenarios when you want to change the title from React components, you can use [React Helmet](https://github.com/nfl/react-helmet), a third party library. 291 | 292 | If you use a custom server for your app in production and want to modify the title before it gets sent to the browser, you can follow advice in [this section](#generating-dynamic-meta-tags-on-the-server). Alternatively, you can pre-build each page as a static HTML file which then loads the JavaScript bundle, which is covered [here](#pre-rendering-into-static-html-files). 293 | 294 | ## Installing a Dependency 295 | 296 | The generated project includes React and ReactDOM as dependencies. It also includes a set of scripts used by Create React App as a development dependency. You may install other dependencies (for example, React Router) with `npm`: 297 | 298 | ``` 299 | npm install --save <library-name> 300 | ``` 301 | 302 | ## Importing a Component 303 | 304 | This project setup supports ES6 modules thanks to Babel.<br> 305 | While you can still use `require()` and `module.exports`, we encourage you to use [`import` and `export`](http://exploringjs.com/es6/ch_modules.html) instead. 306 | 307 | For example: 308 | 309 | ### `Button.js` 310 | 311 | ```js 312 | import React, { Component } from 'react'; 313 | 314 | class Button extends Component { 315 | render() { 316 | // ... 317 | } 318 | } 319 | 320 | export default Button; // Don’t forget to use export default! 321 | ``` 322 | 323 | ### `DangerButton.js` 324 | 325 | 326 | ```js 327 | import React, { Component } from 'react'; 328 | import Button from './Button'; // Import a component from another file 329 | 330 | class DangerButton extends Component { 331 | render() { 332 | return <Button color="red" />; 333 | } 334 | } 335 | 336 | export default DangerButton; 337 | ``` 338 | 339 | Be aware of the [difference between default and named exports](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281). It is a common source of mistakes. 340 | 341 | We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use `export default Button` and `import Button from './Button'`. 342 | 343 | Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like. 344 | 345 | Learn more about ES6 modules: 346 | 347 | * [When to use the curly braces?](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281) 348 | * [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html) 349 | * [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules) 350 | 351 | ## Adding a Stylesheet 352 | 353 | This project setup uses [Webpack](https://webpack.github.io/) for handling all assets. Webpack offers a custom way of “extending” the concept of `import` beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to **import the CSS from the JavaScript file**: 354 | 355 | ### `Button.css` 356 | 357 | ```css 358 | .Button { 359 | padding: 20px; 360 | } 361 | ``` 362 | 363 | ### `Button.js` 364 | 365 | ```js 366 | import React, { Component } from 'react'; 367 | import './Button.css'; // Tell Webpack that Button.js uses these styles 368 | 369 | class Button extends Component { 370 | render() { 371 | // You can use them as regular CSS styles 372 | return <div className="Button" />; 373 | } 374 | } 375 | ``` 376 | 377 | **This is not required for React** but many people find this feature convenient. You can read about the benefits of this approach [here](https://medium.com/seek-ui-engineering/block-element-modifying-your-javascript-components-d7f99fcab52b). However you should be aware that this makes your code less portable to other build tools and environments than Webpack. 378 | 379 | In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified `.css` file in the build output. 380 | 381 | If you are concerned about using Webpack-specific semantics, you can put all your CSS right into `src/index.css`. It would still be imported from `src/index.js`, but you could always remove that import if you later migrate to a different build tool. 382 | 383 | ## Post-Processing CSS 384 | 385 | This project setup minifies your CSS and adds vendor prefixes to it automatically through [Autoprefixer](https://github.com/postcss/autoprefixer) so you don’t need to worry about it. 386 | 387 | For example, this: 388 | 389 | ```css 390 | .App { 391 | display: flex; 392 | flex-direction: row; 393 | align-items: center; 394 | } 395 | ``` 396 | 397 | becomes this: 398 | 399 | ```css 400 | .App { 401 | display: -webkit-box; 402 | display: -ms-flexbox; 403 | display: flex; 404 | -webkit-box-orient: horizontal; 405 | -webkit-box-direction: normal; 406 | -ms-flex-direction: row; 407 | flex-direction: row; 408 | -webkit-box-align: center; 409 | -ms-flex-align: center; 410 | align-items: center; 411 | } 412 | ``` 413 | 414 | If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling). 415 | 416 | ## Adding a CSS Preprocessor (Sass, Less etc.) 417 | 418 | Generally, we recommend that you don’t reuse the same CSS classes across different components. For example, instead of using a `.Button` CSS class in `<AcceptButton>` and `<RejectButton>` components, we recommend creating a `<Button>` component with its own `.Button` styles, that both `<AcceptButton>` and `<RejectButton>` can render (but [not inherit](https://facebook.github.io/react/docs/composition-vs-inheritance.html)). 419 | 420 | Following this rule often makes CSS preprocessors less useful, as features like mixins and nesting are replaced by component composition. You can, however, integrate a CSS preprocessor if you find it valuable. In this walkthrough, we will be using Sass, but you can also use Less, or another alternative. 421 | 422 | First, let’s install the command-line interface for Sass: 423 | 424 | ``` 425 | npm install node-sass --save-dev 426 | ``` 427 | 428 | Then in `package.json`, add the following lines to `scripts`: 429 | 430 | ```diff 431 | "scripts": { 432 | + "build-css": "node-sass src/ -o src/", 433 | + "watch-css": "npm run build-css && node-sass src/ -o src/ --watch --recursive", 434 | "start": "react-scripts start", 435 | "build": "react-scripts build", 436 | "test": "react-scripts test --env=jsdom", 437 | ``` 438 | 439 | >Note: To use a different preprocessor, replace `build-css` and `watch-css` commands according to your preprocessor’s documentation. 440 | 441 | Now you can rename `src/App.css` to `src/App.scss` and run `npm run watch-css`. The watcher will find every Sass file in `src` subdirectories, and create a corresponding CSS file next to it, in our case overwriting `src/App.css`. Since `src/App.js` still imports `src/App.css`, the styles become a part of your application. You can now edit `src/App.scss`, and `src/App.css` will be regenerated. 442 | 443 | To share variables between Sass files, you can use Sass imports. For example, `src/App.scss` and other component style files could include `@import "./shared.scss";` with variable definitions. 444 | 445 | At this point you might want to remove all CSS files from the source control, and add `src/**/*.css` to your `.gitignore` file. It is generally a good practice to keep the build products outside of the source control. 446 | 447 | As a final step, you may find it convenient to run `watch-css` automatically with `npm start`, and run `build-css` as a part of `npm run build`. You can use the `&&` operator to execute two scripts sequentially. However, there is no cross-platform way to run two scripts in parallel, so we will install a package for this: 448 | 449 | ``` 450 | npm install --save-dev npm-run-all 451 | ``` 452 | 453 | Then we can change `start` and `build` scripts to include the CSS preprocessor commands: 454 | 455 | ```diff 456 | "scripts": { 457 | "build-css": "node-sass src/ -o src/", 458 | "watch-css": "npm run build-css && node-sass src/ -o src/ --watch --recursive", 459 | - "start": "react-scripts start", 460 | - "build": "react-scripts build", 461 | + "start-js": "react-scripts start", 462 | + "start": "npm-run-all -p watch-css start-js", 463 | + "build": "npm run build-css && react-scripts build", 464 | "test": "react-scripts test --env=jsdom", 465 | "eject": "react-scripts eject" 466 | } 467 | ``` 468 | 469 | Now running `npm start` and `npm run build` also builds Sass files. Note that `node-sass` seems to have an [issue recognizing newly created files on some systems](https://github.com/sass/node-sass/issues/1891) so you might need to restart the watcher when you create a file until it’s resolved. 470 | 471 | ## Adding Images and Fonts 472 | 473 | With Webpack, using static assets like images and fonts works similarly to CSS. 474 | 475 | You can **`import` an image right in a JavaScript module**. This tells Webpack to include that image in the bundle. Unlike CSS imports, importing an image or a font gives you a string value. This value is the final image path you can reference in your code. 476 | 477 | Here is an example: 478 | 479 | ```js 480 | import React from 'react'; 481 | import logo from './logo.png'; // Tell Webpack this JS file uses this image 482 | 483 | console.log(logo); // /logo.84287d09.png 484 | 485 | function Header() { 486 | // Import result is the URL of your image 487 | return <img src={logo} alt="Logo" />; 488 | } 489 | 490 | export default Header; 491 | ``` 492 | 493 | This ensures that when the project is built, Webpack will correctly move the images into the build folder, and provide us with correct paths. 494 | 495 | This works in CSS too: 496 | 497 | ```css 498 | .Logo { 499 | background-image: url(./logo.png); 500 | } 501 | ``` 502 | 503 | Webpack finds all relative module references in CSS (they start with `./`) and replaces them with the final paths from the compiled bundle. If you make a typo or accidentally delete an important file, you will see a compilation error, just like when you import a non-existent JavaScript module. The final filenames in the compiled bundle are generated by Webpack from content hashes. If the file content changes in the future, Webpack will give it a different name in production so you don’t need to worry about long-term caching of assets. 504 | 505 | Please be advised that this is also a custom feature of Webpack. 506 | 507 | **It is not required for React** but many people enjoy it (and React Native uses a similar mechanism for images).<br> 508 | An alternative way of handling static assets is described in the next section. 509 | 510 | ## Using the `public` Folder 511 | 512 | >Note: this feature is available with `react-scripts@0.5.0` and higher. 513 | 514 | ### Changing the HTML 515 | 516 | The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title). 517 | The `<script>` tag with the compiled code will be added to it automatically during the build process. 518 | 519 | ### Adding Assets Outside of the Module System 520 | 521 | You can also add other assets to the `public` folder. 522 | 523 | Note that we normally encourage you to `import` assets in JavaScript files instead. 524 | For example, see the sections on [adding a stylesheet](#adding-a-stylesheet) and [adding images and fonts](#adding-images-and-fonts). 525 | This mechanism provides a number of benefits: 526 | 527 | * Scripts and stylesheets get minified and bundled together to avoid extra network requests. 528 | * Missing files cause compilation errors instead of 404 errors for your users. 529 | * Result filenames include content hashes so you don’t need to worry about browsers caching their old versions. 530 | 531 | However there is an **escape hatch** that you can use to add an asset outside of the module system. 532 | 533 | If you put a file into the `public` folder, it will **not** be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the `public` folder, you need to use a special variable called `PUBLIC_URL`. 534 | 535 | Inside `index.html`, you can use it like this: 536 | 537 | ```html 538 | <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> 539 | ``` 540 | 541 | Only files inside the `public` folder will be accessible by `%PUBLIC_URL%` prefix. If you need to use a file from `src` or `node_modules`, you’ll have to copy it there to explicitly specify your intention to make this file a part of the build. 542 | 543 | When you run `npm run build`, Create React App will substitute `%PUBLIC_URL%` with a correct absolute path so your project works even if you use client-side routing or host it at a non-root URL. 544 | 545 | In JavaScript code, you can use `process.env.PUBLIC_URL` for similar purposes: 546 | 547 | ```js 548 | render() { 549 | // Note: this is an escape hatch and should be used sparingly! 550 | // Normally we recommend using `import` for getting asset URLs 551 | // as described in “Adding Images and Fonts” above this section. 552 | return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />; 553 | } 554 | ``` 555 | 556 | Keep in mind the downsides of this approach: 557 | 558 | * None of the files in `public` folder get post-processed or minified. 559 | * Missing files will not be called at compilation time, and will cause 404 errors for your users. 560 | * Result filenames won’t include content hashes so you’ll need to add query arguments or rename them every time they change. 561 | 562 | ### When to Use the `public` Folder 563 | 564 | Normally we recommend importing [stylesheets](#adding-a-stylesheet), [images, and fonts](#adding-images-and-fonts) from JavaScript. 565 | The `public` folder is useful as a workaround for a number of less common cases: 566 | 567 | * You need a file with a specific name in the build output, such as [`manifest.webmanifest`](https://developer.mozilla.org/en-US/docs/Web/Manifest). 568 | * You have thousands of images and need to dynamically reference their paths. 569 | * You want to include a small script like [`pace.js`](http://github.hubspot.com/pace/docs/welcome/) outside of the bundled code. 570 | * Some library may be incompatible with Webpack and you have no other option but to include it as a `<script>` tag. 571 | 572 | Note that if you add a `<script>` that declares global variables, you also need to read the next section on using them. 573 | 574 | ## Using Global Variables 575 | 576 | When you include a script in the HTML file that defines global variables and try to use one of these variables in the code, the linter will complain because it cannot see the definition of the variable. 577 | 578 | You can avoid this by reading the global variable explicitly from the `window` object, for example: 579 | 580 | ```js 581 | const $ = window.$; 582 | ``` 583 | 584 | This makes it obvious you are using a global variable intentionally rather than because of a typo. 585 | 586 | Alternatively, you can force the linter to ignore any line by adding `// eslint-disable-line` after it. 587 | 588 | ## Adding Bootstrap 589 | 590 | You don’t have to use [React Bootstrap](https://react-bootstrap.github.io) together with React but it is a popular library for integrating Bootstrap with React apps. If you need it, you can integrate it with Create React App by following these steps: 591 | 592 | Install React Bootstrap and Bootstrap from npm. React Bootstrap does not include Bootstrap CSS so this needs to be installed as well: 593 | 594 | ``` 595 | npm install react-bootstrap --save 596 | npm install bootstrap@3 --save 597 | ``` 598 | 599 | Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your ```src/index.js``` file: 600 | 601 | ```js 602 | import 'bootstrap/dist/css/bootstrap.css'; 603 | import 'bootstrap/dist/css/bootstrap-theme.css'; 604 | // Put any other imports below so that CSS from your 605 | // components takes precedence over default styles. 606 | ``` 607 | 608 | Import required React Bootstrap components within ```src/App.js``` file or your custom component files: 609 | 610 | ```js 611 | import { Navbar, Jumbotron, Button } from 'react-bootstrap'; 612 | ``` 613 | 614 | Now you are ready to use the imported React Bootstrap components within your component hierarchy defined in the render method. Here is an example [`App.js`](https://gist.githubusercontent.com/gaearon/85d8c067f6af1e56277c82d19fd4da7b/raw/6158dd991b67284e9fc8d70b9d973efe87659d72/App.js) redone using React Bootstrap. 615 | 616 | ### Using a Custom Theme 617 | 618 | Sometimes you might need to tweak the visual styles of Bootstrap (or equivalent package).<br> 619 | We suggest the following approach: 620 | 621 | * Create a new package that depends on the package you wish to customize, e.g. Bootstrap. 622 | * Add the necessary build steps to tweak the theme, and publish your package on npm. 623 | * Install your own theme npm package as a dependency of your app. 624 | 625 | Here is an example of adding a [customized Bootstrap](https://medium.com/@tacomanator/customizing-create-react-app-aa9ffb88165) that follows these steps. 626 | 627 | ## Adding Flow 628 | 629 | Flow is a static type checker that helps you write code with fewer bugs. Check out this [introduction to using static types in JavaScript](https://medium.com/@preethikasireddy/why-use-static-types-in-javascript-part-1-8382da1e0adb) if you are new to this concept. 630 | 631 | Recent versions of [Flow](http://flowtype.org/) work with Create React App projects out of the box. 632 | 633 | To add Flow to a Create React App project, follow these steps: 634 | 635 | 1. Run `npm install --save-dev flow-bin` (or `yarn add --dev flow-bin`). 636 | 2. Add `"flow": "flow"` to the `scripts` section of your `package.json`. 637 | 3. Run `npm run flow -- init` (or `yarn flow -- init`) to create a [`.flowconfig` file](https://flowtype.org/docs/advanced-configuration.html) in the root directory. 638 | 4. Add `// @flow` to any files you want to type check (for example, to `src/App.js`). 639 | 640 | Now you can run `npm run flow` (or `yarn flow`) to check the files for type errors. 641 | You can optionally use an IDE like [Nuclide](https://nuclide.io/docs/languages/flow/) for a better integrated experience. 642 | In the future we plan to integrate it into Create React App even more closely. 643 | 644 | To learn more about Flow, check out [its documentation](https://flowtype.org/). 645 | 646 | ## Adding Custom Environment Variables 647 | 648 | >Note: this feature is available with `react-scripts@0.2.3` and higher. 649 | 650 | Your project can consume variables declared in your environment as if they were declared locally in your JS files. By 651 | default you will have `NODE_ENV` defined for you, and any other environment variables starting with 652 | `REACT_APP_`. 653 | 654 | **The environment variables are embedded during the build time**. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, just like [described here](#injecting-data-from-the-server-into-the-page). Alternatively you can rebuild the app on the server anytime you change them. 655 | 656 | >Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid accidentally [exposing a private key on the machine that could have the same name](https://github.com/facebookincubator/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running. 657 | 658 | These environment variables will be defined for you on `process.env`. For example, having an environment 659 | variable named `REACT_APP_SECRET_CODE` will be exposed in your JS as `process.env.REACT_APP_SECRET_CODE`. 660 | 661 | There is also a special built-in environment variable called `NODE_ENV`. You can read it from `process.env.NODE_ENV`. When you run `npm start`, it is always equal to `'development'`, when you run `npm test` it is always equal to `'test'`, and when you run `npm run build` to make a production bundle, it is always equal to `'production'`. **You cannot override `NODE_ENV` manually.** This prevents developers from accidentally deploying a slow development build to production. 662 | 663 | These environment variables can be useful for displaying information conditionally based on where the project is 664 | deployed or consuming sensitive data that lives outside of version control. 665 | 666 | First, you need to have environment variables defined. For example, let’s say you wanted to consume a secret defined 667 | in the environment inside a `<form>`: 668 | 669 | ```jsx 670 | render() { 671 | return ( 672 | <div> 673 | <small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small> 674 | <form> 675 | <input type="hidden" defaultValue={process.env.REACT_APP_SECRET_CODE} /> 676 | </form> 677 | </div> 678 | ); 679 | } 680 | ``` 681 | 682 | During the build, `process.env.REACT_APP_SECRET_CODE` will be replaced with the current value of the `REACT_APP_SECRET_CODE` environment variable. Remember that the `NODE_ENV` variable will be set for you automatically. 683 | 684 | When you load the app in the browser and inspect the `<input>`, you will see its value set to `abcdef`, and the bold text will show the environment provided when using `npm start`: 685 | 686 | ```html 687 | <div> 688 | <small>You are running this application in <b>development</b> mode.</small> 689 | <form> 690 | <input type="hidden" value="abcdef" /> 691 | </form> 692 | </div> 693 | ``` 694 | 695 | The above form is looking for a variable called `REACT_APP_SECRET_CODE` from the environment. In order to consume this 696 | value, we need to have it defined in the environment. This can be done using two ways: either in your shell or in 697 | a `.env` file. Both of these ways are described in the next few sections. 698 | 699 | Having access to the `NODE_ENV` is also useful for performing actions conditionally: 700 | 701 | ```js 702 | if (process.env.NODE_ENV !== 'production') { 703 | analytics.disable(); 704 | } 705 | ``` 706 | 707 | When you compile the app with `npm run build`, the minification step will strip out this condition, and the resulting bundle will be smaller. 708 | 709 | ### Referencing Environment Variables in the HTML 710 | 711 | >Note: this feature is available with `react-scripts@0.9.0` and higher. 712 | 713 | You can also access the environment variables starting with `REACT_APP_` in the `public/index.html`. For example: 714 | 715 | ```html 716 | <title>%REACT_APP_WEBSITE_NAME% 717 | ``` 718 | 719 | Note that the caveats from the above section apply: 720 | 721 | * Apart from a few built-in variables (`NODE_ENV` and `PUBLIC_URL`), variable names must start with `REACT_APP_` to work. 722 | * The environment variables are injected at build time. If you need to inject them at runtime, [follow this approach instead](#generating-dynamic-meta-tags-on-the-server). 723 | 724 | ### Adding Temporary Environment Variables In Your Shell 725 | 726 | Defining environment variables can vary between OSes. It’s also important to know that this manner is temporary for the 727 | life of the shell session. 728 | 729 | #### Windows (cmd.exe) 730 | 731 | ```cmd 732 | set REACT_APP_SECRET_CODE=abcdef&&npm start 733 | ``` 734 | 735 | (Note: the lack of whitespace is intentional.) 736 | 737 | #### Linux, macOS (Bash) 738 | 739 | ```bash 740 | REACT_APP_SECRET_CODE=abcdef npm start 741 | ``` 742 | 743 | ### Adding Development Environment Variables In `.env` 744 | 745 | >Note: this feature is available with `react-scripts@0.5.0` and higher. 746 | 747 | To define permanent environment variables, create a file called `.env` in the root of your project: 748 | 749 | ``` 750 | REACT_APP_SECRET_CODE=abcdef 751 | ``` 752 | 753 | These variables will act as the defaults if the machine does not explicitly set them.
754 | Please refer to the [dotenv documentation](https://github.com/motdotla/dotenv) for more details. 755 | 756 | >Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need 757 | these defined as well. Consult their documentation how to do this. For example, see the documentation for [Travis CI](https://docs.travis-ci.com/user/environment-variables/) or [Heroku](https://devcenter.heroku.com/articles/config-vars). 758 | 759 | ## Can I Use Decorators? 760 | 761 | Many popular libraries use [decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841) in their documentation.
762 | Create React App doesn’t support decorator syntax at the moment because: 763 | 764 | * It is an experimental proposal and is subject to change. 765 | * The current specification version is not officially supported by Babel. 766 | * If the specification changes, we won’t be able to write a codemod because we don’t use them internally at Facebook. 767 | 768 | However in many cases you can rewrite decorator-based code without decorators just as fine.
769 | Please refer to these two threads for reference: 770 | 771 | * [#214](https://github.com/facebookincubator/create-react-app/issues/214) 772 | * [#411](https://github.com/facebookincubator/create-react-app/issues/411) 773 | 774 | Create React App will add decorator support when the specification advances to a stable stage. 775 | 776 | ## Integrating with an API Backend 777 | 778 | These tutorials will help you to integrate your app with an API backend running on another port, 779 | using `fetch()` to access it. 780 | 781 | ### Node 782 | Check out [this tutorial](https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/). 783 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo). 784 | 785 | ### Ruby on Rails 786 | 787 | Check out [this tutorial](https://www.fullstackreact.com/articles/how-to-get-create-react-app-to-work-with-your-rails-api/). 788 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo-rails). 789 | 790 | ## Proxying API Requests in Development 791 | 792 | >Note: this feature is available with `react-scripts@0.2.3` and higher. 793 | 794 | People often serve the front-end React app from the same host and port as their backend implementation.
795 | For example, a production setup might look like this after the app is deployed: 796 | 797 | ``` 798 | / - static server returns index.html with React app 799 | /todos - static server returns index.html with React app 800 | /api/todos - server handles any /api/* requests using the backend implementation 801 | ``` 802 | 803 | Such setup is **not** required. However, if you **do** have a setup like this, it is convenient to write requests like `fetch('/api/todos')` without worrying about redirecting them to another host or port during development. 804 | 805 | To tell the development server to proxy any unknown requests to your API server in development, add a `proxy` field to your `package.json`, for example: 806 | 807 | ```js 808 | "proxy": "http://localhost:4000", 809 | ``` 810 | 811 | This way, when you `fetch('/api/todos')` in development, the development server will recognize that it’s not a static asset, and will proxy your request to `http://localhost:4000/api/todos` as a fallback. The development server will only attempt to send requests without a `text/html` accept header to the proxy. 812 | 813 | Conveniently, this avoids [CORS issues](http://stackoverflow.com/questions/21854516/understanding-ajax-cors-and-security-considerations) and error messages like this in development: 814 | 815 | ``` 816 | Fetch API cannot load http://localhost:4000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 817 | ``` 818 | 819 | Keep in mind that `proxy` only has effect in development (with `npm start`), and it is up to you to ensure that URLs like `/api/todos` point to the right thing in production. You don’t have to use the `/api` prefix. Any unrecognized request without a `text/html` accept header will be redirected to the specified `proxy`. 820 | 821 | The `proxy` option supports HTTP, HTTPS and WebSocket connections.
822 | If the `proxy` option is **not** flexible enough for you, alternatively you can: 823 | 824 | * Enable CORS on your server ([here’s how to do it for Express](http://enable-cors.org/server_expressjs.html)). 825 | * Use [environment variables](#adding-custom-environment-variables) to inject the right server host and port into your app. 826 | 827 | ## Using HTTPS in Development 828 | 829 | >Note: this feature is available with `react-scripts@0.4.0` and higher. 830 | 831 | You may require the dev server to serve pages over HTTPS. One particular case where this could be useful is when using [the "proxy" feature](#proxying-api-requests-in-development) to proxy requests to an API server when that API server is itself serving HTTPS. 832 | 833 | To do this, set the `HTTPS` environment variable to `true`, then start the dev server as usual with `npm start`: 834 | 835 | #### Windows (cmd.exe) 836 | 837 | ```cmd 838 | set HTTPS=true&&npm start 839 | ``` 840 | 841 | (Note: the lack of whitespace is intentional.) 842 | 843 | #### Linux, macOS (Bash) 844 | 845 | ```bash 846 | HTTPS=true npm start 847 | ``` 848 | 849 | Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page. 850 | 851 | ## Generating Dynamic `` Tags on the Server 852 | 853 | Since Create React App doesn’t support server rendering, you might be wondering how to make `` tags dynamic and reflect the current URL. To solve this, we recommend to add placeholders into the HTML, like this: 854 | 855 | ```html 856 | 857 | 858 | 859 | 860 | 861 | ``` 862 | 863 | Then, on the server, regardless of the backend you use, you can read `index.html` into memory and replace `__OG_TITLE__`, `__OG_DESCRIPTION__`, and any other placeholders with values depending on the current URL. Just make sure to sanitize and escape the interpolated values so that they are safe to embed into HTML! 864 | 865 | If you use a Node server, you can even share the route matching logic between the client and the server. However duplicating it also works fine in simple cases. 866 | 867 | ## Pre-Rendering into Static HTML Files 868 | 869 | If you’re hosting your `build` with a static hosting provider you can use [react-snapshot](https://www.npmjs.com/package/react-snapshot) to generate HTML pages for each route, or relative link, in your application. These pages will then seamlessly become active, or “hydrated”, when the JavaScript bundle has loaded. 870 | 871 | There are also opportunities to use this outside of static hosting, to take the pressure off the server when generating and caching routes. 872 | 873 | The primary benefit of pre-rendering is that you get the core content of each page _with_ the HTML payload—regardless of whether or not your JavaScript bundle successfully downloads. It also increases the likelihood that each route of your application will be picked up by search engines. 874 | 875 | You can read more about [zero-configuration pre-rendering (also called snapshotting) here](https://medium.com/superhighfives/an-almost-static-stack-6df0a2791319). 876 | 877 | ## Injecting Data from the Server into the Page 878 | 879 | Similarly to the previous section, you can leave some placeholders in the HTML that inject global variables, for example: 880 | 881 | ```js 882 | 883 | 884 | 885 | 888 | ``` 889 | 890 | Then, on the server, you can replace `__SERVER_DATA__` with a JSON of real data right before sending the response. The client code can then read `window.SERVER_DATA` to use it. **Make sure to [sanitize the JSON before sending it to the client](https://medium.com/node-security/the-most-common-xss-vulnerability-in-react-js-applications-2bdffbcc1fa0) as it makes your app vulnerable to XSS attacks.** 891 | 892 | ## Running Tests 893 | 894 | >Note: this feature is available with `react-scripts@0.3.0` and higher.
895 | >[Read the migration guide to learn how to enable it in older projects!](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030) 896 | 897 | Create React App uses [Jest](https://facebook.github.io/jest/) as its test runner. To prepare for this integration, we did a [major revamp](https://facebook.github.io/jest/blog/2016/09/01/jest-15.html) of Jest so if you heard bad things about it years ago, give it another try. 898 | 899 | Jest is a Node-based runner. This means that the tests always run in a Node environment and not in a real browser. This lets us enable fast iteration speed and prevent flakiness. 900 | 901 | While Jest provides browser globals such as `window` thanks to [jsdom](https://github.com/tmpvar/jsdom), they are only approximations of the real browser behavior. Jest is intended to be used for unit tests of your logic and your components rather than the DOM quirks. 902 | 903 | We recommend that you use a separate tool for browser end-to-end tests if you need them. They are beyond the scope of Create React App. 904 | 905 | ### Filename Conventions 906 | 907 | Jest will look for test files with any of the following popular naming conventions: 908 | 909 | * Files with `.js` suffix in `__tests__` folders. 910 | * Files with `.test.js` suffix. 911 | * Files with `.spec.js` suffix. 912 | 913 | The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder. 914 | 915 | We recommend to put the test files (or `__tests__` folders) next to the code they are testing so that relative imports appear shorter. For example, if `App.test.js` and `App.js` are in the same folder, the test just needs to `import App from './App'` instead of a long relative path. Colocation also helps find tests more quickly in larger projects. 916 | 917 | ### Command Line Interface 918 | 919 | When you run `npm test`, Jest will launch in the watch mode. Every time you save a file, it will re-run the tests, just like `npm start` recompiles the code. 920 | 921 | The watcher includes an interactive command-line interface with the ability to run all tests, or focus on a search pattern. It is designed this way so that you can keep it open and enjoy fast re-runs. You can learn the commands from the “Watch Usage” note that the watcher prints after every run: 922 | 923 | ![Jest watch mode](http://facebook.github.io/jest/img/blog/15-watch.gif) 924 | 925 | ### Version Control Integration 926 | 927 | By default, when you run `npm test`, Jest will only run the tests related to files changed since the last commit. This is an optimization designed to make your tests runs fast regardless of how many tests you have. However it assumes that you don’t often commit the code that doesn’t pass the tests. 928 | 929 | Jest will always explicitly mention that it only ran tests related to the files changed since the last commit. You can also press `a` in the watch mode to force Jest to run all tests. 930 | 931 | Jest will always run all tests on a [continuous integration](#continuous-integration) server or if the project is not inside a Git or Mercurial repository. 932 | 933 | ### Writing Tests 934 | 935 | To create tests, add `it()` (or `test()`) blocks with the name of the test and its code. You may optionally wrap them in `describe()` blocks for logical grouping but this is neither required nor recommended. 936 | 937 | Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this: 938 | 939 | ```js 940 | import sum from './sum'; 941 | 942 | it('sums numbers', () => { 943 | expect(sum(1, 2)).toEqual(3); 944 | expect(sum(2, 2)).toEqual(4); 945 | }); 946 | ``` 947 | 948 | All `expect()` matchers supported by Jest are [extensively documented here](http://facebook.github.io/jest/docs/expect.html).
949 | You can also use [`jest.fn()` and `expect(fn).toBeCalled()`](http://facebook.github.io/jest/docs/expect.html#tohavebeencalled) to create “spies” or mock functions. 950 | 951 | ### Testing Components 952 | 953 | There is a broad spectrum of component testing techniques. They range from a “smoke test” verifying that a component renders without throwing, to shallow rendering and testing some of the output, to full rendering and testing component lifecycle and state changes. 954 | 955 | Different projects choose different testing tradeoffs based on how often components change, and how much logic they contain. If you haven’t decided on a testing strategy yet, we recommend that you start with creating simple smoke tests for your components: 956 | 957 | ```js 958 | import React from 'react'; 959 | import ReactDOM from 'react-dom'; 960 | import App from './App'; 961 | 962 | it('renders without crashing', () => { 963 | const div = document.createElement('div'); 964 | ReactDOM.render(, div); 965 | }); 966 | ``` 967 | 968 | This test mounts a component and makes sure that it didn’t throw during rendering. Tests like this provide a lot value with very little effort so they are great as a starting point, and this is the test you will find in `src/App.test.js`. 969 | 970 | When you encounter bugs caused by changing components, you will gain a deeper insight into which parts of them are worth testing in your application. This might be a good time to introduce more specific tests asserting specific expected output or behavior. 971 | 972 | If you’d like to test components in isolation from the child components they render, we recommend using [`shallow()` rendering API](http://airbnb.io/enzyme/docs/api/shallow.html) from [Enzyme](http://airbnb.io/enzyme/). You can write a smoke test with it too: 973 | 974 | ```sh 975 | npm install --save-dev enzyme react-addons-test-utils 976 | ``` 977 | 978 | ```js 979 | import React from 'react'; 980 | import { shallow } from 'enzyme'; 981 | import App from './App'; 982 | 983 | it('renders without crashing', () => { 984 | shallow(); 985 | }); 986 | ``` 987 | 988 | Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `` and doesn’t go deeper. For example, even if `` itself renders a ` 193 | 194 | 204 | 205 | 215 | 216 | { !this.state.logged && 217 | 226 | } 227 | {this.state.redirectSupport && 228 | } 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | ); 243 | } 244 | } 245 | 246 | export default App; 247 | -------------------------------------------------------------------------------- /FE/src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); 7 | ReactDOM.render(, div); 8 | }); 9 | -------------------------------------------------------------------------------- /FE/src/Dashboard.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import { 3 | Button, 4 | Form, 5 | Grid, 6 | Header, 7 | Message, 8 | Segment, 9 | Icon, 10 | Statistic, 11 | Divider 12 | } from "semantic-ui-react"; 13 | 14 | import { 15 | BrowserRouter as Router, 16 | Route, 17 | Link, 18 | Redirect 19 | } from "react-router-dom"; 20 | 21 | class Dashboard extends Component { 22 | constructor(props) { 23 | super(props); 24 | } 25 | 26 | state = { 27 | statistics: { request_count: "?", created_bins: "?" } 28 | }; 29 | 30 | getStatistics = () => { 31 | var bearer = "Bearer " + localStorage.getItem("access_token"); 32 | //console.log(bearer); 33 | var obj = { 34 | method: "GET", 35 | headers: new Headers({ 36 | Accept: "aplication/json", 37 | Authorization: bearer, 38 | // "Access-Control-Allow-Origin": "*", 39 | "Access-Control-Request-Headers": "Authorization, Accept" 40 | }) 41 | }; 42 | fetch(process.env.REACT_APP_API+"/api/statistics", obj) 43 | .then(res => res.json()) 44 | .then(data => { 45 | if ( 46 | (data.message !== "Token has expired") & 47 | (data.message !== "Not enough segments") 48 | ) { 49 | this.setState({ 50 | statistics: data 51 | }); 52 | } 53 | }) 54 | .catch(err => { 55 | console.log(err); 56 | }); 57 | }; 58 | componentDidMount() { 59 | this.getStatistics(); 60 | } 61 | render() { 62 | return ( 63 |
64 | 69 | 70 |
71 | 72 | DNSfookup 73 | 76 | DNS that fucks things up 77 | 78 |
79 | 80 | 81 | 82 | 83 | {this.state.statistics.created_bins} 84 | 85 | Fookup bins created 86 | 87 | 88 | 89 | {this.state.statistics.request_count} 90 | 91 | total DNS requests recieved 92 | 93 | 94 | 95 |
96 |
97 |
98 | ); 99 | } 100 | } 101 | 102 | export default Dashboard; 103 | -------------------------------------------------------------------------------- /FE/src/Home.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import { Grid, Button, Header, Icon } from "semantic-ui-react"; 3 | import { Link } from "react-router-dom"; 4 | 5 | class Home extends Component { 6 | render() { 7 | return ( 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
24 | 29 | DNSfookup 30 | DNS that fucks things up 31 |
32 | 33 | 34 | 35 | 38 | 39 | 40 | 43 | 44 | 45 | 46 |
47 | ); 48 | } 49 | } 50 | 51 | export default Home; 52 | -------------------------------------------------------------------------------- /FE/src/Login.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import { 3 | Button, 4 | Form, 5 | Grid, 6 | Header, 7 | Message, 8 | Segment, 9 | Icon 10 | } from "semantic-ui-react"; 11 | import { 12 | BrowserRouter as Router, 13 | Route, 14 | Link, 15 | Redirect 16 | } from "react-router-dom"; 17 | 18 | class Login extends Component { 19 | constructor(props) { 20 | super(props); 21 | } 22 | 23 | state = { 24 | loginError: false 25 | }; 26 | 27 | LoginForm() { 28 | return ( 29 | 34 | 35 |
41 | Log-in to your account 42 |
43 |
44 | {this.state.loginError && ( 45 | 46 | 47 | Incorrect Username or Password 48 | 49 | )} 50 | 51 | 58 | 66 | 67 | 76 |
77 | 78 | 79 | 80 | 87 | 88 | 89 | 90 |
91 |
92 |
93 |
94 | ); 95 | } 96 | 97 | postLogin = event => { 98 | event.preventDefault(); 99 | 100 | let email = document.getElementById("username").value; 101 | let password = document.getElementById("password").value; 102 | var data = new FormData(); 103 | data.append("username", email); 104 | data.append("password", password); 105 | 106 | fetch(process.env.REACT_APP_API+"/auth/login", { 107 | method: "POST", 108 | headers: new Headers({ 109 | // 'Content-Type': 'form-data', 110 | }), 111 | body: data 112 | }) 113 | .then(res => res.json()) 114 | .then(data => { 115 | if (data.error != null) { 116 | this.invalidCredenitals(); 117 | } else { 118 | localStorage.setItem("access_token", data.access_token); 119 | this.props.setUser(data); 120 | } 121 | }) 122 | .catch(err => { 123 | console.log(err); 124 | }); 125 | }; 126 | 127 | invalidCredenitals = () => { 128 | this.setState({ 129 | loginError: true 130 | }); 131 | }; 132 | 133 | render() { 134 | return
{this.LoginForm()}
; 135 | } 136 | } 137 | 138 | export default Login; 139 | -------------------------------------------------------------------------------- /FE/src/MyBins.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import { 3 | Grid, 4 | Segment, 5 | Pagination, 6 | Dropdown, 7 | Header, 8 | Icon, 9 | Divider, 10 | Table, 11 | Menu, 12 | Label, 13 | Button, 14 | Popup 15 | } from "semantic-ui-react"; 16 | import { Link } from "react-router-dom"; 17 | import {CopyToClipboard} from 'react-copy-to-clipboard'; 18 | 19 | class MyBins extends Component { 20 | state = { 21 | active: "mybins", 22 | selected: "", 23 | bins: [], 24 | logs: [], 25 | props: [], 26 | total_pages: 1, 27 | total_entries: "?", 28 | curr_page: 1 29 | }; 30 | 31 | getBins = () => { 32 | var bearer = "Bearer " + localStorage.getItem("access_token"); 33 | var obj = { 34 | method: "GET", 35 | headers: new Headers({ 36 | Accept: "aplication/json", 37 | Authorization: bearer, 38 | "Access-Control-Request-Headers": "Authorization, Accept" 39 | }) 40 | }; 41 | fetch(process.env.REACT_APP_API+"/api/fookup/listAll", obj) 42 | .then(res => res.json()) 43 | .then(data => { 44 | if ( 45 | (data.msg !== "Token has expired") & 46 | (data.msg !== "Not enough segments") 47 | ) { 48 | this.setState({ 49 | bins: data.reverse().map(bin => ({ 50 | value: bin.uuid, 51 | text: bin.name 52 | })) 53 | }); 54 | } 55 | }) 56 | .catch(err => { 57 | console.log(err); 58 | }); 59 | }; 60 | 61 | getLogs = (uuid, page) => { 62 | var bearer = "Bearer " + localStorage.getItem("access_token"); 63 | var data = { 64 | "uuid": uuid, 65 | "page": page 66 | }; 67 | var obj = { 68 | method: "POST", 69 | headers: new Headers({ 70 | Accept: "aplication/json", 71 | Authorization: bearer, 72 | // "Access-Control-Allow-Origin": "*", 73 | 'Content-Type': 'application/json', 74 | "Access-Control-Request-Headers": "Authorization, Accept" 75 | }), 76 | body: JSON.stringify(data) 77 | }; 78 | fetch(process.env.REACT_APP_API+"/api/fookup/logs/uuid", obj) 79 | .then(res => res.json()) 80 | .then(data => { 81 | if ( 82 | (data.msg !== "Token has expired") & 83 | (data.msg !== "Not enough segments") 84 | ) { 85 | this.setState({ 86 | total_pages: data.pages, 87 | total_entries: data.entries, 88 | logs: data.data 89 | }); 90 | } 91 | }) 92 | .catch(err => { 93 | console.log(err); 94 | }); 95 | }; 96 | 97 | deleteUUID = (e) => { 98 | var bearer = "Bearer " + localStorage.getItem("access_token"); 99 | e.preventDefault(); 100 | var uuid = this.state.selected 101 | var data = {"uuid": uuid}; 102 | var obj = { 103 | method: "POST", 104 | headers: new Headers({ 105 | Accept: "aplication/json", 106 | Authorization: bearer, 107 | // "Access-Control-Allow-Origin": "*", 108 | 'Content-Type': 'application/json', 109 | "Access-Control-Request-Headers": "Authorization, Accept" 110 | }), 111 | body: JSON.stringify(data) 112 | }; 113 | fetch(process.env.REACT_APP_API+"/api/fookup/delete", obj) 114 | .then(res => res.json()) 115 | .then(data => { 116 | if (data.uuid_props.success === true) { 117 | this.setState({ 118 | selected: "" 119 | }); 120 | this.getBins(); 121 | 122 | } 123 | }) 124 | .catch(err => { 125 | console.log(err); 126 | }); 127 | }; 128 | 129 | getProps = (uuid) => { 130 | var bearer = "Bearer " + localStorage.getItem("access_token"); 131 | var data = {"uuid": uuid}; 132 | var obj = { 133 | method: "POST", 134 | headers: new Headers({ 135 | Accept: "aplication/json", 136 | Authorization: bearer, 137 | // "Access-Control-Allow-Origin": "*", 138 | 'Content-Type': 'application/json', 139 | "Access-Control-Request-Headers": "Authorization, Accept" 140 | }), 141 | body: JSON.stringify(data) 142 | }; 143 | fetch(process.env.REACT_APP_API+"/api/fookup/props", obj) 144 | .then(res => res.json()) 145 | .then(data => { 146 | if (data.ip_props) { 147 | var props = []; 148 | var x; 149 | for (x in data.ip_props){ 150 | props.push(data.ip_props[x]) 151 | } 152 | this.setState({ 153 | 'props': props 154 | }); 155 | console.log(this.state.props) 156 | } 157 | }) 158 | .catch(err => { 159 | console.log(err); 160 | }); 161 | }; 162 | 163 | componentDidMount() { 164 | this.getBins(); 165 | } 166 | onChange = (e, data) => { 167 | e.preventDefault() 168 | this.setState( 169 | { selected: data.value, curr_page: 1, total_pages: 1}, 170 | this.getLogs(data.value, 1), 171 | this.getProps(data.value) 172 | ); 173 | }; 174 | 175 | handleReload = (e) => { 176 | e.preventDefault() 177 | this.setState({ curr_page: 1, total_pages: 1}, 178 | this.getLogs(this.state.selected, 1) 179 | ); 180 | }; 181 | 182 | handlePaginationChange = (e, { activePage }) => { 183 | e.preventDefault() 184 | this.setState({curr_page: activePage}, 185 | this.getLogs(this.state.selected, activePage) 186 | ); 187 | }; 188 | 189 | 190 | 191 | logsTable(input_data) { 192 | return ( 193 | 194 | 195 | 196 | Resolved to 197 | Domain requested 198 | Origin ip:port 199 | Time 200 | 201 | 202 | 203 | {input_data.map(log => ( 204 | 205 | {log.resolved_to} 206 | {log.domain} 207 | 208 | {log.origin_ip}:{log.port} 209 | 210 | {log.created_date} 211 | 212 | ))} 213 | 214 |
215 | ); 216 | } 217 | render() { 218 | return ( 219 |
220 | 221 | 222 | 223 | 230 |
231 |
232 | {this.state.selected !== "" && 233 | (
234 | 235 | 240 | Rebinding flow: 241 | 242 | {this.state.props.map(i => ( 243 | 248 | { 249 | (i.ip.length > 16) && ( 250 | 253 | { i.type===undefined ? "A":i.type} "{i.ip.slice(0, 5)+'...'+i.ip.slice(-5)}" {i.repeat} time{(i.repeat==1) ? '':'s'} 254 |
} 255 | /> 256 | ) 257 | } 258 | { 259 | (i.ip.length <= 16) && 260 | ( 261 |
262 | { i.type===undefined ? "A":i.type} "{i.ip}" {i.repeat} time{(i.repeat==1) ? '':'s'} 263 |
264 | ) 265 | } 266 | 267 | ))} 268 | 269 | 270 | 275 | {this.state.total_entries} DNS queries recieved 276 | 277 | 278 | this.setState({copied: true})} 281 | > 282 |
) 318 | } 319 | 320 | 323 | {this.state.selected === "" && ( 324 |
330 | 335 | Select your DNS bin! 336 | 337 |
338 | )} 339 | {this.state.selected !== "" && this.logsTable(this.state.logs)} 340 | {this.state.selected !== "" && 341 | ( 344 | 345 | 358 | 359 | )} 360 | 361 |
362 | {this.state.selected !== "" && 363 | ( 364 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | ); 355 | } 356 | } 357 | 358 | export default NewBin; 359 | -------------------------------------------------------------------------------- /FE/src/Settings.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import { 3 | Grid, 4 | Button, 5 | Header, 6 | Icon, 7 | Form, 8 | Input, 9 | Segment, 10 | Message, 11 | Popup 12 | } from "semantic-ui-react"; 13 | import { Link } from "react-router-dom"; 14 | import {CopyToClipboard} from 'react-copy-to-clipboard'; 15 | 16 | class Settings extends Component { 17 | 18 | state = { 19 | active: "settings", 20 | copied: false, 21 | pw_changed: false, 22 | pw_fail: false, 23 | fail_msg: "", 24 | del_msg: "", 25 | del_fail: false 26 | } 27 | 28 | 29 | deletMe = (e) => { 30 | e.preventDefault(); 31 | 32 | let pw = document.getElementById("delete_pw").value; 33 | if (pw == ""){ 34 | this.setState({ 35 | del_fail: true, 36 | del_msg: 'Fill the password in' 37 | }); 38 | setTimeout(() => this.setState({pw_fail:false}), 2000); 39 | return 40 | } else if (pw.length < 8){ 41 | this.setState({ 42 | del_fail: true, 43 | del_msg: 'Minimum password length is 8 characters.. Did you know that?' 44 | }); 45 | setTimeout(() => this.setState({pw_fail:false}), 2000); 46 | return 47 | } 48 | 49 | var data = { 50 | "password": pw, 51 | } 52 | var bearer = "Bearer " + localStorage.getItem("access_token"); 53 | 54 | fetch(process.env.REACT_APP_API+"/auth/delete_me", { 55 | method: "POST", 56 | Accept: "aplication/json", 57 | headers: new Headers({ 58 | 'Authorization': bearer, 59 | 'Content-Type': 'application/json', 60 | "Access-Control-Request-Headers": "Authorization, Accept" 61 | }), 62 | body: JSON.stringify(data) 63 | }) 64 | .then(res => res.json()) 65 | .then(data => { 66 | if (data.success === true) { 67 | localStorage.getItem("access_token"); 68 | window.location.reload(); 69 | } else { 70 | this.setState({ 71 | del_fail: true, 72 | del_msg: data.message 73 | }); 74 | setTimeout(() => this.setState({del_fail:false}), 1420); 75 | 76 | } 77 | }) 78 | .catch(err => { 79 | console.log(err); 80 | }); 81 | }; 82 | 83 | pwChange = (e) => { 84 | e.preventDefault(); 85 | 86 | let oldpw = document.getElementById("oldpw").value; 87 | let newpw = document.getElementById("newpw").value; 88 | if (oldpw == "" || newpw == ""){ 89 | this.setState({ 90 | pw_fail: true, 91 | fail_msg: 'Please fill out both fields' 92 | }); 93 | setTimeout(() => this.setState({pw_fail:false}), 2000); 94 | return 95 | } else if (oldpw.length < 8 || newpw.length < 8){ 96 | this.setState({ 97 | pw_fail: true, 98 | fail_msg: 'Minimum password length is 8 characters' 99 | }); 100 | setTimeout(() => this.setState({pw_fail:false}), 2000); 101 | return 102 | } else if (oldpw===newpw){ 103 | this.setState({ 104 | pw_fail: true, 105 | fail_msg: 'For real?' 106 | }); 107 | setTimeout(() => this.setState({pw_fail:false}), 2000); 108 | return 109 | } 110 | 111 | var data = { 112 | "old_password": oldpw, 113 | "new_password": newpw 114 | } 115 | var bearer = "Bearer " + localStorage.getItem("access_token"); 116 | 117 | fetch(process.env.REACT_APP_API+"/auth/change_pw", { 118 | method: "POST", 119 | Accept: "aplication/json", 120 | headers: new Headers({ 121 | 'Authorization': bearer, 122 | 'Content-Type': 'application/json', 123 | "Access-Control-Request-Headers": "Authorization, Accept" 124 | }), 125 | body: JSON.stringify(data) 126 | }) 127 | .then(res => res.json()) 128 | .then(data => { 129 | if (data.success === true) { 130 | this.setState({ 131 | pw_changed: true, 132 | pw_fail: false 133 | }); 134 | setTimeout(() => this.setState({pw_changed:false}), 1420); 135 | 136 | } else { 137 | this.setState({ 138 | pw_fail: true, 139 | fail_msg: data.message 140 | }); 141 | setTimeout(() => this.setState({pw_fail:false}), 1420); 142 | 143 | } 144 | }) 145 | .catch(err => { 146 | console.log(err); 147 | }); 148 | }; 149 | 150 | render() { 151 | return ( 152 |
153 | 154 |
160 | 165 |
166 | 167 | 168 | 169 |
172 |
176 | Change password 177 |
178 | 179 | 186 | 193 | 194 | 200 | Submit 201 | 202 |
203 | 209 | 215 |
216 |
217 | 218 | 219 | 225 | 226 | { 229 | this.setState({copied: true}); 230 | setTimeout(() => this.setState({copied:false}), 800); 231 | }} 232 | > 233 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 259 | 260 | Erase all my data from here 261 | 262 | } 263 | content={ 264 | 267 |
268 | 269 | 276 | 277 | 283 | Delete me forever! 284 | 285 | 286 |
287 | 298 |
299 | } 300 | /> 301 | 302 |
303 |
304 |
305 | ); 306 | } 307 | } 308 | 309 | export default Settings; 310 | -------------------------------------------------------------------------------- /FE/src/Signup.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import { 3 | Button, 4 | Form, 5 | Grid, 6 | Header, 7 | Message, 8 | Segment, 9 | Icon 10 | } from "semantic-ui-react"; 11 | import { 12 | BrowserRouter as Router, 13 | Route, 14 | Link, 15 | Redirect 16 | } from "react-router-dom"; 17 | 18 | class Signup extends Component { 19 | constructor(props) { 20 | super(props); 21 | } 22 | 23 | state = { 24 | loginError: false 25 | }; 26 | 27 | signupErr = x => { 28 | this.setState({ 29 | signupError: true, 30 | errMessage: x.message 31 | }); 32 | console.log(this.state); 33 | }; 34 | postSignup = event => { 35 | event.preventDefault(); 36 | 37 | let email = document.getElementById("username").value; 38 | let password = document.getElementById("password").value; 39 | var data = new FormData(); 40 | data.append("username", email); 41 | data.append("password", password); 42 | 43 | fetch(process.env.REACT_APP_API+"/auth/signup", { 44 | method: "POST", 45 | headers: new Headers({ 46 | // 'Content-Type': 'form-data', 47 | }), 48 | body: data 49 | }) 50 | .then(res => res.json()) 51 | .then(data => { 52 | if (data.error != null) { 53 | this.signupErr(data); 54 | } else { 55 | localStorage.setItem("access_token", data.access_token); 56 | this.props.setUser(data); 57 | } 58 | }) 59 | .catch(err => { 60 | console.log(err); 61 | }); 62 | }; 63 | 64 | SignupForm() { 65 | return ( 66 | 71 | 72 |
78 | Create new account! 79 |
80 |
85 | {this.state.signupError && ( 86 | 87 | 88 | {this.state.errMessage} 89 | 90 | )} 91 | 95 | 102 | 110 | 111 | 119 |
120 | 121 | 122 | 123 | 130 | 131 | 132 | 133 |
134 |
135 |
136 |
137 | ); 138 | } 139 | 140 | render() { 141 | return
{this.SignupForm()}
; 142 | } 143 | } 144 | 145 | export default Signup; 146 | -------------------------------------------------------------------------------- /FE/src/Support.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import { 3 | Button, 4 | Form, 5 | Grid, 6 | Header, 7 | Message, 8 | Segment, 9 | Icon, 10 | Divider, 11 | Image 12 | } from "semantic-ui-react"; 13 | import {CopyToClipboard} from 'react-copy-to-clipboard'; 14 | 15 | class Support extends Component { 16 | render() { 17 | return ( 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
31 | 36 | Like DNSfookup? Support it! 37 |
Please donate to help me keep this running
38 |
39 | 40 |
41 | 42 | 43 | 44 | 45 |
46 | 47 |
50 | Bitcoin 51 |
52 | 57 | { 60 | this.setState({copied: true}); 61 | }} 62 | > 63 | 72 | 73 | 74 | 75 | 76 |
77 |
78 | 79 | 80 |
86 | Hall of Donate fame 87 | 90 | If you donated and want to appear here - Message me on keybase 91 | 92 | 95 | Or you can get my email here 96 | 97 |
98 | Notning here so far :( Rich hackers are welcome 99 |
100 |
101 |
102 |
103 |
); 104 | } 105 | } 106 | 107 | export default Support; 108 | -------------------------------------------------------------------------------- /FE/src/TopBar.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import { Menu, Image, Icon } from "semantic-ui-react"; 3 | import { 4 | BrowserRouter as Router, 5 | Route, 6 | Redirect, 7 | Link 8 | } from "react-router-dom"; 9 | 10 | class TopBar extends Component { 11 | constructor(props) { 12 | super(props); 13 | } 14 | 15 | state = { 16 | name: this.props.name, 17 | redirectHome: false, 18 | redirectBin: false, 19 | redirectSettings: false 20 | }; 21 | 22 | render() { 23 | return ( 24 | 28 | {this.state.redirectHome === true && } 29 | 30 | this.setState({active:""})} 33 | > 34 | 35 | Home 36 | 37 | 38 | this.setState({active:"dnsbin"})} 45 | > 46 | Create new bin 47 | 48 | this.setState({active:"mybins"})} 55 | > 56 | My bins 57 | 58 | this.setState({active:"settings"})} 65 | > 66 | 67 | Settings 68 | 69 | this.setState({active:"support"})} 76 | > 77 | 78 | Support me ❤️ 79 | 80 | 85 | Log Out 86 | 87 | 88 | ); 89 | } 90 | } 91 | export default TopBar; 92 | -------------------------------------------------------------------------------- /FE/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | font-family: sans-serif; 5 | background-color: #212121; 6 | } 7 | #footer{ 8 | position: fixed; 9 | left: 0; 10 | bottom: 0; 11 | width: 100%; 12 | } 13 | -------------------------------------------------------------------------------- /FE/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | import './index.css'; 5 | 6 | console.log(process.env.REACT_APP_API) 7 | 8 | ReactDOM.render( 9 | , 10 | document.getElementById('root') 11 | ); 12 | -------------------------------------------------------------------------------- /FE/src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DnsFookup v 2.0.1 2 | [DNS Rebinding](https://en.wikipedia.org/wiki/DNS_rebinding) freamwork containing: 3 | - a dns server obviously 4 | - python web api to create new subdomains and control the dns server, view logs, stuff like that 5 | - shitty react app to make it more comfy 6 | 7 | [Changelog](./CHANGELOG.md) 8 | 9 | [API documentation](./API.md) 10 | 11 | ## What does it do? 12 | It lets you create dns bins like a burp collaborator 13 | but it adds a bit more features... 14 | ![create new dnsbin](.images/create.png) 15 | 16 | You can specify what ips/domains should the created subdomain resolve to and how many times, for now it *A,CNAME and AAAA record are supported* 17 | 18 | Then you can see where it was requested from, what did it resolve to,... in logs 19 | ![create new dnsbin](.images/logs.png) 20 | 21 | 22 | 23 | ### Video of tool in action 24 | 25 | [![Watch the video](https://img.youtube.com/vi/jP_bFUdDVRQ/maxresdefault.jpg)](https://youtu.be/jP_bFUdDVRQ) 26 | 27 | Source of the vulnerable application is from https://github.com/makuga01/dnsFookup/tree/master/vulnerableApp 28 | 29 | ## How to run it 30 | 31 | First of all, check the configuration in config.yaml 32 | 33 | 34 | You also should not forget to change all passwords and keys inside the config 35 | 36 | 37 | ``` 38 | # First edit config.yaml as you please 39 | # Don't forget to change the JWT secret! 40 | vim config.yaml 41 | 42 | # Install python & docker-compose 43 | apt install docker-compose python3-pip 44 | sudo apt-get install libpq-dev python-dev 45 | 46 | #Set up postgres and redis 47 | sudo docker-compose up 48 | 49 | #in ./BE 50 | pip3 install -r requirements.txt 51 | 52 | python3 dns.py # to start the dns server 53 | 54 | # for testing purposes development server is enough I think 55 | FLASK_APP=app.py 56 | FLASK_ENV=development 57 | flask run 58 | 59 | # Install npm 60 | curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash - 61 | apt -y install nodejs make gcc g++ 62 | 63 | # then in ./FE 64 | npm install 65 | npm start 66 | ``` 67 | 68 | 69 | *If you have a bit of free time, please contribute, it means a lot to me :D* 70 | 71 | #### Want to see some feature in next update? 72 | 73 | Let me know [on keybase](https://keybase.io/gel0) 74 | -------------------------------------------------------------------------------- /config.yaml: -------------------------------------------------------------------------------- 1 | sql: 2 | protocol: 'postgresql+psycopg2' 3 | user: 'postgres' 4 | password: 'CHANGETHISTOO' 5 | host: 'localhost' 6 | db: 'dnsfookup' 7 | deprec_warn: false 8 | 9 | jwt: 10 | secret_key: 'changeme' 11 | blacklist_enabled: true 12 | blacklist_token_checks: ['access'] 13 | token_expires: 21600 # 6 hours 14 | 15 | redis: 16 | password: 'CHANGETHISPW' 17 | host: '127.0.0.1' 18 | port: 6379 19 | expiration: 3600 # expiration of redis key - default = 3600s 20 | timeout: 3 21 | 22 | dns: 23 | domain: 'gel0.space' 24 | #UDP port DNS server will listen on, for testing purposes it's on 5053, 25 | #if you want to deploy the app on server change this to 53 26 | port: 53 27 | ip: '127.0.0.1' 28 | # Failure ip - If server runs over some error it tries to 29 | # resolve to this ip (If that is possible) 30 | # if use_failure_ip is false, server will return NXDOMAIN 31 | use_failure_ip: false 32 | failure_ip: '0.0.0.0' 33 | use_fail_ns: true # when for example google.com is requested from the dns server, return ns record with IP pointing to fail_ns 34 | fail_ns: '8.8.8.8' 35 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | redis: 4 | image: "redis:latest" 5 | command: "redis-server --requirepass CHANGETHISPW" 6 | ports: 7 | - "127.0.0.1:6379:6379" 8 | postgres: 9 | image: "postgres:latest" 10 | restart: always 11 | environment: 12 | POSTGRES_PASSWORD: "CHANGETHISTOO" 13 | POSTGRES_DB: "dnsfookup" 14 | ports: 15 | - "127.0.0.1:5432:5432" 16 | -------------------------------------------------------------------------------- /vulnerableApp/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request 2 | from tld import get_tld 3 | from dns import resolve 4 | import requests 5 | app = Flask(__name__) 6 | 7 | BLACKLIST = ['127.0.0.1', '0.0.0.0'] 8 | 9 | """ 10 | This is a very ugly and half-functioning example of vulnerable code: 11 | (I know, it probably has dozen of other ssrfs inside but for testing purposes it's just fine :D) 12 | """ 13 | 14 | @app.route('/') 15 | def vuln(): 16 | if 'url' in request.args: 17 | try: 18 | url = request.args['url'] 19 | info = get_tld(url, as_object=True) 20 | if resolve(info.parsed_url[1]) not in BLACKLIST: # <- First the domain needst to resolve to non-blacklist IP 21 | return requests.get(url).text # <- After the check passes, it can resolve to whatever you want :D 22 | else: 23 | return 'blacklisted' 24 | except: 25 | return 'bad url' 26 | else: 27 | return 'supply url to GET `url`' 28 | -------------------------------------------------------------------------------- /vulnerableApp/dns.py: -------------------------------------------------------------------------------- 1 | from dnslib import * 2 | 3 | def resolve(domain): 4 | q = DNSRecord.question(domain) 5 | a = q.send('127.0.0.1', port=53, timeout=1) 6 | return str(DNSRecord.parse(a).get_a().rdata) 7 | --------------------------------------------------------------------------------