text
stringlengths
9
39.2M
dir
stringlengths
25
226
lang
stringclasses
163 values
created_date
timestamp[s]
updated_date
timestamp[s]
repo_name
stringclasses
751 values
repo_full_name
stringclasses
752 values
star
int64
1.01k
183k
len_tokens
int64
1
18.5M
```yaml auth: credentials: - password: '-----BEGIN DSA PRIVATE KEY----- MIIBugIBAAKBgQCEgBNwgF+IbMU8NHUXNIMfJ0ONa91ZI/TphuixnilkZqcuwur2 hMbrqY8Yne+n3eGkuepQlBBKEZSd8xPd6qCvWnCOhBqhkBS7g2dH6jMkUl/opX/t Rw6P00crq2oIMafR4/SzKWVW6RQEzJtPnfV7O3i5miY7jLKMDZTn/DRXRwIVALB2 +o4CRHpCG6IBqlD/2JW5HRQBAoGAaSzKOHYUnlpAoX7+ufViz37cUa1/x0fGDA/4 your_sha256_hash your_sha256_hash your_sha256_hash 6X/6VivPAUWmmmev/BuAs8M1HtfGeGGzMzDIiU/WZQ3bScLB1Ykrcjk7TOFD6xrn k/inYAp5l29hjidoAONcXoHmUAMYOKqn63Q2AsDpExVcmfj99/BlpQIUYS6Hs70u B3Upsx556K/iZPPnJZE= -----END DSA PRIVATE KEY----- ' username: root category: ssh contributor: ztgrace, hdmoore default_port: 22 name: Quantum DXi V1000 references: - path_to_url - path_to_url ```
/content/code_sandbox/creds/ssh_key/quantum-dxi-v1000.yml
yaml
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
398
```yaml auth: credentials: - password: '-----BEGIN DSA PRIVATE KEY----- MIIBugIBAAKBgQCUw7F/vKJT2Xsq+fIPVxNC/Dyk+dN9DWQT5RO56eIQasd+h6Fm q1qtQrJ/DOe3VjfUrSm7NN5NoIGOrGCSuQFthFmq+9Lpt6WIykB4mau5iE5orbKM xTfyu8LtntoikYKrlMB+UrmKDidvZ+7oWiC14imT+Px/3Q7naj0UmOrSTwIVAO25 Yf3SYNtTYv8yzaV+X9yNr/AfAoGADAcEh2bdsrDhwhXtVi1L3cFQx1KpN0B07JLr gJzJcDLUrwmlMUmrXR2obDGfVQh46EFMeo/k3IESw2zJUS58FJW+sKZ4noSwRZPq mpBnERKpLOTcWMxUyV8ETsz+9oz71YEMjmR1qvNYAopXf5Yy+4Zq3bgqmMMQyM+K O1PdlCkCgYBmhSl9CVPgVMv1xO8DAHVhM1huIIK8mNFrzMJz+JXzBx81ms1kWSeQ OC/nraaXFTBlqiQsvB8tzr4xZdbaI/QzVLKNAF5C8BJ4ScNlTIx1aZJwyMil8Nzb +0YAsw5Ja+bEZZvEVlAYnd10qRWrPeEY1txLMmX3wDa+JvJL7fmuBgIUZoXsJnzs +sqSEhA35Le2kC4Y1/A= -----END DSA PRIVATE KEY----- ' username: sync category: ssh contributor: ztgrace, hdmoore default_port: 22 name: Array Networks vxAG references: - path_to_url - path_to_url ```
/content/code_sandbox/creds/ssh_key/array_networks_vxag.yml
yaml
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
522
```yaml auth: credentials: - password: '-----BEGIN RSA PRIVATE KEY----- MIICWAIBAAKBgGdlD7qeGU9f8mdfmLmFemWMnz1tKeeuxKznWFI+6gkaagqjAF10 hIruzXQAik7TEBYZyvw9SvYU6MQFsMeqVHGhcXQ5yaz3G/eqX0RhRDn5T4zoHKZa your_sha256_hash GSZrnBieX2pdjsQ55/AJA/HF3oJWTRysYWi0nmJUmm41eDV8oRxXl2qFAIqCgeBQ BWA4SzGA77/ll3cBfKzkG1Q3OiVG/YJPOYLp7127zh337hhHZyzTiSjMPFVcanrg your_sha256_hash iYZd6xnZeZugaX51gQzKgN1QJ1y2sfTfLV6AwsPnieo7+vw2yk+Hl1i5uG9+XkTs Ry45AkEAkk0MPL5YxqLKwH6wh2FHytr1jmENOkQu97k2TsuX0CzzDQApIY/eFkCj QAgkI282MRsaTosxkYeG7ErsA5BJfwJAMOXYbHXp26PSYy4BjYzz4ggwf/dafmGz ebQs+HXa8xGOreroPFFzfL8Eg8Ro0fDOi1lF7Ut/w330nrGxw1GCHQJAYtodBnLG your_sha256_hash 86DC8q8p2OTzYwJANXzRM0SGTqSDMnnid7PGlivaQqfpPOx8MiFR/cGr2dT1HD7y x6f/85mMeTqamSxjTJqALHeKPYWyzeSnUrp+Eg== -----END RSA PRIVATE KEY----- ' username: root category: ssh contributor: ztgrace default_port: 22 name: Exagrid references: - path_to_url ```
/content/code_sandbox/creds/ssh_key/exagrid.yml
yaml
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
527
```yaml auth: credentials: - password: '-----BEGIN RSA PRIVATE KEY----- MIICWwIBAAKBgQDBEh0OUdoiplc0P+XW8VPu57etz8O9eHbLHkQW27EZBEdXEYxr MOFXi+PkA0ZcNDBRgjSJmHpo5WsPLwj/L3/L5gMYK+yeqsNu48ONbbqzZsFdaBQ+ IL3dPdMDovYo7GFVyXuaWMQ4hgAJEc+kk1hUaGKcLENQf0vEyt01eA/k6QIBIwKB your_sha256_hash CyTcztDy1I0stH8j0zts+DpSbYZnWKSb5hxhl/w96yNYPUJaTatgcPB46xOBDsgv 4Lf4GGt3gsQFvuTUArIf6MCJiUn4AQA9Q96QyCH/g4mdiwJBAPHdYgTDiQcpUAbY SanIpq7XFeKXBPgRbAN57fTwzWVDyFHwvVUrpqc+SSwfzhsaNpE3IpLD9RqOyEr6 your_sha256_hash 93gCvQORq4dpApJYZxhigY4k/f46BlU1AkAbpEW3Zs3U7sdRPUo/SiGtlOyO7LAc WcMzmOf+vG8+xesCDOJwIj7uisaIsy1/cLXHdAPzhBwDCQDyoDtnGty7AkEAnaUP your_sha256_hash 7GzJqxN8SGwqhIiK3wJAOQ2Hm068EicG5WQoS+8+KIE/SVHWmFDvet+f1vgDchvT uPa5zx2eZ2rxP1pXHAdBSgh799hCF60eZZtlWnNqLg== -----END RSA PRIVATE KEY----- ' username: mateidu category: ssh contributor: ztgrace, hdmoore default_port: 22 name: Ceragon FibeAir IP-10 references: - path_to_url - path_to_url ```
/content/code_sandbox/creds/ssh_key/ceragon-fibeair.yml
yaml
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
555
```yaml auth: credentials: - password: '-----BEGIN DSA PRIVATE KEY----- MIIBugIBAAKBgQCsCgcOw+DgNR/7g+IbXYdOEwSB3W0o3l1Ep1ibHHvAtLb6AdNW Gq47/UxY/rX3g2FVrVCtQwNSZMqkrqALQwDScxeCOiLMndCj61t3RxU3IOl5c/Hd yhGh6JGPdzTpgf8VhJIZnvG+0NFNomYntqYFm0y11dBQPpYbJE7Tx1t/lQIVANHJ rJSVVkpcTB4XdtR7TfO317xVAoGABDytZN2OhKwGyJfenZ1Ap2Y7lkO8V8tOtqX+ t0LkViOi2ErHJt39aRJJ1lDRa/3q0NNqZH4tnj/bh5dUyNapflJiV94N3637LCzW cFlwFtJvD22Nx2UrPn+YXrzN7mt9qZyg5m0NlqbyjcsnCh4vNYUiNeMTHHW5SaJY TeYmPP8CgYAjEe5+0m/TlBtVkqQbUit+s/g+eB+PFQ+raaQdL1uztW3etntXAPH1 MjxsAC/vthWYSTYXORkDFMhrO5ssE2rfg9io0NDyTIZt+VRQMGdi++dH8ptU+ldl 2ZejLFdTJFwFgcfXz+iQ1mx6h9TPX1crE1KoMAVOj3yKVfKpLB1EkAIUCsG3dIJH SzmJVCWFyVuuANR2Bnc= -----END DSA PRIVATE KEY----- ' username: root category: ssh contributor: ztgrace, hdmoore default_port: 22 name: Loadbalancer.org Enterprise VA references: - path_to_url - path_to_url ```
/content/code_sandbox/creds/ssh_key/loadbalancer.org_enterprise_va.yml
yaml
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
536
```yaml auth: credentials: - password: '-----BEGIN DSA PRIVATE KEY----- MIIBuwIBAAKBgQDdwCE68iTEMjimYwJMvpkP/KThyJbuKvKc5kdKqLSmi5tssnuW tD2NqzmkEQM4uxD4XgV26k2/GvE6x4RlyOT+xlB2iYaOR4RJ8PuU8ALz+9i+y3D8 MTMY/6y3Ef41frizLFXiVVo8CXFL/N8sz16FYytIayJvkSy3rkzPoE8pRwIVAPmA F1excCJPPVq3MyDfEMUXXOWjAoGAJS8ukwjJTgTNCHD7Lz//WxIw49DPGGWs3are GpjtiGjVD2Lff7CLCzkH8SI/JsgytUzqfDckSXqe1eWiAhuH90Pl5LZZi83Vp97I 721riAF3taKYxtk+vWIcXx2a/Fp+z+LaQoMqjOLh5lCq35wc0EPb5FFFrGaFFzNm your_sha256_hash pBNliaD185UjCEsjPiudhGil/j4Zt/+VY3aGOLoi8kqXBBc8ZAML9bbkXpyhQhMg wiywx3ciFmvSn2UAin8yurStYPQxtXauZN5PYbdwCHPS7ApIStdpMAIVAJ+eePIA Azb0ux287wRfcfdbjlDM -----END DSA PRIVATE KEY----- ' username: root category: ssh contributor: ztgrace, hdmoore default_port: 22 name: Monroe Electronics R189 One-Net references: - path_to_url - path_to_url ```
/content/code_sandbox/creds/ssh_key/monroe_electronics_r189.yml
yaml
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
460
```yaml auth: credentials: - password: '----BEGIN DSA PRIVATE KEY----- MIIBuwIBAAKBgQDKuRHCBXXwoyWpMkJz/wQafaHOpqWmVYLn9GZ6eQuNLcIhtZQE kCWZTNajgf4ZAVmHgQh1JHDixJ1V0mcweti/lvyxiqHap7IkD0a+ewAOoz3OpjQZ 3ox2ovHEnQJfZ/9LNiEI3XK8TPAj6trhMn5tCdwFei6228a+TYBOccTPgwIVAKYW T8ztHHaN7Gwn0I6keQfBSNw1AoGAHYNfKAcqf7Y4wyoVoZpr/h21SETpEaksQb7h GRJnFpYN/JiyE9W8nX6UqLv1eKyOXLccAnyda0a+uqcOhsAq8+H15slZYa4+065L ckPfs0V4cpxeMHTT1hK4TR2/LRpUjhYjgXFE5aLl91f5Gug5HemUK2S0BWh/oI38 k2WfNh0CgYEArsJgp7RLPOsCeLqoia/eljseBFVDazO5Q0ysUotTw9wgXGGVWREw m8wNggFNb9eCiBAAUfVZVfhVAtFT0pBf/eIVLPXyaMw3prBt7LqeBrbagODc3WAA dMTPIdYYcOKgv+YvTXa51zG64v6pQOfS8WXgKCzDl44puXfYeDk5lVQCFAPfgalL +FT93tofXMuNVfeQMLJl -----END DSA PRIVATE KEY----- ' username: cluster category: ssh contributor: ztgrace, hdmoore default_port: 8002 name: Barracuda Load Balancer ADC VM references: - path_to_url - path_to_url ```
/content/code_sandbox/creds/ssh_key/barracuda_load_balancer.yml
yaml
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
522
```python import redis import pickle # based on path_to_url class RedisQueue(object): """Simple Queue with Redis Backend""" def __init__(self, name, namespace='queue', **redis_kwargs): """The default connection parameters are: host='localhost', port=6379, db=0""" self.__db= redis.Redis(**redis_kwargs) self.key = '%s:%s' %(namespace, name) def qsize(self): """Return the approximate size of the queue.""" return self.__db.llen(self.key) def empty(self): """Return True if the queue is empty, False otherwise.""" return self.qsize() == 0 def put(self, item): """Put item into the queue.""" self.__db.rpush(self.key, pickle.dumps(item)) def get(self, block=True, timeout=None): """Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available.""" if block: item = self.__db.blpop(self.key, timeout=timeout) else: item = self.__db.lpop(self.key) if item: item = item[1] return pickle.loads(item) def get_nowait(self): """Equivalent to get(False).""" return self.get(False) def ping(self): self.__db.ping() def delete(self): self.__db.delete(self.key) self.__db.flushdb() ```
/content/code_sandbox/changeme/redis_queue.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
322
```python __all__ = ['core', 'version', 'scan_engine'] ```
/content/code_sandbox/changeme/__init__.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
15
```python class Cred(object): def __init__(self, cdict): self.name = cdict['name'] # fingerprint # auth self.credentials = cdict['auth']['credentials'] self.csrf = cdict['auth']['csrf'] self.headers = cdict['auth']['headers'] self.username = cdict['auth']['username'] self.password = cdict['auth']['password'] self.b64 = cdict['auth']['base64'] self.success = cdict['auth']['success'] ```
/content/code_sandbox/changeme/cred.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
112
```python #!/usr/bin/env python import changeme.core import os try: # Python 3 from urllib.parse import unquote_plus except ImportError: # Python 2 from urllib import unquote_plus import yaml cli_prompt = input try: cli_prompt = raw_input except NameError: pass http_schema = { 'auth': { 'type': 'dict', 'required': True, 'schema': { 'credentials': { 'type': 'list', 'required': True, 'schema': { 'type': 'dict', 'schema': { 'username': { 'type': ['string', 'integer'], 'nullable': True, 'required': True, }, 'password': { 'type': ['string', 'integer'], 'nullable': True, 'required': True, }, 'ref': {'type': 'string', 'required': False}, 'raw': {'type': 'string', 'required': False}, } } }, 'headers': { 'type': 'list', 'required': False, 'schema': { 'type': 'dict' } }, 'csrf': { 'type': 'string', 'nullable': True, 'required': False, }, 'form_data': { 'type': 'boolean', 'nullable': False, 'required': False, }, 'post': { 'type': 'dict', 'allow_unknown': True, 'schema': { 'username': {'type': 'string', 'required': True}, 'password': {'type': 'string', 'required': True}, } }, 'get': { 'type': 'dict', 'allow_unknown': True, 'schema': { 'username': {'type': 'string', 'required': True}, 'password': {'type': 'string', 'required': True}, } }, 'sessionid': { 'type': 'string', 'nullable': True, 'required': False, }, 'base64': { 'type': 'boolean', 'nullable': False, 'required': False, }, 'success': { 'type': 'dict', 'schema': { 'body': { 'type': 'list', 'required': False }, 'status': {'type': 'integer', 'required': True}, }, }, 'type': { 'type': 'string', 'regex': 'post|basic_auth|get|raw_post', 'required': True }, 'url': { 'type': 'list', 'required': True, 'schema': {'type': 'string'} }, } }, 'category': {'type': 'string', 'required': True}, 'contributor': {'type': 'string', 'required': True}, 'fingerprint': { 'type': 'dict', 'required': True, 'schema': { 'body': {'type': 'list', 'required': False}, 'server_header': {'type': 'string', 'required': False}, 'cookie': { 'type': 'list', 'required': False, 'schema': { 'type': 'dict' }, }, 'headers': { 'type': 'list', 'required': False, 'schema': { 'type': 'dict' } }, 'status': {'type': 'integer', 'required': True}, 'basic_auth_realm': { 'type': 'string', 'nullable': True, 'required': False, }, 'url': { 'type': 'list', 'required': True, 'schema': {'type': 'string'} }, }, }, 'default_port': {'type': 'integer', 'required': True}, 'name': {'type': 'string', 'required': True}, 'ssl': {'type': 'boolean', 'required': True}, 'references': {'type': 'list', 'required': False}, 'versions': {'type': 'list', 'required': False}, 'protocol': {'type': 'string', 'required': False}, } def mkcred(): """ TODO: - move credentials under auth - move auth url under auth - move success under auth - move auth url under auth - move type under auth """ parameters = dict() auth_types = ['post', 'basic_auth', 'get', 'raw_post'] def get_data(field, prompt, boolean=False, integer=False): result = cli_prompt(prompt).strip() if boolean and result.lower() == 'y': result = True elif boolean: result = False if integer: result = int(result) parameters[field] = result get_data('contributor', 'Your name or handle: ') get_data('name', 'Name of service (JBoss, Tomcat): ') get_data('protocol', 'Protocol of service (http, ssh, ftp): ') get_data('category', 'Category of service (general, printer, phone): ') get_data('default_port', 'Default port: ', integer=True) get_data('ssl', 'Does the service use ssl (y/n): ', boolean=True) # Fingerprint ############################################################################### fp = dict() # Fingerprint url is confiured as a list so we can have more than one path path = cli_prompt('Path to the fingerprint page (/index.php): ') path_list = list() path_list.append(path) fp['url'] = path_list fp_status = cli_prompt('HTTP status code of fingerprint (401, 200): ') fp_body = cli_prompt('Unique string in the fingerprint page (Welcome to ***): ') server_header = cli_prompt('Server header (if unique): ') basic_auth_realm = cli_prompt('Basic Auth Realm: ') fp['status'] = int(fp_status) if fp_body: b = list() b.append(fp_body) fp['body'] = b if basic_auth_realm: fp['basic_auth_realm'] = basic_auth_realm if server_header: fp['server_header'] = server_header parameters['fingerprint'] = fp # Authentication ############################################################################### auth = dict() headers = list() auth_urls = list() url = cli_prompt('Authentication URL (/login.php): ') auth_urls.append(url) auth['url'] = auth_urls while True: t = cli_prompt('Type of authentication method (post, basic_auth, get, raw_post): ') if t in auth_types: auth['type'] = t break else: print('Invalid auth type') if auth['type'] == 'post' or auth['type'] == 'get': form = dict() form['username'] = cli_prompt('Name of username field: ') form['password'] = cli_prompt('Name of password field: ') form_params = cli_prompt('Post parameters, query string or raw post (json, xml): ') if form_params: form_params = unquote_plus(form_params) # decode the parameters for f in form_params.split('&'): fname = f.split('=')[0] fvalue = f.split('=')[1] if fname == form['username'] or fname == form['password']: continue else: form[fname] = fvalue if auth['type'] == 'raw_post': form['raw'] = form_params auth[auth['type']] = form while True: header = cli_prompt('Pleae enter any custom header needed. Hit enter if done or not needed \n Example: Content-Type: application/json: ') if len(header) > 0: if len(header.split(':')) == 2: h = header.split(':') header = {h[0]: h[1]} headers.append(header) else: print('Invalid header. Headers must be in the format "Header_name: header_value"\n') else: break csrf = cli_prompt('Name of csrf field: ') if csrf: auth['csrf'] = csrf sessionid = cli_prompt('Name of session cookie: ') if sessionid: auth['sessionid'] = sessionid creds = list() num_creds = cli_prompt('How many default creds for this service (1, 2, 3): ') for i in range(0, int(num_creds)): user = cli_prompt('Username %i: ' % (i + 1)) passwd = cli_prompt('Password %i: ' % (i + 1)) if auth['type'] == 'raw_post': raw = cli_prompt('Raw post %i: ' % (i + 1)) creds.append({'username': user, 'password': passwd, 'raw': raw}) else: creds.append({'username': user, 'password': passwd}) auth['credentials'] = creds auth['headers'] = headers success = dict() success['status'] = 200 success['body'] = list() success['body'].append(cli_prompt('Unique string in page of a successful login (Logout</a>): ')) auth['success'] = success parameters['auth'] = auth print() fname = parameters['name'].lower().replace(' ', '_').replace('/', '_') + '.yml' print('Writing config to %s' % fname) cdir = os.path.join('creds', parameters['protocol'], parameters['category']) if not os.path.isdir(cdir): os.makedirs(cdir) with open(os.path.join(cdir, fname), 'w') as fout: fout.write(yaml.dump(parameters, default_flow_style=False)) print(yaml.dump(parameters, default_flow_style=False)) changeme.core.validate_cred(parameters, fname, parameters['category']) ```
/content/code_sandbox/changeme/schema.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
2,191
```python __version__ = '1.2.3' contributors = [ "ztgrace", "the-c0d3r", "Graph-X", "AlessandroZ", "ThomasTJ", "Alistair Chapman", "John Van de Meulebrouck Brendgard", "network23", "decidedlygray", "Joe Testa", "Chandrapal", "Naglis Jonaitis", "Samuel Henrique", "sil3ntcor3", ] ```
/content/code_sandbox/changeme/version.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
117
```python from libnmap.parser import NmapParser as np import logging from netaddr import IPNetwork from netaddr.core import AddrFormatError import re from os.path import isfile import shodan import socket class Target(object): def __init__(self, host=None, port=None, protocol=None, url=None): self.host = host if port: port = re.sub(r'\D','',str(port)) if 0 < int(port) < 65535: self.port = int(port) else: #just disregard the port for now. self.port = None else: self.port = None self.protocol = protocol self.url = url self.ip = None def __eq__(self, other): return self.__dict__ == other.__dict__ def __hash__(self): return id(self) def __repr__(self): return self.__str__() def __str__(self): target = self if self.host: target = self.host if self.port: target += ":%s" % self.port if self.protocol: target = "%s://" % self.protocol + target if self.url: target += self.url return str(target) def get_ip(self): if self.ip is None: regex = re.compile(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$') result = regex.match(self.host) if not result: self.ip = socket.gethostbyname(self.host) else: self.ip = self.host return self.ip @staticmethod def parse_target(target): logger = logging.getLogger('changeme') targets = set() if isfile(target): try: # parse nmap report = np.parse_fromfile(target) logger.info('Loaded %i hosts from %s' % (len(report.hosts), target)) for h in report.hosts: for s in h.services: targets.add(Target(host=h.address, port=s.port)) except: # parse text file with open(target, 'r') as fin: for line in fin: res = Target._parse_target_string(line) for t in res: targets.add(t) else: targets = Target._parse_target_string(target) return targets @staticmethod def _parse_target_string(target): logger = logging.getLogger('changeme') logger.debug('Parsing target %s' % target) target = target.strip().rstrip('/') targets = set() try: for ip in IPNetwork(target).iter_hosts(): #(covers IP or cidr) #3,4 targets.add(Target(host=str(ip))) except AddrFormatError: if len(target.split(':')) == 3: # mysql://127.0.0.1:3306 protocol = target.split(':')[0] host = target.split(':')[1].replace('//', '') port = target.split(':')[2] targets.add(Target(host=host, port=port, protocol=protocol)) elif "://" in target: # snmp://127.0.0.1 protocol = target.split(':')[0] host = target.split(':')[1].replace('//', '') targets.add(Target(host=host, protocol=protocol)) elif ":" in target: # 127.0.0.1:8080 host = target.split(':')[0] port = target.split(':')[1] targets.add(Target(host=host, port=port)) else: targets.add(Target(host=target)) return targets @staticmethod def get_shodan_targets(config): logger = logging.getLogger('changeme') targets = set() api = shodan.Shodan(config.shodan_key) results = api.search(config.shodan_query) logger.debug("shodan results: %s" % results) for r in results['matches']: targets.add(Target(host=r['ip_str'])) return targets ```
/content/code_sandbox/changeme/target.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
885
```python import csv from copy import deepcopy from datetime import datetime import jinja2 import json import logging import os import re import sys from tabulate import tabulate class Report: def __init__(self, queue, output): self.results = self._convert_q2list(queue) self.output = output self.logger = logging.getLogger('changeme') def render_csv(self,): fname = self.output if not re.match(r'.*\.csv$', fname): fname += ".csv" with open(fname, 'w') as fout: fieldnames = ["name", "username", "password", "target"] writer = csv.DictWriter( fout, quoting=csv.QUOTE_ALL, fieldnames=fieldnames, extrasaction='ignore' ) writer.writeheader() writer.writerows(self.results) self.logger.critical("%i credentials written to %s" % (len(self.results), fname)) def render_json(self): # convert the Target classes to a string so it can be json'd res = deepcopy(self.results) for r in res: t = r['target'] r['target'] = str(t) results = dict() results["results"] = res j = json.dumps(results) fname = self.output if not re.match(r'.*\.json$', fname): fname += ".json" with open(fname, 'w') as fout: fout.write(j) self.logger.critical("%i credentials written to %s" % (len(self.results), fname)) def print_results(self): if len(self.results) > 0: results = deepcopy(self.results) for r in results: if 'http' in r['target'].protocol: r['evidence'] = '' print("") print("") self.logger.critical('Found %i default credentials' % len(self.results)) print("") print(tabulate(results, headers={'name': 'Name', 'username': 'Username', 'password': 'Password', 'target': 'Target', 'evidence': 'Evidence'})) print("") else: print("No default credentials found") def render_html(self): template_loader = jinja2.FileSystemLoader(searchpath=self.get_template_path()) template_env = jinja2.Environment(loader=template_loader) report_template = template_env.get_template('report.j2') cli = ' '.join(sys.argv) timestamp = datetime.now() report = report_template.render({'found': self.results, 'cli': cli, 'timestamp': timestamp}) fname = self.output if not re.match(r'.*\.html$', fname): fname += ".html" with open(fname, 'w') as fout: fout.write(report) self.logger.critical("%i credentials written to %s" % (len(self.results), fname)) @staticmethod def get_template_path(): PATH = os.path.dirname(os.path.abspath(__file__)) template_path = os.path.join(PATH, 'templates') return template_path def _convert_q2list(self, q): items = list() while not q.qsize() == 0: i = q.get() items.append(i) # Restore queue for i in items: q.put(i) return items ```
/content/code_sandbox/changeme/report.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
717
```python import argparse from cerberus import Validator from changeme.redis_queue import RedisQueue import logging from logutils import colorize import os import re import redis from .report import Report import requests from requests import ConnectionError from requests.packages.urllib3.exceptions import InsecureRequestWarning from .scan_engine import ScanEngine from . import schema import sys from . import version import yaml PERSISTENT_QUEUE = "data.db" # Instantiated in the scan_engine class def banner(version): b = """ ##################################################### # _ # # ___| |__ __ _ _ __ __ _ ___ _ __ ___ ___ # # / __| '_ \ / _` | '_ \ / _` |/ _ \ '_ ` _ \ / _ \\ # # | (__| | | | (_| | | | | (_| | __/ | | | | | __/ # # \___|_| |_|\__,_|_| |_|\__, |\___|_| |_| |_|\___| # # |___/ # # v%s # # Default Credential Scanner by @ztgrace # ##################################################### """ % version return b def main(): print(banner(version.__version__)) args = parse_args() init_logging(args['args'].verbose, args['args'].debug, args['args'].log) config = Config(args['args'], args['parser']) if not config.noversion: check_version() creds = load_creds(config) s = None if config.mkcred: schema.mkcred() quit() if config.contributors: print_contributors(creds) quit() if config.dump: print_creds(creds) quit() logger = logging.getLogger('changeme') if not config.validate: check_for_interrupted_scan(config) s = ScanEngine(creds, config) try: s.scan() except IOError: logger.debug('Caught IOError exception') report = Report(s.found_q, config.output) report.print_results() if config.output and ".json" in config.output or config.output and config.oa: report.render_json() if config.output and ".csv" in config.output or config.output and config.oa: report.render_csv() if config.output and ".html" in config.output or config.output and config.oa: report.render_html() if (config.output and not ('json' in config.output or 'csv' in config.output or 'html' in config.output)) and not config.oa: logger.error('Only JSON, CSV and HTML are the only supported output types.') return s def init_logging(verbose=False, debug=False, logfile=None): """ Logging levels: - Critical: Default credential found - Error: error in the program - Warning: Verbose data - Info: more verbose - Debug: Extra info for debugging purposes """ # Set up our logging object logger = logging.getLogger('changeme') if debug: logger.setLevel(logging.DEBUG) elif verbose: logger.setLevel(logging.INFO) else: logger.setLevel(logging.WARNING) if logfile: # Create file handler which logs even debug messages ####################################################################### fh = logging.FileHandler(logfile) # create formatter and add it to the handler formatter = logging.Formatter( '[%(asctime)s][%(levelname)s] %(message)s') fh.setFormatter(formatter) logger.addHandler(fh) # Set up the StreamHandler so we can write to the console ########################################################################### # create console handler with a higher log level ch = colorize.ColorizingStreamHandler(sys.stdout) # set custom colorings: ch.level_map[logging.DEBUG] = [None, 2, False] ch.level_map[logging.INFO] = [None, 'white', False] ch.level_map[logging.WARNING] = [None, 'yellow', False] ch.level_map[logging.ERROR] = [None, 'red', False] ch.level_map[logging.CRITICAL] = [None, 'green', False] if debug: formatter = logging.Formatter('[%(asctime)s][%(module)s][%(funcName)s] %(message)s', datefmt='%H:%M:%S') else: formatter = logging.Formatter('[%(asctime)s] %(message)s', datefmt='%H:%M:%S') ch.setFormatter(formatter) logger.addHandler(ch) # Adjust the loggers for requests and urllib3 logging.getLogger('requests').setLevel(logging.ERROR) logging.getLogger('urllib3').setLevel(logging.ERROR) requests.packages.urllib3.disable_warnings(InsecureRequestWarning) return logger class Config(object): def __init__(self, args, arg_parser): # Convert argparse Namespace to a dict and make the keys + values member variables of the config class args = vars(args) self.target = None for key in args: setattr(self, key, args[key]) self._validate_args(arg_parser) def _validate_args(self, ap): logger = logging.getLogger('changeme') if (not self.validate and not self.contributors and not self.dump and not self.shodan_query and not self.mkcred and not self.resume) and not self.target: ap.print_help() quit() if self.proxy and re.match('^https?://[0-9\.]+:[0-9]{1,5}$', self.proxy): self.proxy = {'http': self.proxy, 'https': self.proxy} logger.info('Setting proxy to %s' % self.proxy) elif self.proxy: logger.error('Invalid proxy, must be http(s)://x.x.x.x:8080') sys.exit() if self.delay and self.delay != 0: if isinstance(self.delay, int) and 0 <= self.delay <= 1000: logger.debug('Delay is set to %d milliseconds' % self.delay) else: logger.error('Invalid delay type. Delay must be an integer between 0 and 1000. Delay is: %s' % type(self.delay)) # Drop logging level to INFO to see the fingerprint messages if self.fingerprint: logger.setLevel(logging.INFO) if self.verbose: logger.setLevel(logging.INFO) if self.debug or self.validate: logger.setLevel(logging.DEBUG) self.useragent = {'User-Agent': self.useragent} if self.useragent else {} if ',' in self.protocols: self.protocols = self.protocols.split(',') if self.all: self.protocols = 'all' logger.debug(self.protocols) if self.output and which('phantomjs') is None: logger.warning('phantomjs is not in your path, screenshots will not work') def _file_exists(self, f): if not os.path.isfile(f): self.logger.error("File %s not found" % f) sys.exit() def parse_args(): ap = argparse.ArgumentParser(description='Default credential scanner v%s' % version.__version__) ap.add_argument('--all', '-a', action='store_true', help='Scan for all protocols', default=False) ap.add_argument('--category', '-c', type=str, help='Category of default creds to scan for', default=None) ap.add_argument('--contributors', action='store_true', help='Display cred file contributors') ap.add_argument('--debug', '-d', action='store_true', help='Debug output') ap.add_argument('--delay', '-dl', type=int, help="Specify a delay in milliseconds to avoid 429 status codes default=500", default=500) ap.add_argument('--dump', action='store_true', help='Print all of the loaded credentials') ap.add_argument('--dryrun', action='store_true', help='Print urls to be scan, but don\'t scan them') ap.add_argument('--fingerprint', '-f', action='store_true', help='Fingerprint targets, but don\'t check creds', default=False) ap.add_argument('--fresh', action='store_true', help='Flush any previous scans and start fresh', default=False) ap.add_argument('--log', '-l', type=str, help='Write logs to logfile', default=None) ap.add_argument('--mkcred', action='store_true', help='Make cred file', default=False) ap.add_argument('--name', '-n', type=str, help='Narrow testing to the supplied credential name', default=None) ap.add_argument('--noversion', action='store_true', help='Don\'t perform a version check', default=False) ap.add_argument('--proxy', '-p', type=str, help='HTTP(S) Proxy', default=None) ap.add_argument('--output', '-o', type=str, help='Name of result file. File extension determines type (csv, html, json).', default=None) ap.add_argument('--oa', action='store_true', help='Output results files in csv, html and json formats', default=False) ap.add_argument('--protocols', type=str, help="Comma separated list of protocols to test: http,ssh,ssh_key. Defaults to http.", default='http') ap.add_argument('--portoverride', action='store_true', help='Scan all protocols on all specified ports', default=False) ap.add_argument('--redishost', type=str, help='Redis server', default='localhost') ap.add_argument('--redisport', type=str, help='Redis server', default='6379') ap.add_argument('--resume', '-r', action='store_true', help='Resume previous scan', default=False) ap.add_argument('--shodan_query', '-q', type=str, help='Shodan query', default=None) ap.add_argument('--shodan_key', '-k', type=str, help='Shodan API key', default=None) ap.add_argument('--ssl', action='store_true', help='Force cred to SSL and fall back to non-SSL if an SSLError occurs', default=False) ap.add_argument('--threads', '-t', type=int, help='Number of threads, default=10', default=10) ap.add_argument('--timeout', type=int, help='Timeout in seconds for a request, default=10', default=10) ap.add_argument('--useragent', '-ua', type=str, help="User agent string to use", default=None) ap.add_argument('--validate', action='store_true', help='Validate creds files', default=False) ap.add_argument('--verbose', '-v', action='store_true', help='Verbose output', default=False) # Hack to get the help to show up right cli = ' '.join(sys.argv) if "-h" in cli or "--help" in cli: ap.add_argument('target', type=str, help='Target to scan. Can be IP, subnet, hostname, nmap xml file, text file or proto://host:port', default=None) # initial parse to see if an option not requiring a target was used args, unknown = ap.parse_known_args() if not args.dump and not args.contributors and not args.mkcred and not args.resume and not args.shodan_query and not args.validate: ap.add_argument('target', type=str, help='Target to scan. Can be IP, subnet, hostname, nmap xml file, text file or proto://host:port', default=None) args = ap.parse_args() return {'args': args, 'parser': ap} def get_protocol(filename): parts = filename.split(os.path.sep) cred_index = 0 for p in parts: if p == 'creds': break cred_index += 1 return parts[cred_index + 1] def load_creds(config): # protocol is based off of the directory and category is a field in the cred file. That way you can # have default creds across protocols for a single device like a printer logger = logging.getLogger('changeme') creds = list() total_creds = 0 cred_names = list() cred_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'creds') logger.debug('cred_path: %s' % cred_path) protocols = [proto for proto in os.walk(cred_path)][0][1] for root, dirs, files in os.walk(cred_path): for fname in files: f = os.path.join(root, fname) protocol = get_protocol(f) if is_yaml(f): parsed = parse_yaml(f) if parsed: if parsed['name'] in cred_names: pass elif validate_cred(parsed, f, protocol): parsed['protocol'] = protocol # Add the protocol after the schema validation if in_scope(config.name, config.category, parsed, protocols): total_creds += len(parsed['auth']['credentials']) creds.append(parsed) cred_names.append(parsed['name']) logger.debug('Loaded %s' % parsed['name']) print('Loaded %i default credential profiles' % len(creds)) print('Loaded %i default credentials\n' % total_creds) creds return creds def validate_cred(cred, f, protocol): valid = True if protocol == 'http': v = Validator() valid = v.validate(cred, schema.http_schema) for e in v.errors: logging.getLogger('changeme').error("[validate_cred] Validation Error: %s, %s - %s" % (f, e, v.errors[e])) # TODO: implement schema validators for other protocols return valid def parse_yaml(f): logger = logging.getLogger('changeme') with open(f, 'r') as fin: raw = fin.read() try: parsed = yaml.safe_load(raw) except Exception as e: logger.error("[parse_yaml] %s is not a valid yaml file" % f) logger.debug(e) return None return parsed def is_yaml(f): isyaml = False try: isyaml = os.path.basename(f).split('.')[1] == 'yml' except: pass return isyaml def in_scope(name, category, cred, protocols): add = True if name: names = name.split(',') found = False for n in names: if n.lower() in cred['name'].lower(): found = True if found is False: add = False if category and not cred['category'] == category: add = False elif cred['protocol'] not in protocols: add = False return add def print_contributors(creds): contributors = set() for cred in creds: cred_contributors = cred['contributor'].split(', ') for c in cred_contributors: contributors.add(c) for c in version.contributors: contributors.add(c) print("Thank you to our contributors!") for i in sorted(contributors, key=str.lower): print(i) print() def print_creds(creds): for cred in creds: print("\n%s (%s)" % (cred['name'], cred['category'])) for i in cred['auth']['credentials']: print(" - %s:%s" % (i['username'], i['password'])) def check_for_interrupted_scan(config): logger = logging.getLogger('changeme') if config.fresh: logger.debug("Forcing a fresh scan") remove_queues() elif config.resume: logger.debug("Resuming previous scan") return fp = RedisQueue('fingerprint') scanners = RedisQueue('scanners') fp_qsize = 0 scanners_qsize = 0 logger.debug('scanners: %s, fp: %s' % (scanners_qsize, fp_qsize)) try: fp_qsize = fp.qsize() except redis.exceptions.ConnectionError: pass try: scanners_qsize = scanners.qsize() except redis.exceptions.ConnectionError: pass if fp_qsize > 0 or scanners_qsize > 0: if not prompt_for_resume(config): remove_queues() if fp_qsize == 0 and scanners_qsize == 0: # Clear the found queue if there's no fingerprints or scanners in the queues try: logger.debug('Clearing found_q') found_q = RedisQueue('found_q') found_q.delete() except Exception as e: logger.debug('Exception: %s: %s' % (type(e).__name__, e.__str__().replace('\n', '|'))) pass def prompt_for_resume(config): logger = logging.getLogger('changeme') logger.error('A previous scan was interrupted. Type R to resume or F to start a fresh scan') answer = '' while not (answer == 'R' or answer == 'F'): prompt = '(R/F)> ' answer = '' try: answer = raw_input(prompt) except NameError: answer = input(prompt) if answer.upper() == 'F': logger.debug("Forcing a fresh scan") elif answer.upper() == 'R': logger.debug("Resuming previous scan") config.resume = True return config.resume def remove_queues(): logger = logging.getLogger('changeme') try: os.remove(PERSISTENT_QUEUE) logger.debug("%s removed" % PERSISTENT_QUEUE) except OSError: logger.debug("%s didn't exist" % PERSISTENT_QUEUE) pass # Clear Redis queues = ['fingerprint', 'scanners', 'found_q'] for q in queues: logger.debug('Removing %s RedisQueue' % q) r = RedisQueue(q) try: r.delete() logger.debug("%s Redis queue removed" % q) except: logger.debug("%s Redis queue exception" % q) pass def check_version(): logger = logging.getLogger('changeme') try: res = requests.get('path_to_url timeout=2) except ConnectionError: logger.debug("Unable to retrieve latest changeme version.") return latest = res.text.split('\n')[0].split(' = ')[1].replace("'", '') if not version.__version__ == latest: logger.warning('Your version of changeme is out of date. Local version: %s, Latest: %s' % (str(version.__version__), latest)) # copied from path_to_url def which(program): import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None ```
/content/code_sandbox/changeme/core.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
4,100
```python import logging import multiprocessing as mp import redis from changeme.redis_queue import RedisQueue import pickle from .scanners.ftp import FTP from .scanners.http_fingerprint import HttpFingerprint from .scanners.memcached import MemcachedScanner from .scanners.mongo import Mongodb from .scanners.mssql import MSSQL from .scanners.mysql import MySQL from .scanners.postgres import Postgres from .scanners.redis_scanner import RedisScanner from .scanners.snmp import SNMP from .scanners.ssh import SSH from .scanners.ssh_key import SSHKey from .scanners.telnet import Telnet from .scanners.http_fingerprint import HttpFingerprint from .target import Target import time try: # Python 2 from Queue import Queue except: # Python 3 from queue import Queue class ScanEngine(object): def __init__(self, creds, config): self.creds = creds self.config = config self.logger = logging.getLogger('changeme') self.scanners = self._get_queue('scanners') self.total_scanners = 0 self.targets = set() self.fingerprints = self._get_queue('fingerprints') self.total_fps = 0 self.found_q = self._get_queue('found_q') def scan(self): # Phase I - Fingerprint ###################################################################### if not self.config.resume: self._build_targets() if self.config.dryrun: self.dry_run() num_procs = self.config.threads if self.fingerprints.qsize() > self.config.threads else self.fingerprints.qsize() self.logger.debug('Number of procs: %i' % num_procs) self.total_fps = self.fingerprints.qsize() procs = [mp.Process(target=self.fingerprint_targets) for i in range(num_procs)] self._add_terminators(self.fingerprints) for proc in procs: proc.start() for proc in procs: proc.join() self.logger.info('Fingerprinting completed') # Phase II - Scan ###################################################################### # Unique the queue scanners = list() while self.scanners.qsize() > 0: s = self.scanners.get() if s not in scanners: scanners.append(s) for s in scanners: self.scanners.put(s) if not self.config.fingerprint: num_procs = self.config.threads if self.scanners.qsize() > self.config.threads else self.scanners.qsize() self.total_scanners = self.scanners.qsize() self.logger.debug('Starting %i scanner procs' % num_procs) procs = [mp.Process(target=self._scan, args=(self.scanners, self.found_q)) for i in range(num_procs)] self._add_terminators(self.scanners) for proc in procs: self.logger.debug('Starting scanner proc') proc.start() for proc in procs: proc.join() self.logger.info('Scanning Completed') # Hack to address a broken pipe IOError per path_to_url time.sleep(0.1) def _add_terminators(self, q): # Add poison pills for i in range(self.config.threads): q.put(None) def _scan(self, scanq, foundq): while True: remaining = self.scanners.qsize() self.logger.debug('%i scanners remaining' % remaining) try: scanner = scanq.get(block=True) if scanner is None: return except Exception as e: self.logger.debug('Caught exception: %s' % type(e).__name__) continue result = scanner.scan() if result: foundq.put(result) def fingerprint_targets(self): while True: remaining = self.fingerprints.qsize() self.logger.debug('%i fingerprints remaining' % remaining) try: fp = self.fingerprints.get() if type(fp) == bytes: fp = pickle.loads(fp) # Exit process if fp is None: return except Exception as e: self.logger.debug('Caught exception: %s' % type(e).__name__) self.logger.debug('Exception: %s: %s' % (type(e).__name__, e.__str__().replace('\n', '|'))) return if fp.fingerprint(): results = fp.get_scanners(self.creds) if results: for result in results: self.scanners.put(result) else: self.logger.debug('failed fingerprint') self.logger.debug('scanners: %i, %s' % (self.scanners.qsize(), id(self.scanners))) def _build_targets(self): self.logger.debug('Building targets') if self.config.target: self.targets = Target.parse_target(self.config.target) else: self.logger.warning('shodan') self.targets = Target.get_shodan_targets(self.config) # Load set of targets into queue self.logger.debug('%i targets' % len(self.targets)) # If there's only one protocol and the user specified a protocol, override the defaults if len(self.targets) == 1: t = self.targets.pop() if t.protocol: self.config.protocols = t.protocol self.targets.add(t) fingerprints = list() # Build a set of unique fingerprints if 'http' in self.config.protocols or self.config.all: fingerprints = fingerprints + HttpFingerprint.build_fingerprints(self.targets, self.creds, self.config) fingerprints = list(set(fingerprints)) # unique the HTTP fingerprints # Add any protocols if they were included in the targets for t in self.targets: if t.protocol and t.protocol not in self.config.protocols: self.config.protocols += ",%s" % t.protocol self.logger.info('Configured protocols: %s' % self.config.protocols) # scanner_map maps the friendly proto:// name to the actual class name scanner_map = { 'ssh': 'SSH', 'ssh_key': 'SSHKey', 'ftp': 'FTP', 'memcached': 'MemcachedScanner', 'mongodb': 'Mongodb', 'mssql': 'MSSQL', 'mysql': 'MySQL', 'postgres': 'Postgres', 'redis': 'RedisScanner', 'snmp': 'SNMP', 'telnet': 'Telnet', } for target in self.targets: for cred in self.creds: for proto, classname in scanner_map.items(): if cred['protocol'] == proto and (proto in self.config.protocols or self.config.all): t = Target(host=target.host, port=target.port, protocol=proto) fingerprints.append(globals()[classname](cred, t, self.config, '', '')) self.logger.info("Loading creds into queue") for fp in set(fingerprints): self.fingerprints.put(fp) self.total_fps = self.fingerprints.qsize() self.logger.debug('%i fingerprints' % self.fingerprints.qsize()) def dry_run(self): self.logger.info("Dry run targets:") while self.fingerprints.qsize() > 0: fp = self.fingerprints.get() print(fp.target) quit() def _get_queue(self, name): try: # Try for redis r = RedisQueue(name) r.ping() self.logger.debug('Using RedisQueue for %s' % name) return r except redis.ConnectionError: # Fall back to sqlite persistent queue self.logger.debug('Using in-memory queue for %s' % name) m = mp.Manager() q = m.Queue() return q ```
/content/code_sandbox/changeme/scan_engine.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
1,684
```python import responses class MockResponses: tomcat_fp = { 'method': responses.GET, 'url': 'path_to_url 'status': 401, 'adding_headers': { 'Server': 'Apache-Coyote/1.1', 'WWW-Authenticate': 'Basic realm="Tomcat Manager Application'} } tomcat_fp_alt = { 'method': responses.GET, 'url': 'path_to_url 'status': 404, 'adding_headers': { 'Server': 'Apache-Coyote/1.1', 'WWW-Authenticate': 'Basic realm="Tomcat Manager Application'} } tomcat_auth = { 'method': responses.GET, 'url': 'path_to_url 'status': 200, 'body': '<font size="+2">Tomcat Web Application Manager</font>', 'adding_headers': {'Server': 'Apache-Coyote/1.1'} } jboss_fp = { 'method': responses.GET, 'url': 'path_to_url 'status': 200, 'body': '<p>Welcome to the JBoss AS 6 Admin Console.</p><input name="javax.faces.ViewState" value="foobar" />', 'adding_headers': { 'Server': 'Apache-Coyote/1.1', 'Set-Cookie': 'JSESSIONID=foobar' } } jboss_fp_no_csrf = { 'method': responses.GET, 'url': 'path_to_url 'status': 200, 'body': '<p>Welcome to the JBoss AS 6 Admin Console.</p>', 'adding_headers': { 'Server': 'Apache-Coyote/1.1', 'Set-Cookie': 'JSESSIONID=foobar' } } jboss_auth = { 'method': responses.POST, 'url': 'path_to_url 'status': 200, 'body': '<a>Logout</a>', 'adding_headers': {'Server': 'Apache-Coyote/1.1'} } jboss_auth_fail = { 'method': responses.POST, 'url': 'path_to_url 'status': 200, 'body': 'Fail', 'adding_headers': {'Server': 'Apache-Coyote/1.1'} } idrac_fp = { 'method': responses.GET, 'url': 'path_to_url 'status': 200, 'body': '<title>Integrated Dell Remote Access Controller</title>', 'adding_headers': { 'Server': 'Mbedthis-Appweb/2.4.2', 'Content-type': 'text/xml', 'Set-Cookie': '_appwebSessionId_=dffaac7c4fb4e3c4cbd46d3691aeb40f;', }, 'body': '<title>Integrated Dell Remote Access Controller 6 - Express</title>', } idrac_auth = { 'method': responses.POST, 'url': 'path_to_url 'status': 200, 'body': '<title>Integrated Dell Remote Access Controller</title>', 'adding_headers': { 'Server': 'Mbedthis-Appweb/2.4.2', 'Content-type': 'text/xml', 'Set-Cookie': '_appwebSessionId_=dffaac7c4fb4e3c4cbd46d3691aeb40f', }, 'body': '<? xml version="1.0" encoding="UTF-8"?> <root> <status>ok</status> <authResult>0</authResult> <forwardUrl>index.html</forwardUrl> </root>' } zabbix_fp = { 'method': responses.GET, 'url': 'path_to_url 'status': 200, 'body': 'by Zabbix SIA', } zabbix_auth = { 'method': responses.POST, 'url': 'path_to_url 'status': 200, 'body': '<a>Logout</a>', } zabbix_fail = { 'method': responses.POST, 'url': 'path_to_url 'status': 200, 'body': 'foobar', } ipcamera_fp = { 'method': responses.GET, 'url': 'path_to_url 'status': 200, 'body': 'GetXml("login.xml?"+param,OnLoginAckOK,OnLoginAckFail);' } ipcamera_auth = { 'method': responses.GET, 'url': 'path_to_url 'status': 200, 'body': '<?xml version="1.0" encoding="UTF-8" ?><Result><Success>1</Success><UserLevel>0</UserLevel><UserGroup>Admin</UserGroup></Result>' } elasticsearch = { 'method': responses.GET, 'url': 'path_to_url 'status': 200, 'body': """{ "name" : "foo", "cluster_name" : "elasticsearch", "cluster_uuid" : "1C4hbDs6TRetjINxrOKBZw", "version" : { "number" : "5.0.2", "build_hash" : "f6b4951", "build_date" : "2016-11-24T10:07:18.101Z", "build_snapshot" : false, "lucene_version" : "6.2.1" }, "tagline" : "You Know, for Search" }""" } endpoint_protector_fp = { 'method': responses.GET, 'url': 'path_to_url 'status': 200, 'body': 'Endpoint Protector - Reporting and Administration Tool <input name="csrf_token_anon" value="foobar" />', 'adding_headers': { 'Set-Cookie': 'ratool=foobar' } } endpoint_protector_auth = { 'method': responses.POST, 'url': 'path_to_url 'status': 200, 'body': 'Edit Profile</a>', } ```
/content/code_sandbox/changeme/tests/mock_responses.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
1,355
```python import argparse from changeme import core from .core import cli_args from copy import deepcopy import logging import mock def reset_handlers(): logger = logging.getLogger('changeme') logger.handlers = [] core.remove_queues() snmp_args = deepcopy(cli_args) snmp_args['protocols'] = 'snmp' snmp_args['name'] = 'publicprivate' snmp_args['target'] = 'demo.snmplabs.com' @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**snmp_args)) def test_snmp(mock_args): reset_handlers() se = core.main() assert se.found_q.qsize() == 2 snmp_args = deepcopy(cli_args) snmp_args['name'] = 'publicprivate' snmp_args['target'] = 'snmp://demo.snmplabs.com' @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**snmp_args)) def test_snmp_proto(mock_args): reset_handlers() se = core.main() assert se.found_q.qsize() == 2 ```
/content/code_sandbox/changeme/tests/snmp.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
236
```python __all__ = ['core', 'http', 'memcached', 'redis_scanner', 'snmp', 'target'] ```
/content/code_sandbox/changeme/tests/__init__.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
27
```python import argparse from changeme import core from .core import cli_args from copy import deepcopy import logging import mock def reset_handlers(): logger = logging.getLogger('changeme') logger.handlers = [] core.remove_queues() redis_args = deepcopy(cli_args) redis_args['protocols'] = 'redis' redis_args['target'] = '127.0.0.1' @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**redis_args)) def test_redis(mock_args): reset_handlers() se = core.main() assert se.found_q.qsize() == 1 ```
/content/code_sandbox/changeme/tests/redis_scanner.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
131
```python import argparse from changeme import core from .core import cli_args from copy import deepcopy import logging import mock import os logger = logging.getLogger('changeme') def reset_handlers(): logger = logging.getLogger('changeme') logger.handlers = [] core.remove_queues() mongodb_args = deepcopy(cli_args) mongodb_args['target'] = 'mongodb://127.0.0.1' @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**mongodb_args)) def test_mongodb(mock_args): reset_handlers() se = core.main() try: assert se.found_q.qsize() == 1 except Exception as e: # Raise an assertion error if we're in Travis CI and fail if os.environ.get('TRAVIS', None): raise e # Warn if we're not Travis CI else: logger.warning('mongodb failed') ```
/content/code_sandbox/changeme/tests/mongodb.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
195
```python import argparse from changeme import * from copy import deepcopy import mock from nose.tools import * from netaddr import IPAddress cli_args = {'all': False, 'category': None, 'contributors': False, 'debug': True, 'delay': 500, 'dump': False, 'dryrun': False, 'fingerprint': False, 'fresh': True, 'log': None, 'mkcred': False, 'name': None, 'noversion': True, 'output': None, 'oa': False, 'portoverride': False, 'protocols': 'http', 'proxy': None, 'resume': False, 'shodan_query': None, 'shodan_key': None, 'ssl': False, 'target': '127.0.0.1', 'threads': 20, 'timeout': 10, 'useragent': None, 'validate': False, 'verbose': False,} def test_banner(): core.banner(version.__version__) no_args = deepcopy(cli_args) no_args['target'] = None @raises(SystemExit) @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**no_args)) def test_no_args(mock_args): args = core.parse_args() core.init_logging(args['args'].verbose, args['args'].debug, args['args'].log) config = core.Config(args['args'], args['parser']) args = deepcopy(cli_args) args['target'] = '127.0.0.1' @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**args)) def test_target(mock_args): args = core.parse_args() core.init_logging(args['args'].verbose, args['args'].debug, args['args'].log) config = core.Config(args['args'], args['parser']) """ args = deepcopy(cli_args) args['targets'] = '/etc/hosts' args['target'] = None print args @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**args)) def test_targets(mock_args): core.Config() """ args = deepcopy(cli_args) args['contributors'] = True @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**args)) def test_contributors(mock_args): args = core.parse_args() core.init_logging(args['args'].verbose, args['args'].debug, args['args'].log) config = core.Config(args['args'], args['parser']) creds = core.load_creds(config) core.print_contributors(creds) args = deepcopy(cli_args) args['dump'] = True @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**args)) def test_print_creds(mock_args): args = core.parse_args() core.init_logging(args['args'].verbose, args['args'].debug, args['args'].log) config = core.Config(args['args'], args['parser']) creds = core.load_creds(config) core.print_creds(creds) ```
/content/code_sandbox/changeme/tests/core.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
663
```python from changeme.target import Target import os """ 1. nmap.xml 2. targets.txt 3. 127.0.0.1 4. 192.168.1.0/24 5. 192.168.59.139:8080 6. snmp://192.168.59.101 7. mysql://192.168.59.101:33306 """ def test_nmap(): path = os.path.dirname(os.path.abspath(__file__)) nmap = os.path.join(path, "tomcat_nmap.xml") targets = Target.parse_target(nmap) assert len(targets) == 1 t = targets.pop() path = os.path.dirname(os.path.abspath(__file__)) print("target: %s" % t) assert t == Target(host='127.0.0.1', port='8080') def test_targets_file(): target = '/tmp/targets.txt' with open(target, 'w') as fout: fout.write('127.0.0.1\n') fout.write('127.0.0.2:8080\n') targets = Target.parse_target(target) assert len(targets) == 2 for t in targets: if t.host == '127.0.0.1': t1(t) else: t2(t) os.remove(target) def t1(t): assert t == Target(host='127.0.0.1') def t2(t): assert t == Target(host='127.0.0.2', port=8080) def test_ip(): target = '127.0.0.1' targets = Target.parse_target(target) assert len(targets) == 1 t = targets.pop() assert t == Target(host=target) assert str(t) == target def test_cidr(): target = '192.168.1.0/24' targets = Target.parse_target(target) assert len(targets) == 254 # TODO explicitly validate the range """ for ip in IPNetwork(target).iter_hosts(): print str(ip) assert Target(host=str(ip)) in targets """ def test_ip_port(): target = '192.168.1.1:8080' targets = Target.parse_target(target) assert len(targets) == 1 t = targets.pop() assert t == Target(host='192.168.1.1', port='8080') assert str(t) == target def test_proto_ip(): target = 'snmp://192.168.1.1' targets = Target.parse_target(target) assert len(targets) == 1 t = targets.pop() assert t == Target(host='192.168.1.1', protocol='snmp') assert str(t) == target def test_proto_ip_port(): target = 'snmp://192.168.1.1:8080' targets = Target.parse_target(target) assert len(targets) == 1 t = targets.pop() assert t == Target(host='192.168.1.1', port=8080, protocol='snmp') assert str(t) == target def test_hostname(): target = 'example.com' targets = Target.parse_target(target) assert len(targets) == 1 t = targets.pop() assert t == Target(host='example.com') def test_hostname_proto(): target = 'path_to_url targets = Target.parse_target(target) assert len(targets) == 1 t = targets.pop() assert t == Target(host='example.com', protocol='http') def test_hostname_proto_port(): target = 'path_to_url targets = Target.parse_target(target) assert len(targets) == 1 t = targets.pop() assert t == Target(host='example.com', port='80', protocol='http') ```
/content/code_sandbox/changeme/tests/target.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
845
```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE nmaprun> <?xml-stylesheet href="file:///usr/bin/../share/nmap/nmap.xsl" type="text/xsl"?> <!-- Nmap 7.30 scan initiated Tue Jan 17 21:26:24 2017 as: nmap -p 8080 -oX tests/tomcat_nmap -sV -v -n 127.0.0.1 --> <nmaprun scanner="nmap" args="nmap -p 8080 -oX tests/tomcat_nmap -sV -v -n 127.0.0.1" start="1484709984" startstr="Tue Jan 17 21:26:24 2017" version="7.30" xmloutputversion="1.04"> <scaninfo type="syn" protocol="tcp" numservices="1" services="8080"/> <verbose level="1"/> <debugging level="0"/> <taskbegin task="ARP Ping Scan" time="1484709984"/> <taskend task="ARP Ping Scan" time="1484709984" extrainfo="1 total hosts"/> <taskbegin task="SYN Stealth Scan" time="1484709984"/> <taskend task="SYN Stealth Scan" time="1484709984" extrainfo="1 total ports"/> <taskbegin task="Service scan" time="1484709984"/> <taskend task="Service scan" time="1484709990" extrainfo="1 service on 1 host"/> <taskbegin task="NSE" time="1484709990"/> <taskend task="NSE" time="1484709990"/> <taskbegin task="NSE" time="1484709990"/> <taskend task="NSE" time="1484709990"/> <host starttime="1484709984" endtime="1484709990"><status state="up" reason="arp-response" reason_ttl="0"/> <address addr="127.0.0.1" addrtype="ipv4"/> <address addr="08:00:27:F7:00:F2" addrtype="mac" vendor="Oracle VirtualBox virtual NIC"/> <hostnames> </hostnames> <ports><port protocol="tcp" portid="8080"><state state="open" reason="syn-ack" reason_ttl="64"/><service name="http" product="Apache Tomcat/Coyote JSP engine" version="1.1" method="probed" conf="10"><cpe>cpe:/a:apache:coyote_http_connector:1.1</cpe></service></port> </ports> <times srtt="357" rttvar="3753" to="100000"/> </host> <runstats><finished time="1484709990" timestr="Tue Jan 17 21:26:30 2017" elapsed="6.63" summary="Nmap done at Tue Jan 17 21:26:30 2017; 1 IP address (1 host up) scanned in 6.63 seconds" exit="success"/><hosts up="1" down="0" total="1"/> </runstats> </nmaprun> ```
/content/code_sandbox/changeme/tests/tomcat_nmap.xml
xml
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
695
```python import argparse from changeme import core from .core import cli_args from copy import deepcopy import logging import mock import os logger = logging.getLogger('changeme') def reset_handlers(): logger = logging.getLogger('changeme') logger.handlers = [] core.remove_queues() memcached_args = deepcopy(cli_args) memcached_args['protocols'] = 'memcached' memcached_args['target'] = '127.0.0.1' @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**memcached_args)) def memcached(mock_args): reset_handlers() se = core.main() try: assert se.found_q.qsize() == 1 except Exception as e: # Raise an assertion error if we're in Travis CI and fail if os.environ.get('TRAVIS', None): raise e # Warn if we're not Travis CI else: logger.warning('memcached failed') ```
/content/code_sandbox/changeme/tests/memcached.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
207
```python from changeme.scanners.http_post import HTTPPostScanner class HTTPRawPostScanner(HTTPPostScanner): def __init__(self, cred, target, username, password, config, cookies, csrf, raw): super(HTTPRawPostScanner, self).__init__(cred, target, username, password, config, cookies, csrf) self.raw = raw def __reduce__(self): return (self.__class__, (self.cred, self.target, self.username, self.password, self.config, self.cookies, self.csrf, self.raw)) def _make_request(self): self.logger.debug('_make_request') self.logger.debug("target: %s" % self.target) self.response = self.request.post(self.target, self.raw, verify=False, proxies=self.config.proxy, timeout=self.config.timeout, headers=self.headers, cookies=self.cookies) ```
/content/code_sandbox/changeme/scanners/http_raw_post.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
185
```python from pymongo import MongoClient from .scanner import Scanner import socket class Mongodb(Scanner): def __init__(self, cred, target, username, password, config): super(Mongodb, self).__init__(cred, target, config, username, password) def _check(self): u_p = "" if self.username or self.password: u_p = "%s:%s@" % (self.username, self.password) client = MongoClient('mongodb://%s%s:%s/' % (u_p, self.target.host, self.target.port)) dbs = client.database_names() server_info = client.server_info() evidence = 'Version: %s, databases: %s' % (server_info['version'], ', '.join(dbs)) return evidence def _mkscanner(self, cred, target, u, p, config): return Mongodb(cred, target, u, p, config) ```
/content/code_sandbox/changeme/scanners/mongo.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
196
```python from changeme.scanners.http_get import HTTPGetScanner class HTTPPostScanner(HTTPGetScanner): def __init__(self, cred, target, username, password, config, cookies, csrf): super(HTTPPostScanner, self).__init__(cred, target, username, password, config, cookies) self.csrf = csrf def __reduce__(self): return (self.__class__, (self.cred, self.target, self.username, self.password, self.config, self.cookies, self.csrf)) def _make_request(self): self.logger.debug('_make_request') self.logger.debug("target: %s" % self.target) data = self.render_creds(self.cred, self.csrf) if self.cred.get('form_data'): form_data = {} for k in data: form_data[k] = (None, data[k]) self.response = self.request.post(self.target, file=form_data, verify=False, proxies=self.config.proxy, timeout=self.config.timeout, headers=self.headers, cookies=self.cookies) else: self.response = self.request.post(self.target, data, verify=False, proxies=self.config.proxy, timeout=self.config.timeout, headers=self.headers, cookies=self.cookies) ```
/content/code_sandbox/changeme/scanners/http_post.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
266
```python from pysnmp.hlapi import * from .scanner import Scanner class SNMP(Scanner): def __init__(self, cred, target, username, password, config): super(SNMP, self).__init__(cred, target, config, username, password) def fingerprint(self): # Don't fingerprint since it's UDP return True def _check(self): iterator = getCmd(SnmpEngine(), CommunityData(self.password), UdpTransportTarget((str(self.target.host), 161)), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))) errorIndication, errorStatus, errorIndex, varBinds = next(iterator) evidence = "" if errorIndication: self.logger.debug(errorIndication) elif errorStatus: self.logger.debug('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: evidence += ' = '.join([x.prettyPrint() for x in varBind]) if evidence == "": raise Exception return evidence def _mkscanner(self, cred, target, u, p, config): return SNMP(cred, target, u, p, config) ```
/content/code_sandbox/changeme/scanners/snmp.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
288
```python __all__ = [ 'database', 'ftp', 'http_basic_auth', 'http_fingerprint', 'http_get', 'http_post', 'http_raw_post', 'memcached', 'mongo', 'mssql', 'mysql', 'postgres', 'redis_scanner', 'scanner', 'snmp', 'ssh_key', 'ssh', 'telnet' ] ```
/content/code_sandbox/changeme/scanners/__init__.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
94
```python import argparse from changeme.scan_engine import ScanEngine from changeme.target import Target from changeme import core from .core import cli_args from copy import deepcopy import csv import json import logging import mock from .mock_responses import MockResponses from nose.tools import * import os import responses """ TODO: - Custom headers - 429 response code - """ def reset_handlers(): logger = logging.getLogger('changeme') logger.handlers = [] core.remove_queues() fp_args = deepcopy(cli_args) fp_args['nmap'] = 'tests/tomcat_nmap.xml' fp_args['name'] = 'Tomcat' @responses.activate @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**fp_args)) def test_tomcat_match_nmap(mock_args): def tomcat_callback(request): if request.headers.get('Authorization', False): return (200, MockResponses.tomcat_auth['adding_headers'], MockResponses.tomcat_auth['body']) else: return (401, MockResponses.tomcat_fp['adding_headers'], '') responses.add_callback( responses.GET, MockResponses.tomcat_fp['url'], callback=tomcat_callback, ) reset_handlers() try: os.remove(core.PERSISTENT_QUEUE) except OSError: pass args = core.parse_args() core.init_logging(args['args'].verbose, args['args'].debug, args['args'].log) config = core.Config(args['args'], args['parser']) creds = core.load_creds(config) s = ScanEngine(creds, config) s._build_targets() s._add_terminators(s.fingerprints) print(("fp: %i" % s.fingerprints.qsize())) s.fingerprint_targets() # Queue is not serializeable so we can't copy it using deepcopy scanners = list() print(("scanners: %s" % s.scanners.qsize())) t1 = Target(host='127.0.0.1', port=8080, protocol='http', url='/manager/html') t2 = Target(host='127.0.0.1', port=8080, protocol='http', url='/tomcat/manager/html') while s.scanners.qsize() > 0: scanner = s.scanners.get() assert scanner.target == t1 or scanner.target == t2 scanners.append(scanner) # Load the scanners back into the queue for scanner in scanners: s.scanners.put(scanner) assert s.scanners.qsize() == 34 s._add_terminators(s.scanners) responses.reset() responses.add(**MockResponses.tomcat_auth) s._scan(s.scanners, s.found_q) assert s.found_q.qsize() == 17 fp_args = deepcopy(cli_args) fp_args['fingerprint'] = True fp_args['name'] = 'Tomcat' fp_args['noversion'] = False @responses.activate @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**fp_args)) def test_tomcat_fingerprint(mock_args): responses.add(**MockResponses.tomcat_fp) print(responses.__dict__) reset_handlers() se = core.main() print(("Scanners:",se.scanners.qsize())) assert se.scanners.qsize() == 34 core.remove_queues() @responses.activate @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**cli_args)) def test_tomcat_invalid_creds(mock_args): responses.add(**MockResponses.tomcat_fp) reset_handlers() se = core.main() assert se.found_q.qsize() == 0 @responses.activate @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**cli_args)) def test_jboss_scan_fail(mock_args): responses.add(**MockResponses.jboss_fp) responses.add(**MockResponses.jboss_auth_fail) reset_handlers() args = core.parse_args() core.init_logging(args['args'].verbose, args['args'].debug, args['args'].log) config = core.Config(args['args'], args['parser']) creds = core.load_creds(config) se = ScanEngine(creds, config) se._build_targets() se._add_terminators(se.fingerprints) se.fingerprint_targets() print(se.scanners.qsize()) scanners = list() while se.scanners.qsize() > 0: s = se.scanners.get() print(s.cred['name']) print(s.target) print(s.username) print(s.password) scanners.append(s) print("num scanners: %i" % len(scanners)) assert len(scanners) == 2 # put scanners back in queue for s in scanners: se.scanners.put(s) se._add_terminators(se.scanners) se._scan(se.scanners, se.found_q) assert se.found_q.qsize() == 0 jboss_args = deepcopy(cli_args) jboss_args['name'] = 'JBoss AS 6 Alt' @responses.activate @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**jboss_args)) def test_jboss_scan_success(mock_args): responses.add(**MockResponses.jboss_fp) responses.add(**MockResponses.jboss_auth) reset_handlers() se = core.main() assert se.found_q.qsize() == 1 subnet_args = deepcopy(cli_args) subnet_args['target'] = '127.0.0.1/32' subnet_args['protocols'] = 'http' subnet_args['name'] = 'JBoss AS 6 Alt' @responses.activate @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**subnet_args)) def test_jboss_scan_success_subnet(mock_args): responses.add(**MockResponses.jboss_fp) responses.add(**MockResponses.jboss_auth) reset_handlers() se = core.main() assert se.found_q.qsize() == 1 @responses.activate @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**cli_args)) def test_jboss_csrf_fail(mock_args): responses.add(**MockResponses.jboss_fp_no_csrf) reset_handlers() se = core.main() assert se.found_q.qsize() == 0 idrac_args = deepcopy(cli_args) idrac_args['name'] = "Dell iDRAC" @responses.activate @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**idrac_args)) def test_idrac_scan_success(mock_args): responses.reset() responses.add(**MockResponses.idrac_fp) responses.add(**MockResponses.idrac_auth) reset_handlers() se = core.main() assert se.found_q.qsize() == 1 targets_args = deepcopy(cli_args) targets_args['target'] = '/tmp/targets.txt' @responses.activate @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**targets_args)) def test_targets_scan_success(mock_args): responses.reset() responses.add(**MockResponses.idrac_fp) responses.add(**MockResponses.idrac_auth) with open(targets_args['target'], 'w') as fout: fout.write('127.0.0.1' + '\n') reset_handlers() se = core.main() assert se.found_q.qsize() == 1 csv_args = deepcopy(cli_args) csv_args['log'] = '/tmp/output.log' csv_args['output'] = '/tmp/output.csv' csv_args['name'] = 'JBoss AS 6 Alt' @responses.activate @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**csv_args)) def test_csv_output(mock_args): responses.add(**MockResponses.jboss_fp) responses.add(**MockResponses.jboss_auth) reset_handlers() se = core.main() print(se.found_q.qsize()) assert se.found_q.qsize() == 1 assert os.path.isfile(csv_args['output']) i = 0 with open(csv_args['output'], 'r') as csvfile: reader = csv.reader(csvfile) for line in reader: if i == 1: assert line[0] == 'JBoss AS 6 Alt' assert line[1] == 'admin' assert line[2] == 'admin' assert line[3] == 'path_to_url i += 1 assert os.path.isfile(csv_args['log']) json_args = deepcopy(cli_args) json_args['output'] = '/tmp/output.json' json_args['name'] = 'JBoss AS 6 Alt' @responses.activate @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**json_args)) def test_json_output(mock_args): responses.add(**MockResponses.jboss_fp) responses.add(**MockResponses.jboss_auth) reset_handlers() se = core.main() assert se.found_q.qsize() == 1 assert os.path.isfile(json_args['output']) i = 0 with open(json_args['output'], 'r') as json_file: j = json.loads(json_file.read()) assert j["results"][0]['name'] == 'JBoss AS 6 Alt' assert j['results'][0]['username'] == 'admin' assert j['results'][0]['password'] == 'admin' assert j['results'][0]['target'] == 'path_to_url dr_args = deepcopy(cli_args) dr_args['dryrun'] = True @raises(SystemExit) @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**dr_args)) def test_dryrun(mock_args): reset_handlers() se = core.main() assert se.found_q.qsize() == 0 es_args = deepcopy(cli_args) es_args['name'] = "elasticsearch" @responses.activate @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace(**es_args)) def test_es_scan_success(mock_args): responses.reset() responses.add(**MockResponses.elasticsearch) reset_handlers() se = core.main() assert se.found_q.qsize() == 1 ```
/content/code_sandbox/changeme/tests/http.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
2,209
```python from .database import Database class MySQL(Database): def __init__(self, cred, target, username, password, config): super(MySQL, self).__init__(cred, target, username, password, config) self.database = "" self.query = "select version();" def _mkscanner(self, cred, target, u, p, config): return MySQL(cred, target, u, p, config) ```
/content/code_sandbox/changeme/scanners/mysql.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
92
```python from .database import Database class MSSQL(Database): def __init__(self, cred, target, username, password, config): super(MSSQL, self).__init__(cred, target, username, password, config) self.target.protocol = "mssql+pyodbc" self.database = "" self.query = "SELECT @@VERSION AS 'SQL Server Version';" def _mkscanner(self, cred, target, u, p, config): return MSSQL(cred, target, u, p, config) ```
/content/code_sandbox/changeme/scanners/mssql.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
114
```python from .scanner import Scanner import telnetlib import re import time class Telnet(Scanner): def __init__(self, cred, target, username, password, config): super(Telnet, self).__init__(cred, target, config, username, password) def _check(self): try: telnet = telnetlib.Telnet(str(self.target.host)) timeout_allowed = int(self.cred['auth']['blockingio_timeout']) wait_for_pass_prompt = int(self.cred['auth']['telnet_read_timeout']) retval = telnet.open(str(self.target.host), int(self.target.port), timeout=timeout_allowed) retval._has_poll = False # telnetlib hackery :) banner = telnet.read_until("login: ") telnet.write(self.username + "\n") password = str(self.password) if self.password else '' result = telnet.read_until("Password: ", timeout=wait_for_pass_prompt) result = Telnet._trim_string(result) if "Password:" in result: telnet.write(password + "\n") else: self.logger.debug("Check closed at: 1") telnet.close() raise Exception("Telnet credential not found") telnet.write(b"ls\n") # evidence = '(slow connection, evidence not collected)' # try: # evidence = telnet.read_all() # except: # pass evidence = "(slow connection, evidence not collected)" time.sleep(3) evidence = telnet.read_very_eager() evidence_fp_check = Telnet._trim_string(evidence) self.logger.debug("Evidence string returned (stripped): %s" % str(evidence_fp_check)) evidence_fp_check_as_bytes = ":".join("{:02x}".format(ord(c)) for c in evidence_fp_check) self.logger.debug("Evidence string returned (bytes): %s" % str(evidence_fp_check_as_bytes)) # Remove simple echos or additional password prompt (wrong password) if (not evidence_fp_check) or (evidence_fp_check == "ls") or ("Password:" in evidence) or (evidence == ""): self.logger.debug("Check closed at: 2") telnet.close() raise Exception("Telnet credential not found") # Remove additional prompts to login - we have a correct username, but incorrect password if evidence_fp_check.endswith("login:") or evidence_fp_check.endswith("login: "): self.logger.debug("Check closed at: 3") telnet.close() raise Exception("Telnet credential not found") telnet.write("exit\n") telnet.close() return evidence except Exception as e: self.logger.debug("Error: %s" % str(e)) raise e @staticmethod def _trim_string(str_to_trim): return str(str_to_trim).replace(' ','').replace('\s','').replace('\t','').replace('\r','').replace('\n','') def _mkscanner(self, cred, target, u, p, config): return Telnet(cred, target, u, p, config) ```
/content/code_sandbox/changeme/scanners/telnet.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
672
```python import logging import paramiko from .ssh import SSH from io import StringIO class SSHKey(SSH): def __init__(self, cred, target, username, key, config): super(SSHKey, self).__init__(cred, target, username, key, config) self.logger = logging.getLogger('changeme') def _check(self): fake = StringIO(self.password) if "RSA PRIVATE KEY" in self.password: key = paramiko.RSAKey.from_private_key(fake) elif "DSA PRIVATE KEY" in self.password: key = paramiko.DSSKey.from_private_key(fake) c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy()) # ignore unknown hosts c.connect(hostname=self.target.host, port=self.target.port, username=self.username, pkey=key) stdin, stdout, stderr = c.exec_command('uname -a') evidence = stdout.readlines()[0] c.close() self.password = 'Private Key' return evidence def _mkscanner(self, cred, target, u, p, config): return SSHKey(cred, target, u, p, config) ```
/content/code_sandbox/changeme/scanners/ssh_key.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
255
```python from .database import Database class Postgres(Database): def __init__(self, cred, target, username, password, config): super(Postgres, self).__init__(cred, target, username, password, config) self.target.protocol = "postgresql+psycopg2" self.database = "" self.query = "select version();" def _mkscanner(self, cred, target, u, p, config): return Postgres(cred, target, u, p, config) ```
/content/code_sandbox/changeme/scanners/postgres.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
106
```python import redis from .scanner import Scanner class RedisScanner(Scanner): def __init__(self, cred, target, username, password, config): super(RedisScanner, self).__init__(cred, target, config, username, password) def _check(self): r = redis.StrictRedis(host=self.target.host, port=self.target.port) info = r.info() evidence = "redis_version: %s, os: %s" % (info['redis_version'], info['os']) return evidence def _mkscanner(self, cred, target, u, p, config): return RedisScanner(cred, target, u, p, config) ```
/content/code_sandbox/changeme/scanners/redis_scanner.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
143
```python import logging from netaddr import IPAddress import socket class Scanner(object): def __init__(self, cred, target, config, username, password): self.logger = logging.getLogger('changeme') self.cred = cred self.target = target if self.target.port is None: self.target.port = self.cred['default_port'] self.config = config self.username = username self.password = password def __hash__(self): return id(self) def scan(self): return self.check_success() def fingerprint(self): if self.target.port is None: self.target.port = self.cred['default_port'] try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(3) result = sock.connect_ex((str(self.target.host), self.target.port)) sock.shutdown(2) if result == 0: return True self.logger.info('Port %i open' % self.target.port) else: return False except Exception as e: self.logger.debug(str(e)) return False def get_scanners(self, creds): scanners = list() for pair in self.cred['auth']['credentials']: scanners.append(self._mkscanner(self.cred, self.target, pair['username'], pair['password'], self.config)) return scanners def check_success(self): try: evidence = self._check() self.logger.critical('[+] Found %s default cred %s:%s at %s' % (self.cred['name'], self.username, self.password, self.target)) self.logger.debug('%s %s:%s evidence: %s' % (self.target, self.username, self.password, evidence)) return {'name': self.cred['name'], 'username': self.username, 'password': self.password, 'target': self.target, 'evidence': evidence} except Exception as e: self.logger.info('Invalid %s default cred %s:%s at %s' % (self.cred['name'], self.username, self.password, str(self.target))) self.logger.debug('%s Exception: %s' % (type(e).__name__, str(e))) return False def _check(self): raise NotImplementedError("A Scanner class needs to implement a _check method.") def __getstate__(self): state = self.__dict__ state['logger'] = None # Need to clear the logger when serializing otherwise mp.Queue blows up return state def __setstate__(self, d): self.__dict__ = d self.logger = logging.getLogger('changeme') def __eq__(self, other): return self.__dict__ == other.__dict__ #return (str(self.target) + self.username + self.password) == (other.target + other.username + other.password) ```
/content/code_sandbox/changeme/scanners/scanner.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
618
```python from .scanner import Scanner import sqlalchemy class Database(Scanner): def __init__(self, cred, target, username, password, config): super(Database, self).__init__(cred, target, config, username, password) self.database = None self.query = None def _check(self): url = "%s://%s:%s@%s:%s/%s" % (self.target.protocol, self.username, self.password, self.target.host, self.target.port, self.database) engine = sqlalchemy.create_engine(url, connect_args={'connect_timeout': self.config.timeout}) c = engine.connect() res = c.execute(self.query) results = list() [results.append(i) for i in res.fetchall()] return str(results[0][0]) def _mkscanner(self, cred, target, u, p, config): raise NotImplementedError("A Database class needs to implement a _mkscanner method.") ```
/content/code_sandbox/changeme/scanners/database.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
199
```python from .scanner import Scanner import ftplib class FTP(Scanner): def __init__(self, cred, target, username, password, config): super(FTP, self).__init__(cred, target, config, username, password) def _check(self): ftp = ftplib.FTP() ftp.connect(self.target.host, self.target.port) ftp.login(self.username, self.password) evidence = ftp.retrlines('LIST') ftp.quit() return evidence def _mkscanner(self, cred, target, u, p, config): return FTP(cred, target, u, p, config) ```
/content/code_sandbox/changeme/scanners/ftp.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
135
```python import base64 import random from requests import session from .scanner import Scanner import re from selenium import webdriver from time import sleep try: # Python 3 from urllib.parse import urlencode, urlparse except ImportError: # Python 2 from urllib import urlencode from urlparse import urlparse HEADERS_USERAGENTS = [ 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3) Gecko/20090913 Firefox/3.5.3', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729)', 'Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729)', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.1) Gecko/20090718 Firefox/3.5.1', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.1 (KHTML, like Gecko) Chrome/4.0.219.6 Safari/532.1', 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; InfoPath.2)', 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Win64; x64; Trident/4.0)', 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; SV1; .NET CLR 2.0.50727; InfoPath.2)', 'Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)', 'Mozilla/4.0 (compatible; MSIE 6.1; Windows XP)', 'Opera/9.80 (Windows NT 5.2; U; ru) Presto/2.5.22 Version/10.51' ] def get_useragent(): return random.choice(HEADERS_USERAGENTS) class HTTPGetScanner(Scanner): def __init__(self, cred, target, username, password, config, cookies): super(HTTPGetScanner, self).__init__(cred, target, config, username, password) self.cred = cred self.config = config self.cookies = cookies self.headers = dict() self.request = session() self.response = None headers = self.cred['auth'].get('headers', dict()) custom_ua = False if headers: for h in headers: self.headers.update(h) if not custom_ua and any(k.lower() == 'user-agent' for k in h): custom_ua = True # If set, take user agent from CLI args, otherwise, pick a random # one if not provided in the cred file. if self.config.useragent: self.headers.update(self.config.useragent) elif not custom_ua: self.headers.update({'User-Agent': get_useragent()}) # make the cred have only one u:p combo self.cred['auth']['credentials'] = [{'username': self.username, 'password': self.password}] def __reduce__(self): return self.__class__, (self.cred, self.target, self.username, self.password, self.config, self.cookies) def scan(self): try: self._make_request() except Exception as e: self.logger.error('Failed to connect to %s' % self.target) self.logger.debug('Exception: %s: %s' % (type(e).__name__, e.__str__().replace('\n', '|'))) return None if self.response.status_code == 429: self.warn('Status 429 received. Sleeping for %d seconds and trying again' % self.config.delay) sleep(self.config.delay) try: self._make_request() except Exception as e: self.logger.error('Failed to connect to %s' % self.target) return self.check_success() def check_success(self): match = False success = self.cred['auth']['success'] if self.cred['auth'].get('base64', None): self.username = base64.b64decode(self.cred.username) self.password = base64.b64decode(self.cred.password) if success.get('status') == self.response.status_code or self.response.history and self.response.history[0].status_code == success.get('status'): self.logger.debug('%s matched %s success status code %s' % (self.target, self.cred['name'], self.response.status_code)) if success.get('body'): for string in success.get('body'): if re.search(string, self.response.text, re.IGNORECASE): self.logger.debug('%s matched %s success body text %s' % (self.target, self.cred['name'], success.get('body'))) match = True break else: match = True if match: self.logger.critical('[+] Found %s default cred %s:%s at %s' % (self.cred['name'], self.username, self.password, self.target)) evidence = '' if self.config.output is not None: try: evidence = self._screenshot(self.target) except Exception as e: self.logger.error("Error gathering screenshot for %s" % self.target) self.logger.debug('Exception: %s: %s' % (type(e).__name__, e.__str__().replace('\n', '|'))) return {'name': self.cred['name'], 'username': self.username, 'password': self.password, 'target': self.target, 'evidence': evidence} else: self.logger.info('Invalid %s default cred %s:%s at %s' % (self.cred['name'], self.username, self.password, self.target)) return False def _check_fingerprint(self): self.logger.debug("_check_fingerprint") self.request = session() self.response = self.request.get(self.target, timeout=self.config.timeout, verify=False, proxies=self.config.proxy, cookies=self.fingerprint.cookies, headers=self.fingerprint.headers) self.logger.debug('_check_fingerprint', '%s - %i' % (self.target, self.response.status_code)) return self.fingerprint.match(self.response) def _make_request(self): self.logger.debug("_make_request") data = self.render_creds(self.cred) qs = urlencode(data) url = "%s?%s" % (self.target, qs) self.logger.debug("url: %s" % url) self.response = self.request.get(self.target, verify=False, proxies=self.config.proxy, timeout=self.config.timeout, headers=self.headers, cookies=self.cookies) def render_creds(self, candidate, csrf=None): """ Return a list of dicts with post/get data and creds. The list of dicts have a data element and a username and password associated with the data. The data will either be a dict if its a regular GET or POST and a string if its a raw POST. """ b64 = candidate['auth'].get('base64', None) type = candidate['auth'].get('type') config = None if type == 'post': config = candidate['auth'].get('post', None) if type == 'get': config = candidate['auth'].get('get', None) if not type == 'raw_post': data = self._get_parameter_dict(candidate['auth']) if csrf: csrf_field = candidate['auth']['csrf'] data[csrf_field] = csrf for cred in candidate['auth']['credentials']: cred_data = {} username = "" password = "" if b64: username = base64.b64encode(cred['username']) password = base64.b64encode(cred['password']) else: username = cred['username'] password = cred['password'] cred_data[config['username']] = username cred_data[config['password']] = password data_to_send = dict(list(data.items()) + list(cred_data.items())) return data_to_send else: # raw post return None def _get_parameter_dict(self, auth): params = dict() data = auth.get('post', auth.get('get', None)) for k in list(data.keys()): if k not in ('username', 'password', 'url'): params[k] = data[k] return params @staticmethod def get_base_url(req): parsed = urlparse(req) url = "%s://%s" % (parsed[0], parsed[1]) return url def _screenshot(self, target): self.logger.debug("Screenshotting %s" % self.target) # Set up the selenium webdriver # This feels like it will have threading issues for key, value in self.response.request.headers.items(): capability_key = 'phantomjs.page.customHeaders.{}'.format(key) webdriver.DesiredCapabilities.PHANTOMJS[capability_key] = value if self.config.proxy: webdriver.DesiredCapabilities.PHANTOMJS['proxy'] = { "httpProxy": self.config.proxy['http'].replace('path_to_url ''), "ftpProxy": self.config.proxy['http'].replace('path_to_url ''), "sslProxy": self.config.proxy['http'].replace('path_to_url ''), "noProxy":None, "proxyType":"MANUAL", "autodetect":False } driver = webdriver.PhantomJS() driver.set_page_load_timeout(int(self.config.timeout) - 0.1) driver.set_window_position(0, 0) driver.set_window_size(850, 637.5) for cookie in self.response.request._cookies.items(): self.logger.debug("Adding cookie: %s:%s" % cookie) driver.add_cookie({'name': cookie[0], 'value': cookie[1], 'path': '/', 'domain': self.target.host }) try: driver.get(str(self.target)) driver.save_screenshot('screenshot.png') evidence = driver.get_screenshot_as_base64() driver.quit() except Exception as e: self.logger.error('Error getting screenshot for %s' % self.target) self.logger.debug('Exception: %s: %s' % (type(e).__name__, e.__str__().replace('\n', '|'))) evidence = "" return evidence ```
/content/code_sandbox/changeme/scanners/http_get.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
2,403
```python import paramiko from .scanner import Scanner import socket class SSH(Scanner): def __init__(self, cred, target, username, password, config): super(SSH, self).__init__(cred, target, config, username, password) def _check(self): c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy()) # ignore unknown hosts c.connect(hostname=self.target.host, port=self.target.port, username=self.username, password=self.password) stdin, stdout, stderr = c.exec_command('uname -a') evidence = stdout.readlines()[0] c.close() return evidence def _mkscanner(self, cred, target, u, p, config): return SSH(cred, target, u, p, config) ```
/content/code_sandbox/changeme/scanners/ssh.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
174
```python from changeme.scanners.http_get import HTTPGetScanner from requests.auth import HTTPBasicAuth class HTTPBasicAuthScanner(HTTPGetScanner): pass def _make_request(self): self.logger.debug("Requesting %s" % self.target) self.response = self.request.get(self.target, auth=HTTPBasicAuth(self.username, self.password), verify=False, proxies=self.config.proxy, timeout=self.config.timeout, headers=self.headers, cookies=self.cookies) ```
/content/code_sandbox/changeme/scanners/http_basic_auth.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
102
```python import memcache from .scanner import Scanner class MemcachedScanner(Scanner): def __init__(self, cred, target, username, password, config): super(MemcachedScanner, self).__init__(cred, target, config, username, password) def _check(self): mc = memcache.Client(['%s:%s' % (self.target.host, self.target.port)], debug=0) stats = mc.get_stats() evidence = "version: %s" % (stats[0][1]['version']) return evidence def _mkscanner(self, cred, target, u, p, config): return MemcachedScanner(cred, target, u, p, config) ```
/content/code_sandbox/changeme/scanners/memcached.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
151
```python from changeme.scanners.http_basic_auth import HTTPBasicAuthScanner from changeme.scanners.http_get import HTTPGetScanner from changeme.scanners.http_post import HTTPPostScanner from changeme.scanners.http_raw_post import HTTPRawPostScanner from changeme.target import Target from copy import deepcopy import logging from lxml import html import re import requests class HttpFingerprint: def __init__(self, target, headers, cookies, config): self.target = target # changeme.target.Target() self.headers = headers self.cookies = cookies self.config = config self.logger = logging.getLogger('changeme') self.res = None self.req = requests.Session() def __getstate__(self): state = self.__dict__ state['logger'] = None # Need to clear the logger when serializing otherwise mp.Queue blows up return state def __setstate__(self, d): self.__dict__ = d self.logger = logging.getLogger('changeme') def __hash__(self): return hash(str(self.target) + str(self.headers) + str(self.cookies)) def __eq__(self, other): s = dict() o = dict() s['target'] = self.target s['headers'] = self.headers s['cookies'] = self.cookies o['target'] = other.target o['headers'] = other.headers o['cookies'] = other.cookies return s == o def fingerprint(self): try: self._fp() except Exception as e: if self.config.ssl and e.__class__ == requests.exceptions.SSLError: self.target.protocol = 'http' self.logger.debug('Retrying with non-SSL target: %s' % self.target) try: self._fp() except Exception as e: self.logger.debug('Failed to connect to %s' % self.target) return False return True def _fp(self): self.res = self.req.get( str(self.target), timeout=self.config.timeout, verify=False, proxies=self.config.proxy, headers=self.headers, cookies=self.cookies ) def _get_csrf_token(self, res, cred): name = cred['auth'].get('csrf', False) if name: tree = html.fromstring(res.content) try: csrf = str(tree.xpath('//input[@name="%s"]/@value' % name)[0]) except: self.logger.error( 'Failed to get CSRF token %s in %s' % (str(name), str(res.url))) return False self.logger.debug('Got CSRF token %s: %s' % (name, csrf)) else: csrf = False return csrf def _get_session_id(self, res, cred): cookie = cred['auth'].get('sessionid', False) if cookie: try: value = res.cookies[cookie] self.logger.debug('Got session cookie value: %s' % value) except: self.logger.error( 'Failed to get %s cookie from %s' % (cookie, res.url)) return False return {cookie: value} else: self.logger.debug('No cookie') return False def ismatch(self, cred, response): match = False if cred['protocol'] == 'http': fp = cred['fingerprint'] basic_auth = fp.get('basic_auth_realm', None) if basic_auth and basic_auth in response.headers.get('WWW-Authenticate', list()): self.logger.info('%s basic auth matched: %s' % (cred['name'], basic_auth)) match = True server = response.headers.get('Server', None) fp_server = fp.get('server_header', None) if fp_server and server and fp_server in server: self.logger.debug('%s server header matched: %s' % (cred['name'], fp_server)) match = True body = fp.get('body', None) if body: for b in body: if re.search(b, response.text): match = True self.logger.info('%s body matched: %s' % (cred['name'], b)) elif body: match = False return match def get_scanners(self, creds): scanners = list() for cred in creds: if self.ismatch(cred, self.res): csrf = self._get_csrf_token(self.res, cred) if cred['auth'].get('csrf', False) and not csrf: self.logger.error('Missing required CSRF token') return sessionid = self._get_session_id(self.res, cred) if cred['auth'].get('sessionid') and not sessionid: self.logger.error("Missing session cookie %s for %s" % (cred['auth'].get('sessionid'), self.res.url)) return for pair in cred['auth']['credentials']: for u in cred['auth']['url']: # pass in the auth url target = deepcopy(self.target) target.url = u self.logger.debug('Building %s %s:%s, %s' % (cred['name'], pair['username'], pair['password'], target)) if cred['auth']['type'] == 'get': scanners.append(HTTPGetScanner(cred, target, pair['username'], pair['password'], self.config, self.req.cookies)) elif cred['auth']['type'] == 'post': scanners.append(HTTPPostScanner(cred, target, pair['username'], pair['password'], self.config, self.req.cookies, csrf)) elif cred['auth']['type'] == 'raw_post': scanners.append(HTTPRawPostScanner(cred, target, pair['username'], pair['password'], self.config, self.req.cookies, csrf, pair['raw'])) elif cred['auth']['type'] == 'basic_auth': scanners.append(HTTPBasicAuthScanner(cred, target, pair['username'], pair['password'], self.config, self.req.cookies)) return scanners @staticmethod def build_fingerprints(targets, creds, config): fingerprints = list() logger = logging.getLogger('changeme') # Build a set of unique fingerprints for target in targets: for c in creds: if not c['protocol'] == 'http': continue if not config.portoverride and (target.port and not c['default_port'] == target.port): continue fp = c['fingerprint'] for url in fp.get('url'): t = Target(host=target.host, port=target.port, protocol=target.protocol) if c.get('ssl') or config.ssl: t.protocol = 'https' else: t.protocol = 'http' if not t.port: t.port = c['default_port'] t.url = url hfp = HttpFingerprint(t, fp.get('headers', None), fp.get('cookie', None), config) logger.debug('Adding %s to fingerprint list' % hfp.target) fingerprints.append(hfp) return fingerprints ```
/content/code_sandbox/changeme/scanners/http_fingerprint.py
python
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
1,532
```unknown <html> <head> <title>Changme Default Credential Report</title> <script type="text/javascript" src="path_to_url" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script> <script src="path_to_url" integrity=your_sha256_hashcPD7Txa" crossorigin="anonymous"></script> <link href="path_to_url" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <style type=text/css> .row { border-top: 1px solid #666; } ul { padding-left: 0px; } ul li { list-style: none; } ul li a { word-wrap: break-word; } </style> </head> <body> <div class="container"> <div class="row"> <div class="col-sm-12 center"> <h1>Changeme</h1> <ul> <li><strong>Found {{ found|length }} credentials</strong></li> <li>Scan: {{ cli }}</li> <li>Report Timestamp: {{ timestamp }}</li> </ul> </div> </div> {% for cred in found %} <div class="row"> <div class="col-sm-3"> <ul> <li>Service: {{ cred['name'] }}</li> <li>Username: {{ cred['username'] if cred['username'] != None }}</li> <li>Password: {{ cred['password'] if cred['password'] != None }}</li> {% if 'http' in cred['target'].protocol %} <li><a href="{{ cred['target'] }}">{{ cred['target'] }}</a></li> {% else %} <li>{{ cred['target'] }}</li> {% endif %} </ul> </div> <div class="col-sm-9"> {% if 'http' in cred['target'].protocol %} <img alt="{{ cred['url'] }}" src="data:image/png;base64,{{ cred['evidence'] }}" /> {% else %} {{ cred['evidence'] }} {% endif %} </div> </div> {% endfor %} </div> </body> </html> ```
/content/code_sandbox/changeme/templates/report.j2
unknown
2016-03-11T17:10:34
2024-08-13T06:37:08
changeme
ztgrace/changeme
1,427
560
```javascript import { Mock, Constant } from './_utils' const { ApiPrefix } = Constant let postId = 0 const database = Mock.mock({ 'data|100': [ { id() { postId += 1 return postId + 10000 }, 'status|1-2': 1, title: '@title', author: '@last', categories: '@word', tags: '@word', 'views|10-200': 1, 'comments|10-200': 1, visibility: () => { return Mock.mock( '@pick(["Public",' + '"Password protected", ' + '"Private"])' ) }, date: '@dateTime', image() { return Mock.Random.image( '100x100', Mock.Random.color(), '#757575', 'png', this.author.substr(0, 1) ) }, }, ], }).data module.exports = { [`GET ${ApiPrefix}/posts`](req, res) { const { query } = req let { pageSize, page, ...other } = query pageSize = pageSize || 10 page = page || 1 let newData = database for (let key in other) { if ({}.hasOwnProperty.call(other, key)) { newData = newData.filter(item => { if ({}.hasOwnProperty.call(item, key)) { return ( String(item[key]) .trim() .indexOf(decodeURI(other[key]).trim()) > -1 ) } return true }) } } res.status(200).json({ data: newData.slice((page - 1) * pageSize, page * pageSize), total: newData.length, }) }, } ```
/content/code_sandbox/mock/post.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
387
```javascript module.exports = { testURL: 'path_to_url } ```
/content/code_sandbox/jest.config.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
15
```unknown src/**/*-test.js src/public src/routes/chart/ECharts/theme src/routes/chart/highCharts/mapdata src/locales/_build/ src/locales/**/*.js docs/**/*.js ```
/content/code_sandbox/.eslintignore
unknown
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
42
```unknown BROWSER=none HOST=0.0.0.0 PORT=7000 ```
/content/code_sandbox/.env
unknown
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
21
```javascript // path_to_url import { resolve } from 'path' const fs = require('fs') const path = require('path') const lessToJs = require('less-vars-to-js') const isDevelopment = process.env.NODE_ENV === 'development' const { theme } = require('antd/lib') const { convertLegacyToken } = require('@ant-design/compatible/lib') const mapToken = theme.defaultAlgorithm(theme.defaultSeed) const v4Token = convertLegacyToken(mapToken) // how to speed compile: path_to_url export default { // IMPORTANT! change next line to yours or delete. And hide in dev publicPath: isDevelopment ? '/' : 'path_to_url alias: { api: resolve(__dirname, './src/services/'), components: resolve(__dirname, './src/components'), config: resolve(__dirname, './src/utils/config'), themes: resolve(__dirname, './src/themes'), utils: resolve(__dirname, './src/utils'), }, antd: false, // a lower cost way to genereate sourcemap, default is cheap-module-source-map, could save 60% time in dev hotload devtool: 'eval', dva: { immer: true }, dynamicImport: { loading: 'components/Loader/Loader', }, extraBabelPlugins: [ [ 'import', { libraryName: 'lodash', libraryDirectory: '', camel2DashComponentName: false, }, 'lodash', ], [ 'import', { libraryName: '@ant-design/icons', libraryDirectory: 'es/icons', camel2DashComponentName: false, }, 'ant-design-icons', ], [ 'macros' ] ], hash: true, ignoreMomentLocale: true, // umi3 comple node_modules by default, could be disable nodeModulesTransform: { type: 'none', exclude: [], }, // Webpack Configuration proxy: { '/api/v1/weather': { target: 'path_to_url changeOrigin: true, pathRewrite: { '^/api/v1/weather': '/v3/weather' }, }, }, // Theme for antd // path_to_url theme: { ...v4Token, ...lessToJs( fs.readFileSync(path.join(__dirname, './src/themes/default.less'), 'utf8') ) }, webpack5: {}, mfsu: {}, chainWebpack: function (config, { webpack }) { !isDevelopment && config.merge({ optimization: { minimize: false, splitChunks: { chunks: 'all', minSize: 30000, minChunks: 3, automaticNameDelimiter: '.', cacheGroups: { react: { name: 'react', priority: 20, test: /[\\/]node_modules[\\/](react|react-dom|react-dom-router)[\\/]/, }, antd: { name: 'antd', priority: 20, test: /[\\/]node_modules[\\/](antd|@ant-design\/icons)[\\/]/, }, 'echarts-gl': { name: 'echarts-gl', priority: 30, test: /[\\/]node_modules[\\/]echarts-gl[\\/]/, }, zrender: { name: 'zrender', priority: 30, test: /[\\/]node_modules[\\/]zrender[\\/]/, }, echarts: { name: 'echarts', priority: 20, test: /[\\/]node_modules[\\/](echarts|echarts-for-react|echarts-liquidfill)[\\/]/, }, highcharts: { name: 'highcharts', priority: 20, test: /[\\/]node_modules[\\/]highcharts[\\/]/, }, recharts: { name: 'recharts', priority: 20, test: /[\\/]node_modules[\\/]recharts[\\/]/, }, draftjs: { name: 'draftjs', priority: 30, test: /[\\/]node_modules[\\/](draft-js|react-draft-wysiwyg|draftjs-to-html|draftjs-to-markdown)[\\/]/, }, async: { chunks: 'async', minChunks: 2, name: 'async', maxInitialRequests: 1, minSize: 0, priority: 5, reuseExistingChunk: true, }, }, }, }, }) }, } ```
/content/code_sandbox/.umirc.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
1,005
```javascript import { Constant } from './_utils' const { ApiPrefix } = Constant const database = [ { id: '1', icon: 'dashboard', name: 'Dashboard', zh: { name: '' }, 'pt-br': { name: 'Dashboard' }, route: '/dashboard', }, { id: '2', breadcrumbParentId: '1', name: 'Users', zh: { name: '' }, 'pt-br': { name: 'Usurio' }, icon: 'user', route: '/user', }, { id: '7', breadcrumbParentId: '1', name: 'Posts', zh: { name: '' }, 'pt-br': { name: 'Posts' }, icon: 'shopping-cart', route: '/post', }, { id: '21', menuParentId: '-1', breadcrumbParentId: '2', name: 'User Detail', zh: { name: '' }, 'pt-br': { name: 'Detalhes do usurio' }, route: '/user/:id', }, { id: '3', breadcrumbParentId: '1', name: 'Request', zh: { name: 'Request' }, 'pt-br': { name: 'Requisio' }, icon: 'api', route: '/request', }, { id: '4', breadcrumbParentId: '1', name: 'UI Element', zh: { name: 'UI' }, 'pt-br': { name: 'Elementos UI' }, icon: 'camera-o', }, { id: '45', breadcrumbParentId: '4', menuParentId: '4', name: 'Editor', zh: { name: 'Editor' }, 'pt-br': { name: 'Editor' }, icon: 'edit', route: '/editor', }, { id: '5', breadcrumbParentId: '1', name: 'Charts', zh: { name: 'Charts' }, 'pt-br': { name: 'Graficos' }, icon: 'code-o', }, { id: '51', breadcrumbParentId: '5', menuParentId: '5', name: 'ECharts', zh: { name: 'ECharts' }, 'pt-br': { name: 'ECharts' }, icon: 'line-chart', route: '/chart/ECharts', }, { id: '52', breadcrumbParentId: '5', menuParentId: '5', name: 'HighCharts', zh: { name: 'HighCharts' }, 'pt-br': { name: 'HighCharts' }, icon: 'bar-chart', route: '/chart/highCharts', }, { id: '53', breadcrumbParentId: '5', menuParentId: '5', name: 'Rechartst', zh: { name: 'Rechartst' }, 'pt-br': { name: 'Rechartst' }, icon: 'area-chart', route: '/chart/Recharts', }, ] module.exports = { [`GET ${ApiPrefix}/routes`](req, res) { res.status(200).json(database) }, } ```
/content/code_sandbox/mock/route.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
783
```javascript /** * Query objects that specify keys and values in an array where all values are objects. * @param {array} array An array where all values are objects, like [{key:1},{key:2}]. * @param {string} key The key of the object that needs to be queried. * @param {string} value The value of the object that needs to be queried. * @return {object|undefined} Return frist object when query success. */ export function queryArray(array, key, value) { if (!Array.isArray(array)) { return } return array.filter(_ => _[key] === value) } export function randomNumber(min, max) { return Math.floor(Math.random() * (max - min) + min) } export function randomAvatar() { const avatarList = [ 'photo-1549492864-2ec7d66ffb04.jpeg', 'photo-1480535339474-e083439a320d.jpeg', 'photo-1523419409543-a5e549c1faa8.jpeg', 'photo-1519648023493-d82b5f8d7b8a.jpeg', 'photo-1523307730650-594bc63f9d67.jpeg', 'photo-1522962506050-a2f0267e4895.jpeg', 'photo-1489779162738-f81aed9b0a25.jpeg', 'photo-1534308143481-c55f00be8bd7.jpeg', 'photo-1519336555923-59661f41bb45.jpeg', 'photo-1551438632-e8c7d9a5d1b7.jpeg', 'photo-1525879000488-bff3b1c387cf.jpeg', 'photo-1487412720507-e7ab37603c6f.jpeg', 'photo-1510227272981-87123e259b17.jpeg' ] return `//image.zuiidea.com/${avatarList[randomNumber(0, avatarList.length - 1)]}?imageView2/1/w/200/h/200/format/webp/q/75|imageslim` } export const Constant = { ApiPrefix: '/api/v1', NotFound: { message: 'Not Found', documentation_url: '', }, Color: { green: '#64ea91', blue: '#8fc9fb', purple: '#d897eb', red: '#f69899', yellow: '#f8c82e', peach: '#f797d6', borderBase: '#e5e5e5', borderSplit: '#f4f4f4', grass: '#d6fbb5', sky: '#c1e0fc', }, } export Mock from 'mockjs' export qs from 'qs' ```
/content/code_sandbox/mock/_utils.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
629
```javascript import { Mock, Constant, randomAvatar } from './_utils' import qs from 'qs' const { ApiPrefix } = Constant let usersListData = Mock.mock({ 'data|80-100': [ { id: '@id', name: '@name', nickName: '@last', phone: /^1[34578]\d{9}$/, 'age|11-99': 1, address: '@county(true)', isMale: '@boolean', email: '@email', createTime: '@datetime', avatar() { return randomAvatar() }, }, ], }) let database = usersListData.data const EnumRoleType = { ADMIN: 'admin', DEFAULT: 'guest', DEVELOPER: 'developer', } const userPermission = { DEFAULT: { visit: ['1', '2', '21', '7', '5', '51', '52', '53'], role: EnumRoleType.DEFAULT, }, ADMIN: { role: EnumRoleType.ADMIN, }, DEVELOPER: { role: EnumRoleType.DEVELOPER, }, } const adminUsers = [ { id: 0, username: 'admin', password: 'admin', permissions: userPermission.ADMIN, avatar: randomAvatar(), }, { id: 1, username: 'guest', password: 'guest', permissions: userPermission.DEFAULT, avatar: randomAvatar(), }, { id: 2, username: '', password: '123456', permissions: userPermission.DEVELOPER, avatar: randomAvatar(), }, ] const queryArray = (array, key, keyAlias = 'key') => { if (!(array instanceof Array)) { return null } let data for (let item of array) { if (item[keyAlias] === key) { data = item break } } if (data) { return data } return null } const NOTFOUND = { message: 'Not Found', documentation_url: 'path_to_url } module.exports = { [`POST ${ApiPrefix}/user/login`](req, res) { const { username, password } = req.body const user = adminUsers.filter(item => item.username === username) if (user.length > 0 && user[0].password === password) { const now = new Date() now.setDate(now.getDate() + 1) res.cookie( 'token', JSON.stringify({ id: user[0].id, deadline: now.getTime() }), { maxAge: 900000, httpOnly: true, } ) res.json({ success: true, message: 'Ok' }) } else { res.status(400).end() } }, [`GET ${ApiPrefix}/user/logout`](req, res) { res.clearCookie('token') res.status(200).end() }, [`GET ${ApiPrefix}/user`](req, res) { const cookie = req.headers.cookie || '' const cookies = qs.parse(cookie.replace(/\s/g, ''), { delimiter: ';' }) const response = {} let user = {} if (!cookies.token) { res.status(200).send({ message: 'Not Login' }) return } const token = JSON.parse(cookies.token) if (token) { response.success = token.deadline > new Date().getTime() } if (response.success) { const userItem = adminUsers.find(_ => _.id === token.id) if (userItem) { const { password, ...other } = userItem user = other } } response.user = user res.json(response) }, [`GET ${ApiPrefix}/users`](req, res) { const { query } = req let { pageSize, page, ...other } = query pageSize = pageSize || 10 page = page || 1 let newData = database for (let key in other) { if ({}.hasOwnProperty.call(other, key)) { newData = newData.filter(item => { if ({}.hasOwnProperty.call(item, key)) { if (key === 'address') { return other[key].every(iitem => item[key].indexOf(iitem) > -1) } else if (key === 'createTime') { const start = new Date(other[key][0]).getTime() const end = new Date(other[key][1]).getTime() const now = new Date(item[key]).getTime() if (start && end) { return now >= start && now <= end } return true } return ( String(item[key]) .trim() .indexOf(decodeURI(other[key]).trim()) > -1 ) } return true }) } } res.status(200).json({ data: newData.slice((page - 1) * pageSize, page * pageSize), total: newData.length, }) }, [`POST ${ApiPrefix}/users/delete`](req, res) { const { ids=[] } = req.body database = database.filter(item => !ids.some(_ => _ === item.id)) res.status(204).end() }, [`POST ${ApiPrefix}/user`](req, res) { const newData = req.body newData.createTime = Mock.mock('@now') newData.avatar = newData.avatar || Mock.Random.image( '100x100', Mock.Random.color(), '#757575', 'png', newData.nickName.substr(0, 1) ) newData.id = Mock.mock('@id') database.unshift(newData) res.status(200).end() }, [`GET ${ApiPrefix}/user/:id`](req, res) { const { id } = req.params const data = queryArray(database, id, 'id') if (data) { res.status(200).json(data) } else { res.status(200).json(NOTFOUND) } }, [`DELETE ${ApiPrefix}/user/:id`](req, res) { const { id } = req.params const data = queryArray(database, id, 'id') if (data) { database = database.filter(item => item.id !== id) res.status(204).end() } else { res.status(200).json(NOTFOUND) } }, [`PATCH ${ApiPrefix}/user/:id`](req, res) { const { id } = req.params const editItem = req.body let isExist = false database = database.map(item => { if (item.id === id) { isExist = true return Object.assign({}, item, editItem) } return item }) if (isExist) { res.status(201).end() } else { res.status(200).json(NOTFOUND) } }, } ```
/content/code_sandbox/mock/user.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
1,527
```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>antd-admin - An admin dashboard application demo built upon Ant Design and UmiJS</title> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta name="description" content="An admin dashboard application demo built upon Ant Design and UmiJS"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <link rel="stylesheet" href="//unpkg.com/docsify/lib/themes/vue.css"> <link rel="icon" href="/_media/favicon.ico" /> </head> <body> <nav data-cloak class="app-nav"> <a href="/">En</a> <a href="#/zh-cn/"></a> </nav> <div id="app">Loading...</div> <script> window.$docsify = { name: 'AntD Admin', loadSidebar: true, maxLevel: 3, subMaxLevel: 3, auto2top: true, autoHeader: true, repo: 'zuiidea/antd-admin', themeColor: '#1890ff', search: { paths: 'auto', placeholder: { '/zh-cn/': '', '/': 'Type to search' }, noData: { '/zh-cn/': '', '/': 'No Results' } } } // if (typeof navigator.serviceWorker !== 'undefined') { // navigator.serviceWorker.register('sw.js') // } </script> <script src="//unpkg.com/docsify/lib/docsify.min.js"></script> <script src="//unpkg.com/docsify/lib/plugins/search.min.js"></script> <script src="//unpkg.com/docsify/lib/plugins/emoji.min.js"></script> <script src="//unpkg.com/docsify/lib/plugins/zoom-image.min.js"></script> <script src="//unpkg.com/docsify-copy-code"></script> </body> </html> ```
/content/code_sandbox/docs/index.html
html
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
468
```javascript import { Mock, Constant } from './_utils' const { ApiPrefix, Color } = Constant const Dashboard = Mock.mock({ 'sales|8': [ { 'name|+1': 2008, 'Clothes|200-500': 1, 'Food|180-400': 1, 'Electronics|300-550': 1, }, ], cpu: { 'usage|50-600': 1, space: 825, 'cpu|40-90': 1, 'data|20': [ { 'cpu|20-80': 1, }, ], }, browser: [ { name: 'Google Chrome', percent: 43.3, status: 1, }, { name: 'Mozilla Firefox', percent: 33.4, status: 2, }, { name: 'Apple Safari', percent: 34.6, status: 3, }, { name: 'Internet Explorer', percent: 12.3, status: 4, }, { name: 'Opera Mini', percent: 3.3, status: 1, }, { name: 'Chromium', percent: 2.53, status: 1, }, ], user: { name: 'github', sales: 3241, sold: 3556, }, 'completed|12': [ { 'name|+1': 2008, 'Task complete|200-1000': 1, 'Cards Complete|200-1000': 1, }, ], 'comments|5': [ { name: '@last', 'status|1-3': 1, content: '@sentence', avatar() { return Mock.Random.image( '48x48', Mock.Random.color(), '#757575', 'png', this.name.substr(0, 1) ) }, date() { return `2016-${Mock.Random.date('MM-dd')} ${Mock.Random.time( 'HH:mm:ss' )}` }, }, ], 'recentSales|36': [ { 'id|+1': 1, name: '@last', 'status|1-4': 1, date() { return `${Mock.Random.integer(2015, 2016)}-${Mock.Random.date( 'MM-dd' )} ${Mock.Random.time('HH:mm:ss')}` }, 'price|10-200.1-2': 1, }, ], quote: { name: 'Joho Doe', title: 'Graphic Designer', content: "I'm selfish, impatient and a little insecure. I make mistakes, I am out of control and at times hard to handle. But if you can't handle me at my worst, then you sure as hell don't deserve me at my best.", avatar: '//cdn.antd-admin.zuiidea.com/bc442cf0cc6f7940dcc567e465048d1a8d634493198c4-sPx5BR_fw236', }, numbers: [ { icon: 'pay-circle-o', color: Color.green, title: 'Online Review', number: 2781, }, { icon: 'team', color: Color.blue, title: 'New Customers', number: 3241, }, { icon: 'message', color: Color.purple, title: 'Active Projects', number: 253, }, { icon: 'shopping-cart', color: Color.red, title: 'Referrals', number: 4324, }, ], }) module.exports = { [`GET ${ApiPrefix}/dashboard`](req, res) { res.json(Dashboard) }, } ```
/content/code_sandbox/mock/dashboard.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
867
```unknown ```
/content/code_sandbox/docs/.nojekyll
unknown
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
1
```javascript /* =========================================================== * docsify sw.js * =========================================================== * Register service worker. * ========================================================== */ const RUNTIME = 'docsify' const HOSTNAME_WHITELIST = [ self.location.hostname, 'fonts.gstatic.com', 'fonts.googleapis.com', 'unpkg.com' ] // The Util Function to hack URLs of intercepted requests const getFixedUrl = (req) => { var now = Date.now() var url = new URL(req.url) // 1. fixed http URL // Just keep syncing with location.protocol // fetch(httpURL) belongs to active mixed content. // And fetch(httpRequest) is not supported yet. url.protocol = self.location.protocol // 2. add query for caching-busting. // Github Pages served with Cache-Control: max-age=600 // max-age on mutable content is error-prone, with SW life of bugs can even extend. // Until cache mode of Fetch API landed, we have to workaround cache-busting with query string. // Cache-Control-Bug: path_to_url if (url.hostname === self.location.hostname) { url.search += (url.search ? '&' : '?') + 'cache-bust=' + now } return url.href } /** * @Lifecycle Activate * New one activated when old isnt being used. * * waitUntil(): activating ====> activated */ self.addEventListener('activate', event => { event.waitUntil(self.clients.claim()) }) /** * @Functional Fetch * All network requests are being intercepted here. * * void respondWith(Promise<Response> r) */ self.addEventListener('fetch', event => { // Skip some of cross-origin requests, like those for Google Analytics. if (HOSTNAME_WHITELIST.indexOf(new URL(event.request.url).hostname) > -1) { // Stale-while-revalidate // similar to HTTP's stale-while-revalidate: path_to_url // Upgrade from Jake's to Surma's: path_to_url const cached = caches.match(event.request) const fixedUrl = getFixedUrl(event.request) const fetched = fetch(fixedUrl, { cache: 'no-store' }) const fetchedCopy = fetched.then(resp => resp.clone()) // Call respondWith() with whatever we get first. // If the fetch fails (e.g disconnected), wait for the cache. // If theres nothing in cache, wait for the fetch. // If neither yields a response, return offline pages. event.respondWith( Promise.race([fetched.catch(_ => cached), cached]) .then(resp => resp || fetched) .catch(_ => { /* eat any errors */ }) ) // Update the cache with the version we fetched (only for ok status) event.waitUntil( Promise.all([fetchedCopy, caches.open(RUNTIME)]) .then(([response, cache]) => response.ok && cache.put(event.request, response)) .catch(_ => { /* eat any errors */ }) ) } }) ```
/content/code_sandbox/docs/sw.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
648
```less .error { color: black; text-align: center; position: absolute; top: 30%; margin-top: -50px; left: 50%; margin-left: -100px; width: 200px; :global .anticon { font-size: 48px; margin-bottom: 16px; } h1 { font-family: cursive; } } ```
/content/code_sandbox/src/pages/404.less
less
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
93
```javascript /** * Youdao Translate, My private account is for testing purposes only. * Please go to the official account to apply for an account. Thank you for your cooperation. * APP ID055c2d71f9a05214 * Secret keyZcpuQxQW3NkQeKVkqrXIKQYXH57g2KuN */ /* eslint-disable */ const md5 = require('md5') const qs = require('qs') const fs = require('fs') const path = require('path') const axios = require('axios') const jsonFormat = require('json-format') const { i18n } = require('../src/utils/config') const { languages, defaultLanguage } = i18n const locales = {} languages.forEach(item => { locales[item.key] = require(`../src/locales/${item.key}/messages.json`) }) const youdao = ({ q, from, to }) => new Promise((resolve, reject) => { { const appid = '055c2d71f9a05214' const appse = 'ZcpuQxQW3NkQeKVkqrXIKQYXH57g2KuN' const salt = Date.now() const sign = md5(appid + q + salt + appse) const query = qs.stringify({ q, from, to, appKey: appid, salt, sign, }) axios.get(`path_to_url{query}`).then(({ data }) => { if (data.query && data.translation[0]) { resolve(data.translation[0]) } else { resolve(q) } }) } }) const transform = async ({ from, to, locales, outputPath }) => { for (const key in locales[from]) { if (locales[to][key]) { console.log(`add to skip: ${key}`) } else { let res = key let way = 'youdao' if (key.indexOf('/') !== 0) { const reg = '{([^{}]*)}' const tasks = key .match(new RegExp(`${reg}|((?<=(${reg}|^)).*?(?=(${reg}|$)))`, 'g')) .map(item => { if (new RegExp(reg).test(item)) { return Promise.resolve(item) } return youdao({ q: item, from, to, }) }) res = (await Promise.all(tasks)).join('') } else { res = `/${to + key}` way = 'link' } if (res !== key) { locales[to][key] = res console.log(`${way}: ${from} -> ${to}: ${key} -> ${res}`) } else { console.log(`same: ${from} -> ${to}: ${key}`) } } } await fs.writeFileSync( path.resolve(__dirname, outputPath), jsonFormat(locales[to], { type: 'space', size: 2, }) ) } ;(async () => { const tasks = languages .map(item => ({ from: defaultLanguage, to: item.key, })) .filter(item => item.from !== item.to) for (const item of tasks) { console.log(`start: ${item.from} -> ${item.to}`) await transform({ from: item.from, to: item.to, locales, outputPath: `../src/locales/${item.to}/messages.json`, }) console.log(`completed: ${item.from} -> ${item.to}`) } console.log('All translations have been completed.') })() ```
/content/code_sandbox/scripts/translate.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
793
```xml import React from 'react' import { FrownOutlined } from '@ant-design/icons' import { Page } from 'components' import styles from './404.less' const Error = () => ( <Page inner> <div className={styles.error}> <FrownOutlined /> <h1>404 Not Found</h1> </div> </Page> ) export default Error ```
/content/code_sandbox/src/pages/404.tsx
xml
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
84
```javascript import React, { PureComponent } from 'react' import { Redirect } from 'umi' import { t } from "@lingui/macro" class Index extends PureComponent { render() { return <Redirect to={t`/dashboard`} /> } } export default Index ```
/content/code_sandbox/src/pages/index.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
58
```less .dashboard { position: relative; :global { .ant-card { border-radius: 0; margin-bottom: 24px; &:hover { box-shadow: 4px 4px 40px rgba(0, 0, 0, 0.05); } } .ant-card-body { overflow-x: hidden; } } .weather { &:hover { box-shadow: 4px 4px 40px rgba(143, 201, 251, 0.6); } } .quote { &:hover { box-shadow: 4px 4px 40px rgba(246, 152, 153, 0.6); } } } ```
/content/code_sandbox/src/pages/dashboard/index.less
less
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
165
```javascript import { parse } from 'qs' import modelExtend from 'dva-model-extend' import api from 'api' const { pathToRegexp } = require("path-to-regexp") import { model } from 'utils/model' const { queryDashboard, queryWeather } = api const avatar = '//cdn.antd-admin.zuiidea.com/bc442cf0cc6f7940dcc567e465048d1a8d634493198c4-sPx5BR_fw236.jpeg' export default modelExtend(model, { namespace: 'dashboard', state: { weather: { city: '', temperature: '30', name: '', icon: '//cdn.antd-admin.zuiidea.com/sun.png', }, sales: [], quote: { avatar, }, numbers: [], recentSales: [], comments: [], completed: [], browser: [], cpu: {}, user: { avatar, }, }, subscriptions: { setup({ dispatch, history }) { history.listen(({ pathname }) => { if ( pathToRegexp('/dashboard').exec(pathname) || pathToRegexp('/').exec(pathname) ) { dispatch({ type: 'query' }) dispatch({ type: 'queryWeather' }) } }) }, }, effects: { *query({ payload }, { call, put }) { const data = yield call(queryDashboard, parse(payload)) yield put({ type: 'updateState', payload: data, }) }, *queryWeather({ payload = {} }, { call, put }) { payload.location = 'shenzhen' const result = yield call(queryWeather, payload) const { success } = result if (success) { const data = result.results[0] const weather = { city: data.location.name, temperature: data.now.temperature, name: data.now.text, icon: `//cdn.antd-admin.zuiidea.com/web/icons/3d_50/${data.now.code}.png`, } yield put({ type: 'updateState', payload: { weather, }, }) } }, }, }) ```
/content/code_sandbox/src/pages/dashboard/model.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
473
```javascript import React from 'react' import PropTypes from 'prop-types' import { Card } from 'antd' import CountUp from 'react-countup' import iconMap from 'utils/iconMap' import styles from './numberCard.less' function NumberCard({ icon, color, title, number, countUp }) { return ( <Card className={styles.numberCard} bordered={false} bodyStyle={{ padding: 10 }} > <span className={styles.iconWarp} style={{ color }}> {iconMap[icon]} </span> <div className={styles.content}> <p className={styles.title}>{title || 'No Title'}</p> <p className={styles.number}> <CountUp start={0} end={number} duration={2.75} useEasing useGrouping separator="," {...(countUp || {})} /> </p> </div> </Card> ) } NumberCard.propTypes = { icon: PropTypes.string, color: PropTypes.string, title: PropTypes.string, number: PropTypes.number, countUp: PropTypes.object, } export default NumberCard ```
/content/code_sandbox/src/pages/dashboard/components/numberCard.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
255
```less .cpu { .number { display: flex; height: 64px; justify-content: space-between; margin-bottom: 32px; .item { text-align: center; height: 64px; width: 100%; position: relative; & + .item { &::before { content: ''; display: block; width: 1px; height: 40px; position: absolute; background: #f5f5f5; top: 12px; } } p { color: #757575; &:first-child { font-size: 16px; } &:last-child { font-size: 20px; font-weight: 700; } } } } } ```
/content/code_sandbox/src/pages/dashboard/components/cpu.less
less
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
177
```javascript import React, { PureComponent } from 'react' import PropTypes from 'prop-types' import { connect } from 'umi' import { Row, Col, Card } from 'antd' import { Color } from 'utils' import { Page, ScrollBar } from 'components' import { NumberCard, Quote, Sales, Weather, RecentSales, Comments, Completed, Browser, Cpu, User, } from './components' import styles from './index.less' import store from 'store' const bodyStyle = { bodyStyle: { height: 432, background: '#fff', }, } @connect(({ app, dashboard, loading }) => ({ dashboard, loading, })) class Dashboard extends PureComponent { render() { const userDetail = store.get('user') const { avatar, username } = userDetail const { dashboard, loading } = this.props const { weather, sales, quote, numbers, recentSales, comments, completed, browser, cpu, user, } = dashboard const numberCards = numbers.map((item, key) => ( <Col key={key} lg={6} md={12}> <NumberCard {...item} /> </Col> )) return ( <Page // loading={loading.models.dashboard && sales.length === 0} className={styles.dashboard} > <Row gutter={24}> {numberCards} <Col lg={18} md={24}> <Card bordered={false} bodyStyle={{ padding: '24px 36px 24px 0', }} > <Sales data={sales} /> </Card> </Col> <Col lg={6} md={24}> <Row gutter={24}> <Col lg={24} md={12}> <Card bordered={false} className={styles.weather} bodyStyle={{ padding: 0, height: 204, background: Color.blue, }} > <Weather {...weather} loading={loading.effects['dashboard/queryWeather']} /> </Card> </Col> <Col lg={24} md={12}> <Card bordered={false} className={styles.quote} bodyStyle={{ padding: 0, height: 204, background: Color.peach, }} > <ScrollBar> <Quote {...quote} /> </ScrollBar> </Card> </Col> </Row> </Col> <Col lg={12} md={24}> <Card bordered={false} {...bodyStyle}> <RecentSales data={recentSales} /> </Card> </Col> <Col lg={12} md={24}> <Card bordered={false} {...bodyStyle}> <ScrollBar> <Comments data={comments} /> </ScrollBar> </Card> </Col> <Col lg={24} md={24}> <Card bordered={false} bodyStyle={{ padding: '24px 36px 24px 0', }} > <Completed data={completed} /> </Card> </Col> <Col lg={8} md={24}> <Card bordered={false} {...bodyStyle}> <Browser data={browser} /> </Card> </Col> <Col lg={8} md={24}> <Card bordered={false} {...bodyStyle}> <ScrollBar> <Cpu {...cpu} /> </ScrollBar> </Card> </Col> <Col lg={8} md={24}> <Card bordered={false} bodyStyle={{ ...bodyStyle.bodyStyle, padding: 0 }} > <User {...user} avatar={avatar} username={username} /> </Card> </Col> </Row> </Page> ) } } Dashboard.propTypes = { dashboard: PropTypes.object, loading: PropTypes.object, } export default Dashboard ```
/content/code_sandbox/src/pages/dashboard/index.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
881
```less @import '~themes/vars'; .sales { overflow: hidden; .title { margin-left: 32px; font-size: 16px; } } .radiusdot { width: 12px; height: 12px; margin-right: 8px; border-radius: 50%; display: inline-block; } .legend { text-align: right; color: #999; font-size: 14px; li { height: 48px; line-height: 48px; display: inline-block; & + li { margin-left: 24px; } } } .tooltip { background: #fff; padding: 20px; font-size: 14px; .tiptitle { font-weight: 700; font-size: 16px; margin-bottom: 8px; } .tipitem { height: 32px; line-height: 32px; } } ```
/content/code_sandbox/src/pages/dashboard/components/sales.less
less
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
218
```less @import '~themes/vars'; .sales { .title { margin-left: 32px; font-size: 16px; } } .radiusdot { width: 12px; height: 12px; margin-right: 8px; border-radius: 50%; display: inline-block; } .legend { text-align: right; color: #999; font-size: 14px; li { height: 48px; line-height: 48px; display: inline-block; & + li { margin-left: 24px; } } } .tooltip { background: #fff; padding: 20px; font-size: 14px; .tiptitle { font-weight: 700; font-size: 16px; margin-bottom: 8px; } .tipitem { height: 32px; line-height: 32px; } } ```
/content/code_sandbox/src/pages/dashboard/components/completed.less
less
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
213
```less @import '~themes/vars'; .user { .header { display: flex; justify-content: center; text-align: center; color: #fff; height: 200px; background-size: cover; align-items: center; .headerinner { z-index: 2; } &::after { content: ''; background-image: url('./user-background.png'); background-size: cover; position: absolute; width: 100%; height: 200px; left: 0; top: 0; opacity: 0.4; z-index: 1; } .name { font-size: 16px; margin-top: 8px; } } .number { display: flex; height: 116px; justify-content: space-between; border-bottom: solid 1px #f5f5f5; .item { text-align: center; height: 116px; width: 100%; position: relative; padding: 30px 0; & + .item { &::before { content: ''; display: block; width: 1px; height: 116px; position: absolute; background: #f5f5f5; top: 0; } } p { color: #757575; &:first-child { font-size: 16px; } &:last-child { font-size: 20px; font-weight: 700; } } } } .footer { height: 116px; display: flex; justify-content: center; align-items: center; :global .ant-btn { color: @purple; border-color: @purple; padding: 6px 16px; } } } ```
/content/code_sandbox/src/pages/dashboard/components/user.less
less
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
418
```less @import '~themes/vars'; .comments { :global .ant-table-thead > tr > th { background: #fff; border-bottom: solid 1px @border-color-base; } .avatar { width: 48px; height: 48px; background-position: center; background-size: cover; border-radius: 50%; background: #f8f8f8; display: inline-block; } .content { text-align: left; color: #757575; } .date { color: #a3a3a3; line-height: 30px; } .daterow { display: flex; justify-content: space-between; } .name { font-size: 14px; color: #474747; text-align: left; } .avatarcolumn { vertical-align: top; } } ```
/content/code_sandbox/src/pages/dashboard/components/comments.less
less
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
204
```javascript import React from 'react' import PropTypes from 'prop-types' import styles from './quote.less' function Quote({ name, content, title, avatar }) { return ( <div className={styles.quote}> <div className={styles.inner}>{content}</div> <div className={styles.footer}> <div className={styles.description}> <p>-{name}-</p> <p>{title}</p> </div> <div className={styles.avatar} style={{ backgroundImage: `url(${avatar})` }} /> </div> </div> ) } Quote.propTypes = { name: PropTypes.string, content: PropTypes.string, title: PropTypes.string, avatar: PropTypes.string, } export default Quote ```
/content/code_sandbox/src/pages/dashboard/components/quote.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
162
```javascript import React from 'react' import PropTypes from 'prop-types' import { Table, Tag } from 'antd' import { Color } from 'utils' import styles from './comments.less' const status = { 1: { color: Color.green, text: 'APPROVED', }, 2: { color: Color.yellow, text: 'PENDING', }, 3: { color: Color.red, text: 'REJECTED', }, } function Comments({ data }) { const columns = [ { title: 'avatar', dataIndex: 'avatar', width: 48, className: styles.avatarcolumn, render: text => ( <span style={{ backgroundImage: `url(${text})` }} className={styles.avatar} /> ), }, { title: 'content', dataIndex: 'content', render: (text, it) => ( <div> <h5 className={styles.name}>{it.name}</h5> <p className={styles.content}>{it.content}</p> <div className={styles.daterow}> <Tag color={status[it.status].color}>{status[it.status].text}</Tag> <span className={styles.date}>{it.date}</span> </div> </div> ), }, ] return ( <div className={styles.comments}> <Table pagination={false} showHeader={false} columns={columns} rowKey='avatar' dataSource={data.filter((item, key) => key < 3)} /> </div> ) } Comments.propTypes = { data: PropTypes.array, } export default Comments ```
/content/code_sandbox/src/pages/dashboard/components/comments.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
366
```javascript import React from 'react' import PropTypes from 'prop-types' import { Button, Avatar } from 'antd' import CountUp from 'react-countup' import { Color } from 'utils' import styles from './user.less' const countUpProps = { start: 0, duration: 2.75, useEasing: true, useGrouping: true, separator: ',', } function User({ avatar, username, sales = 0, sold = 0 }) { return ( <div className={styles.user}> <div className={styles.header}> <div className={styles.headerinner}> <Avatar size="large" src={avatar} /> <h5 className={styles.name}>{username}</h5> </div> </div> <div className={styles.number}> <div className={styles.item}> <p>EARNING SALES</p> <p style={{ color: Color.green }}> <CountUp end={sales} prefix="$" {...countUpProps} /> </p> </div> <div className={styles.item}> <p>ITEM SOLD</p> <p style={{ color: Color.blue }}> <CountUp end={sold} {...countUpProps} /> </p> </div> </div> <div className={styles.footer}> <Button type="ghost" size="large"> View Profile </Button> </div> </div> ) } User.propTypes = { avatar: PropTypes.string, username: PropTypes.string, sales: PropTypes.number, sold: PropTypes.number, } export default User ```
/content/code_sandbox/src/pages/dashboard/components/user.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
353
```javascript import React from 'react' import PropTypes from 'prop-types' import classnames from 'classnames' import { Color } from 'utils' import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, } from 'recharts' import styles from './sales.less' function Sales({ data }) { return ( <div className={styles.sales}> <div className={styles.title}>Yearly Sales</div> <ResponsiveContainer minHeight={360}> <LineChart data={data}> <Legend verticalAlign="top" content={prop => { const { payload } = prop return ( <ul className={classnames({ [styles.legend]: true, clearfix: true, })} > {payload.map((item, key) => ( <li key={key}> <span className={styles.radiusdot} style={{ background: item.color }} /> {item.value} </li> ))} </ul> ) }} /> <XAxis dataKey="name" axisLine={{ stroke: Color.borderBase, strokeWidth: 1 }} tickLine={false} /> <YAxis axisLine={false} tickLine={false} /> <CartesianGrid vertical={false} stroke={Color.borderBase} strokeDasharray="3 3" /> <Tooltip wrapperStyle={{ border: 'none', boxShadow: '4px 4px 40px rgba(0, 0, 0, 0.05)', }} content={content => { const list = content.payload.map((item, key) => ( <li key={key} className={styles.tipitem}> <span className={styles.radiusdot} style={{ background: item.color }} /> {`${item.name}:${item.value}`} </li> )) return ( <div className={styles.tooltip}> <p className={styles.tiptitle}>{content.label}</p> {content.payload && <ul>{list}</ul>} </div> ) }} /> <Line type="monotone" dataKey="Food" stroke={Color.purple} strokeWidth={3} dot={{ fill: Color.purple }} activeDot={{ r: 5, strokeWidth: 0 }} /> <Line type="monotone" dataKey="Clothes" stroke={Color.red} strokeWidth={3} dot={{ fill: Color.red }} activeDot={{ r: 5, strokeWidth: 0 }} /> <Line type="monotone" dataKey="Electronics" stroke={Color.green} strokeWidth={3} dot={{ fill: Color.green }} activeDot={{ r: 5, strokeWidth: 0 }} /> </LineChart> </ResponsiveContainer> </div> ) } Sales.propTypes = { data: PropTypes.array, } export default Sales ```
/content/code_sandbox/src/pages/dashboard/components/sales.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
662
```javascript import React from 'react' import dayjs from 'dayjs' import PropTypes from 'prop-types' import { Table, Tag } from 'antd' import { Color } from 'utils' import styles from './recentSales.less' const status = { 1: { color: Color.green, text: 'SALE', }, 2: { color: Color.yellow, text: 'REJECT', }, 3: { color: Color.red, text: 'TAX', }, 4: { color: Color.blue, text: 'EXTENDED', }, } function RecentSales({ data }) { const columns = [ { title: 'NAME', dataIndex: 'name', }, { title: 'STATUS', dataIndex: 'status', render: text => <Tag color={status[text].color}>{status[text].text}</Tag>, }, { title: 'DATE', dataIndex: 'date', render: text => dayjs(text).format('YYYY-MM-DD'), }, { title: 'PRICE', dataIndex: 'price', render: (text, it) => ( <span style={{ color: status[it.status].color }}>${text}</span> ), }, ] return ( <div className={styles.recentsales}> <Table pagination={false} columns={columns} rowKey='id' dataSource={data.filter((item, key) => key < 5)} /> </div> ) } RecentSales.propTypes = { data: PropTypes.array, } export default RecentSales ```
/content/code_sandbox/src/pages/dashboard/components/recentSales.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
352
```less @import '~themes/vars'; .quote { color: #fff; height: 100%; width: 100%; padding: 24px; font-size: 16px; font-weight: 700; .inner { text-overflow: ellipsis; word-wrap: normal; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 4; overflow: hidden; text-indent: 24px; } .footer { position: relative; margin-top: 14px; .description { width: 100%; p { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-right: 64px; text-align: right; &:last-child { font-weight: 100; } } } .avatar { width: 48px; height: 48px; background-position: center; background-size: cover; border-radius: 50%; position: absolute; right: 0; top: 0; } } } ```
/content/code_sandbox/src/pages/dashboard/components/quote.less
less
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
250
```javascript import React from 'react' import PropTypes from 'prop-types' import { Spin } from 'antd' import styles from './weather.less' function Weather({ city, icon, dateTime, temperature, name, loading }) { return ( <Spin spinning={loading}> <div className={styles.weather}> <div className={styles.left}> <div className={styles.icon} style={{ backgroundImage: `url(${icon})`, }} /> <p>{name}</p> </div> <div className={styles.right}> <h1 className={styles.temperature}>{`${temperature}`}</h1> <p className={styles.description}> {city},{dateTime} </p> </div> </div> </Spin> ) } Weather.propTypes = { city: PropTypes.string, icon: PropTypes.string, dateTime: PropTypes.string, temperature: PropTypes.string, name: PropTypes.string, loading: PropTypes.bool, } export default Weather ```
/content/code_sandbox/src/pages/dashboard/components/weather.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
211
```less @import '~themes/vars'; .recentsales { :global .ant-table-thead > tr > th { background: #fff; border-bottom: solid 1px @border-color-base; } } ```
/content/code_sandbox/src/pages/dashboard/components/recentSales.less
less
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
47
```less .percent { text-align: right !important; } .name { text-align: left !important; } ```
/content/code_sandbox/src/pages/dashboard/components/browser.less
less
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
23
```less @import '~themes/vars'; .weather { color: #fff; height: 204px; padding: 24px; justify-content: space-between; display: flex; font-size: 14px; .left { display: flex; flex-direction: column; width: 64px; padding-top: 55px; .icon { width: 64px; height: 64px; background-position: center; background-size: contain; } p { margin-top: 16px; } } .right { display: flex; flex-direction: column; width: 50%; .temperature { font-size: 36px; text-align: right; height: 64px; color: #fff; } .description { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: right; } } } ```
/content/code_sandbox/src/pages/dashboard/components/weather.less
less
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
216
```javascript import React from 'react' import PropTypes from 'prop-types' import { Table, Tag } from 'antd' import { Color } from 'utils' import styles from './browser.less' const status = { 1: { color: Color.green, }, 2: { color: Color.red, }, 3: { color: Color.blue, }, 4: { color: Color.yellow, }, } function Browser({ data }) { const columns = [ { title: 'name', dataIndex: 'name', className: styles.name, }, { title: 'percent', dataIndex: 'percent', className: styles.percent, render: (text, it) => <Tag color={status[it.status].color}>{text}%</Tag>, }, ] return ( <Table pagination={false} showHeader={false} columns={columns} rowKey='name' dataSource={data} /> ) } Browser.propTypes = { data: PropTypes.array, } export default Browser ```
/content/code_sandbox/src/pages/dashboard/components/browser.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
231
```less @import '~themes/vars'; .numberCard { padding: 32px; margin-bottom: 24px; cursor: pointer; .iconWarp { font-size: 54px; float: left; } .content { width: 100%; padding-left: 78px; .title { line-height: 16px; font-size: 16px; margin-bottom: 8px; height: 16px; .text-overflow(); } .number { line-height: 32px; font-size: 24px; height: 32px; .text-overflow(); margin-bottom: 0; } } } ```
/content/code_sandbox/src/pages/dashboard/components/numberCard.less
less
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
158
```javascript import React from 'react' import PropTypes from 'prop-types' import classnames from 'classnames' import { Color } from 'utils' import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, } from 'recharts' import styles from './completed.less' function Completed({ data }) { return ( <div className={styles.sales}> <div className={styles.title}>TEAM TOTAL COMPLETED</div> <ResponsiveContainer minHeight={360}> <AreaChart data={data}> <Legend verticalAlign="top" content={prop => { const { payload } = prop return ( <ul className={classnames({ [styles.legend]: true, clearfix: true, })} > {payload.map((item, key) => ( <li key={key}> <span className={styles.radiusdot} style={{ background: item.color }} /> {item.value} </li> ))} </ul> ) }} /> <XAxis dataKey="name" axisLine={{ stroke: Color.borderBase, strokeWidth: 1 }} tickLine={false} /> <YAxis axisLine={false} tickLine={false} /> <CartesianGrid vertical={false} stroke={Color.borderBase} strokeDasharray="3 3" /> <Tooltip wrapperStyle={{ border: 'none', boxShadow: '4px 4px 40px rgba(0, 0, 0, 0.05)', }} content={content => { const list = content.payload.map((item, key) => ( <li key={key} className={styles.tipitem}> <span className={styles.radiusdot} style={{ background: item.color }} /> {`${item.name}:${item.value}`} </li> )) return ( <div className={styles.tooltip}> <p className={styles.tiptitle}>{content.label}</p> {content.payload && <ul>{list}</ul>} </div> ) }} /> <Area type="monotone" dataKey="Task complete" stroke={Color.grass} fill={Color.grass} strokeWidth={2} dot={{ fill: '#fff' }} activeDot={{ r: 5, fill: '#fff', stroke: Color.green }} /> <Area type="monotone" dataKey="Cards Complete" stroke={Color.sky} fill={Color.sky} strokeWidth={2} dot={{ fill: '#fff' }} activeDot={{ r: 5, fill: '#fff', stroke: Color.blue }} /> </AreaChart> </ResponsiveContainer> </div> ) } Completed.propTypes = { data: PropTypes.array, } export default Completed ```
/content/code_sandbox/src/pages/dashboard/components/completed.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
635
```javascript import NumberCard from './numberCard' import Quote from './quote' import Sales from './sales' import Weather from './weather' import RecentSales from './recentSales' import Comments from './comments' import Completed from './completed' import Browser from './browser' import Cpu from './cpu' import User from './user' export { NumberCard, Quote, Sales, Weather, RecentSales, Comments, Completed, Browser, Cpu, User, } ```
/content/code_sandbox/src/pages/dashboard/components/index.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
102
```javascript import { request, config } from 'utils' const { APIV1 } = config export function query(params) { params.key = 'i7sau1babuzwhycn' return request({ url: `${APIV1}/weather/now.json`, method: 'get', data: params, }) } ```
/content/code_sandbox/src/pages/dashboard/services/weather.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
73
```javascript import React from 'react' import PropTypes from 'prop-types' import { Color } from 'utils' import CountUp from 'react-countup' import { LineChart, Line, XAxis, YAxis, CartesianGrid, ResponsiveContainer, } from 'recharts' import styles from './cpu.less' const countUpProps = { start: 0, duration: 2.75, useEasing: true, useGrouping: true, separator: ',', } function Cpu({ usage = 0, space = 0, cpu = 0, data }) { return ( <div className={styles.cpu}> <div className={styles.number}> <div className={styles.item}> <p>usage</p> <p> <CountUp end={usage} suffix="GB" {...countUpProps} /> </p> </div> <div className={styles.item}> <p>space</p> <p> <CountUp end={space} suffix="GB" {...countUpProps} /> </p> </div> <div className={styles.item}> <p>cpu</p> <p> <CountUp end={cpu} suffix="%" {...countUpProps} /> </p> </div> </div> <ResponsiveContainer minHeight={300}> <LineChart data={data} margin={{ left: -40 }}> <XAxis dataKey="name" axisLine={{ stroke: Color.borderBase, strokeWidth: 1 }} tickLine={false} /> <YAxis axisLine={false} tickLine={false} /> <CartesianGrid vertical={false} stroke={Color.borderBase} strokeDasharray="3 3" /> <Line type="monotone" connectNulls dataKey="cpu" stroke={Color.blue} fill={Color.blue} /> </LineChart> </ResponsiveContainer> </div> ) } Cpu.propTypes = { data: PropTypes.array, usage: PropTypes.number, space: PropTypes.number, cpu: PropTypes.number, } export default Cpu ```
/content/code_sandbox/src/pages/dashboard/components/cpu.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
480
```javascript import { request, config } from 'utils' const { api } = config const { dashboard } = api export function query(params) { return request({ url: dashboard, method: 'get', data: params, }) } ```
/content/code_sandbox/src/pages/dashboard/services/dashboard.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
54
```less @import '~themes/vars'; .result { height: 600px; width: 100%; background: @hover-color; border-color: #ddd; padding: 16px; margin-top: 16px; word-break: break-word; line-height: 2; overflow: scroll; } .requestList { padding-right: 24px; margin-bottom: 24px; .listItem { cursor: pointer; padding-left: 8px; &.lstItemActive { background-color: @hover-color; } .background-hover(); } } .paramsBlock { overflow: visible; opacity: 1; height: auto; transition: opacity 0.3s; &.hideParams { width: 0; height: 0; opacity: 0; overflow: hidden; } } ```
/content/code_sandbox/src/pages/request/index.less
less
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
195
```less @import '~themes/vars'; .form { position: absolute; top: 45%; left: 50%; margin: -160px 0 0 -160px; width: 320px; height: 320px; padding: 36px; box-shadow: 0 0 100px rgba(0, 0, 0, 0.08); button { width: 100%; } p { color: rgb(204, 204, 204); text-align: center; margin-top: 16px; font-size: 12px; display: flex; justify-content: space-between; } } .logo { text-align: center; cursor: pointer; margin-bottom: 24px; display: flex; justify-content: center; align-items: center; img { width: 40px; margin-right: 8px; } span { vertical-align: text-bottom; font-size: 16px; text-transform: uppercase; display: inline-block; font-weight: 700; color: @primary-color; .text-gradient(); } } .ant-spin-container, .ant-spin-nested-loading { height: 100%; } .footer { position: absolute; width: 100%; bottom: 0; } ```
/content/code_sandbox/src/pages/login/index.less
less
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
299
```javascript import { history } from 'umi' const { pathToRegexp } = require("path-to-regexp") import api from 'api' const { loginUser } = api export default { namespace: 'login', state: {}, // subscriptions: { // setup({ dispatch, history }) { // history.listen(location => { // if (pathToRegexp('/login').exec(location.pathname)) { // } // }) // }, // }, effects: { *login({ payload }, { put, call, select }) { const data = yield call(loginUser, payload) const { locationQuery } = yield select(_ => _.app) if (data.success) { const { from } = locationQuery yield put({ type: 'app/query' }) if (!pathToRegexp('/login').exec(from)) { if (['', '/'].includes(from)) history.push('/dashboard') else history.push(from) } else { history.push('/dashboard') } } else { throw data } }, }, } ```
/content/code_sandbox/src/pages/login/model.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
236
```javascript import React, { PureComponent, Fragment } from 'react' import PropTypes from 'prop-types' import { connect } from 'umi' import { Button, Row, Input, Form } from 'antd' import { GlobalFooter } from 'components' import { GithubOutlined } from '@ant-design/icons' import { t, Trans } from "@lingui/macro" import { setLocale } from 'utils' import config from 'utils/config' import styles from './index.less' const FormItem = Form.Item @connect(({ loading, dispatch }) => ({ loading, dispatch })) class Login extends PureComponent { render() { const { dispatch, loading } = this.props const handleOk = values => { dispatch({ type: 'login/login', payload: values }) } let footerLinks = [ { key: 'github', title: <GithubOutlined />, href: 'path_to_url blankTarget: true, }, ] if (config.i18n) { footerLinks = footerLinks.concat( config.i18n.languages.map(item => ({ key: item.key, title: ( <span onClick={setLocale.bind(null, item.key)}>{item.title}</span> ), })) ) } return ( <Fragment> <div className={styles.form}> <div className={styles.logo}> <img alt="logo" src={config.logoPath} /> <span>{config.siteName}</span> </div> <Form onFinish={handleOk} > <FormItem name="username" rules={[{ required: true }]} hasFeedback> <Input placeholder={t`Username`} /> </FormItem> <Trans id="Password" render={({translation}) => ( <FormItem name="password" rules={[{ required: true }]} hasFeedback> <Input type='password' placeholder={translation} required /> </FormItem>)} /> <Row> <Button type="primary" htmlType="submit" loading={loading.effects.login} > <Trans>Sign in</Trans> </Button> <p> <span className="margin-right"> <Trans>Username</Trans> guest </span> <span> <Trans>Password</Trans> guest </span> </p> </Row> </Form> </div> <div className={styles.footer}> <GlobalFooter links={footerLinks} copyright={config.copyright} /> </div> </Fragment> ) } } Login.propTypes = { form: PropTypes.object, dispatch: PropTypes.func, loading: PropTypes.object, } export default Login ```
/content/code_sandbox/src/pages/login/index.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
582
```javascript import React from 'react' import { request } from 'utils' import { apiPrefix } from 'utils/config' import { Row, Col, Select, Form, Input, Button, List, Tag, Checkbox } from 'antd' import classnames from 'classnames' import { CloseOutlined } from '@ant-design/icons' import { Trans } from "@lingui/macro" import api from '@/services/api' import { Page } from 'components' import styles from './index.less' const { Option } = Select const InputGroup = Input.Group const methods = ['POST', 'GET', 'PUT', 'PATCH', 'DELETE'] const methodTagColor = { GET: 'green', POST: 'orange', DELETE: 'red', PUT: 'geekblue', } const requests = Object.values(api).map(item => { let url = apiPrefix + item let method = 'GET' const paramsArray = item.split(' ') if (paramsArray.length === 2) { method = paramsArray[0] url = apiPrefix + paramsArray[1] } return { method, url, } }) let uuid = 2 class RequestPage extends React.Component { formRef = React.createRef() constructor(props) { super(props) this.state = { method: 'GET', url: '/api/v1/routes', keys: [1], result: null, visible: true, } } handleRequest = () => { const { method, url } = this.state this.formRef.current.validateFields() .then(values => { // values: { check[1]: true, key[1]: 'username', value[1]: 'admin' } const params = {} for (let i in values) { if (i.startsWith('check')) { const index = i.match(/check\[(\d+)\]/)[1] const key = values[`key[${index}]`] params[key] = values[`value[${index}]`] } } request({ method, url, data: params }).then(data => { this.setState({ result: JSON.stringify(data), }) }) }) .catch(errorInfo => { console.log(errorInfo) /* errorInfo: { values: { username: 'username', password: 'password', }, errorFields: [ { password: ['username'], errors: ['Please input your Password!'] }, ], outOfDate: false, } */ }) } handleClickListItem = ({ method, url }) => { this.setState({ method, url, keys: [uuid++], result: null, }) } handleInputChange = e => { this.setState({ url: e.target.value, }) } handleSelectChange = method => { this.setState({ method, }) } handleAddField = () => { const { keys } = this.state const nextKeys = keys.concat(uuid) uuid++ this.setState({ keys: nextKeys, }) } handleRemoveField = key => { const { keys } = this.state this.setState({ keys: keys.filter(item => item !== key), }) } handleVisible = () => { this.setState({ visible: !this.state.visible, }) } render() { const { result, url, method, keys, visible } = this.state return ( <Page inner> <Row> <Col lg={8} md={24}> <List className={styles.requestList} dataSource={requests} renderItem={item => ( <List.Item className={classnames(styles.listItem, { [styles.lstItemActive]: item.method === method && item.url === url, })} onClick={this.handleClickListItem.bind(this, item)} > <span style={{ width: 72 }}> <Tag style={{ marginRight: 8 }} color={methodTagColor[item.method]} > {item.method} </Tag> </span> {item.url} </List.Item> )} /> </Col> <Col lg={16} md={24}> <Row type="flex" justify="space-between"> <InputGroup compact size="large" style={{ flex: 1 }}> <Select size="large" value={method} style={{ width: 100 }} onChange={this.handleSelectChange} > {methods.map(item => ( <Option value={item} key={item}> {item} </Option> ))} </Select> <Input value={url} onChange={this.handleInputChange} style={{ width: 'calc(100% - 200px)' }} /> <Button ghost={visible} type={visible ? 'primary' : ''} onClick={this.handleVisible} size="large" > <Trans>Params</Trans> </Button> </InputGroup> <Button size="large" type="primary" style={{ width: 100 }} onClick={this.handleRequest} > <Trans>Send</Trans> </Button> </Row> <Form ref={this.formRef} name="control-ref" > <div className={classnames(styles.paramsBlock, { [styles.hideParams]: !visible, })} > {keys.map((key, index) => ( <Row gutter={8} type="flex" justify="start" align="middle" key={key} > <Col style={{ marginTop: 8 }}> <Form.Item name={`check[${key}]`} valuePropName="checked"> <Checkbox defaultChecked /> </Form.Item> </Col> <Col style={{ marginTop: 8 }}> <Form.Item name={`key[${key}]`}> <Input placeholder="Key" /> </Form.Item> </Col> <Col style={{ marginTop: 8 }}> <Form.Item name={`value[${key}]`}> <Input placeholder="Value" /> </Form.Item> </Col> <Col style={{ marginTop: 8 }}> <CloseOutlined onClick={this.handleRemoveField.bind(this, key)} style={{ cursor: 'pointer' }} /> </Col> </Row> ))} <Row style={{ marginTop: 8 }}> <Button onClick={this.handleAddField}> <Trans>Add Param</Trans> </Button> </Row> </div> </Form> <div className={styles.result}>{result}</div> </Col> </Row> </Page> ) } } export default RequestPage ```
/content/code_sandbox/src/pages/request/index.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
1,471
```javascript import React from 'react' import PropTypes from 'prop-types' import HighstockComponent from './HighstockComponent' import HighmapsComponent from './HighmapsComponent' import HighMoreComponent from './HighMoreComponent' const HighChartsComponent = ({ type }) => { if (type === 'Highmaps') return <HighmapsComponent /> if (type === 'HighMore') return <HighMoreComponent /> return <HighstockComponent /> } HighChartsComponent.propTypes = { type: PropTypes.string, } export default HighChartsComponent ```
/content/code_sandbox/src/pages/chart/highCharts/HighChartsComponent.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
111
```less .chart { :global { .ant-radio-wrapper { margin-bottom: 16px; } } } ```
/content/code_sandbox/src/pages/chart/highCharts/index.less
less
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
26
```javascript import React from 'react' import ReactHighcharts from 'react-highcharts' import HighchartsExporting from 'highcharts-exporting' import HighchartsMore from 'highcharts-more' HighchartsMore(ReactHighcharts.Highcharts) HighchartsExporting(ReactHighcharts.Highcharts) const config = { chart: { polar: true, }, xAxis: { categories: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ], }, series: [ { data: [ 29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, ], }, ], } const HighMoreComponent = () => { return <ReactHighcharts config={config} /> } export default HighMoreComponent ```
/content/code_sandbox/src/pages/chart/highCharts/HighMoreComponent.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
250
```javascript import React from 'react' import ReactHighmaps from 'react-highcharts/ReactHighmaps.src' import maps from './mapdata/europe' const config = { chart: { spacingBottom: 20, }, title: { text: 'Europe time zones', }, legend: { enabled: true, }, plotOptions: { map: { allAreas: false, joinBy: ['iso-a2', 'code'], dataLabels: { enabled: true, color: 'white', style: { fontWeight: 'bold', }, }, mapData: maps, tooltip: { headerFormat: '', pointFormat: '{point.name}: <b>{series.name}</b>', }, }, }, series: [ { name: 'UTC', data: ['IE', 'IS', 'GB', 'PT'].map(code => { return { code } }), }, { name: 'UTC + 1', data: [ 'NO', 'SE', 'DK', 'DE', 'NL', 'BE', 'LU', 'ES', 'FR', 'PL', 'CZ', 'AT', 'CH', 'LI', 'SK', 'HU', 'SI', 'IT', 'SM', 'HR', 'BA', 'YF', 'ME', 'AL', 'MK', ].map(code => { return { code } }), }, ], } const HighmapsComponent = () => { return <ReactHighmaps config={config} /> } export default HighmapsComponent ```
/content/code_sandbox/src/pages/chart/highCharts/HighmapsComponent.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
368
```javascript import React from 'react' import ReactHighstock from 'react-highcharts/ReactHighstock.src' const data = [ [1220832000000, 22.56], [1220918400000, 21.67], [1221004800000, 21.66], [1221091200000, 21.81], [1221177600000, 21.28], [1221436800000, 20.05], [1221523200000, 19.98], [1221609600000, 18.26], [1221696000000, 19.16], [1221782400000, 20.13], [1222041600000, 18.72], [1222128000000, 18.12], [1222214400000, 18.39], [1222300800000, 18.85], [1222387200000, 18.32], [1222646400000, 15.04], [1222732800000, 16.24], [1222819200000, 15.59], [1222905600000, 14.3], [1222992000000, 13.87], [1223251200000, 14.02], [1223337600000, 12.74], [1223424000000, 12.83], [1223510400000, 12.68], [1223596800000, 13.8], [1223856000000, 15.75], [1223942400000, 14.87], [1224028800000, 13.99], [1224115200000, 14.56], [1224201600000, 13.91], [1224460800000, 14.06], [1224547200000, 13.07], [1224633600000, 13.84], [1224720000000, 14.03], [1224806400000, 13.77], [1225065600000, 13.16], [1225152000000, 14.27], [1225238400000, 14.94], [1225324800000, 15.86], [1225411200000, 15.37], [1225670400000, 15.28], [1225756800000, 15.86], [1225843200000, 14.76], [1225929600000, 14.16], [1226016000000, 14.03], [1226275200000, 13.7], [1226361600000, 13.54], [1226448000000, 12.87], [1226534400000, 13.78], [1226620800000, 12.89], [1226880000000, 12.59], [1226966400000, 12.84], [1227052800000, 12.33], [1227139200000, 11.5], [1227225600000, 11.8], [1227484800000, 13.28], [1227571200000, 12.97], [1227657600000, 13.57], [1227830400000, 13.24], [1228089600000, 12.7], [1228176000000, 13.21], [1228262400000, 13.7], [1228348800000, 13.06], [1228435200000, 13.43], [1228694400000, 14.25], [1228780800000, 14.29], [1228867200000, 14.03], [1228953600000, 13.57], [1229040000000, 14.04], [1229299200000, 13.54], ] const config = { rangeSelector: { selected: 1, }, title: { text: 'AAPL Stock Price', }, series: [ { name: 'AAPL', data, tooltip: { valueDecimals: 2, }, }, ], } const HighstockComponent = () => { return <ReactHighstock config={config} /> } export default HighstockComponent ```
/content/code_sandbox/src/pages/chart/highCharts/HighstockComponent.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
1,030
```javascript import React from 'react' import { Radio } from 'antd' import { Page } from 'components' import HighChartsComponent from './HighChartsComponent' import styles from './index.less' const RadioGroup = Radio.Group const chartList = [ { label: 'Highstock', value: 'Highstock', }, { label: 'Highmaps', value: 'Highmaps', }, { label: 'HighMore', value: 'HighMore', }, ] class Chart extends React.Component { constructor() { super() this.state = { type: '', } this.handleRadioGroupChange = this.handleRadioGroupChange.bind(this) } handleRadioGroupChange(e) { this.setState({ type: e.target.value, }) } render() { return ( <Page inner> <RadioGroup options={chartList} defaultValue="Highstock" onChange={this.handleRadioGroupChange} /> <div className={styles.chart}> <HighChartsComponent type={this.state.type} /> </div> </Page> ) } } export default Chart ```
/content/code_sandbox/src/pages/chart/highCharts/index.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
248
```javascript import React from 'react' import PropTypes from 'prop-types' import AreaChartComponent from './AreaChartComponent' import BarChartComponent from './BarChartComponent' import LineChartComponent from './LineChartComponent' const ReChartsComponent = ({ type }) => { if (type === 'areaChart') return <AreaChartComponent /> if (type === 'barChart') return <BarChartComponent /> return <LineChartComponent /> } ReChartsComponent.propTypes = { type: PropTypes.string, } export default ReChartsComponent ```
/content/code_sandbox/src/pages/chart/Recharts/ReChartsComponent.js
javascript
2016-01-25T07:46:15
2024-08-16T00:03:22
antd-admin
zuiidea/antd-admin
9,618
111