├── .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 `` 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.
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`.
139 | Read instructions below for using assets from JavaScript and HTML.
140 |
141 | You can, however, create more top-level directories.
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.
151 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
152 |
153 | The page will reload if you make edits.
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.
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.
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.
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.
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 | >
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 ``
285 |
286 | You can find the source HTML file in the `public` folder of the generated project. You may edit the `` 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
300 | ```
301 |
302 | ## Importing a Component
303 |
304 | This project setup supports ES6 modules thanks to Babel.
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 ;
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 ;
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 `` and `` components, we recommend creating a `