-
Notifications
You must be signed in to change notification settings - Fork 13
/
rdp
executable file
·256 lines (226 loc) · 8.37 KB
/
rdp
1
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
#!/usr/bin/env python3
# rdp -- launch FreeRDP to make Remote Desktop connections
import argparse
import gi
import logging
import os
import socket
import subprocess
import sys
gi.require_version("Secret", "1")
from gi.repository import Secret
def die(msg):
if sys.stdin.isatty():
exit("error: %s" % msg)
else:
msg = msg.replace("&", "&") \
.replace("<", "<") \
.replace(">", ">")
subprocess.run(["zenity", "--error",
"--title=mstsc",
"--text=<b>Error:</b> %s" % msg,
"--width=300"])
exit(1)
def argv_hide_password(args):
nargs = []
for arg in args:
if arg.startswith("/p:"):
arg = "/p:" + "*"*(len(arg)-len("/p:"))
nargs.append(arg)
return nargs
def argv_join(args):
nargs = []
for arg in args:
if " " in arg:
arg = "'%s'" % arg
nargs.append(arg)
return " ".join(nargs)
def which(cmd):
dirs = os.environ["PATH"].split(":")
for d in dirs:
exe = os.path.join(d or ".", cmd)
if os.path.exists(exe):
return exe
raise KeyError(f"{cmd!r} not found in PATH")
def resolve_fqdn(host):
res = socket.getaddrinfo(host, 3389,
type=socket.SOCK_STREAM,
flags=socket.AI_CANONNAME)
return res[0][3]
def ask_credentials_zenity(host, title):
res = subprocess.run(["zenity",
"--forms",
"--title", "Enter credentials",
"--text", "Enter credentials for %s:" % title,
"--add-entry", "Username:",
"--add-password", "Password:",
"--separator", "\n"],
stdout=subprocess.PIPE)
if res.stdout:
username, password, _ = res.stdout.decode().split("\n")
return username, password
return None, None
def ask_credentials(host):
title = "Remote Desktop on %s" % host
return ask_credentials_zenity(host, title)
def get_credentials_libsecret(host):
targets = [host]
if len(host.split(".")) >= 3:
_, domain = host.split(".", 1)
targets = [host, "*." + domain]
for target in targets:
for proto in ["rdp", "smb"]:
qattrs = {"xdg:schema": "org.gnome.keyring.NetworkPassword",
"protocol": proto,
"server": target}
logging.debug("searching keyring for protocol %r server %r", proto, target)
res = Secret.password_search_sync(None,
qattrs,
Secret.SearchFlags.LOAD_SECRETS,
None)
if res:
item = res[0]
logging.debug("found keyring entry %r", item.get_label())
for k, v in sorted(item.get_attributes().items()):
logging.debug(" - %s = %r", k, v)
username = item.get_attributes()["user"]
password = item.get_secret().get_text()
if domain := item.get_attributes().get("domain"):
logging.warn("XXX: Found credential with separate domain, u=%r d=%r",
username, domain)
if "." in domain:
username = "%s@%s" % (username, domain)
else:
username = "%s\\%s" % (domain, username)
return username, password
def save_credentials(host, username, password):
label = "Remote Desktop on %s" % host
attrs = {"xdg:schema": "org.gnome.keyring.NetworkPassword",
"protocol": "rdp",
"server": host,
"user": username}
Secret.password_store_sync(None,
attrs,
Secret.COLLECTION_DEFAULT,
label,
password,
None)
def get_credentials(host, ask=True):
if r := get_credentials_libsecret(host):
return r
if ask:
print("Credentials not found, asking interactively")
return ask_credentials(host)
return None, None
parser = argparse.ArgumentParser()
parser.add_argument("-l", "--legacy", "--old",
action="store_true",
help="legacy server (Windows 2003 or older, non-NLA)")
parser.add_argument("-r", "--restricted-admin", "--ra",
action="store_true",
help="Restricted Admin mode - don't delegate any credentials")
parser.add_argument("-k", "--insecure",
action="store_true",
help="ignore certificates")
parser.add_argument("--workarea",
action="store_true",
help="fit display into the work area instead of full-screen")
parser.add_argument("-g", "--gfx",
action="store_true",
help="enable support for RDP8 \"Graphics Pipeline\"")
parser.add_argument("--dev",
action="store_true",
help="use local FreeRDP build if available")
parser.add_argument("--flatpak",
action="store_true",
help="use the Flatpak build")
parser.add_argument("--x11",
action="store_true",
help="use the X11 client instead of SDL client")
parser.add_argument("--save",
action="store_true",
help="save password for future connections")
parser.add_argument("-v", "--verbose",
action="store_true",
help="show more details")
parser.add_argument("host")
args = parser.parse_args()
logging.basicConfig(level=[logging.INFO, logging.DEBUG][args.verbose],
format="rdp: %(message)s")
# We need the FQDN for keyring lookup (and kerberos, and possibly certificate
# validation).
try:
fqdn = resolve_fqdn(args.host)
logging.debug("resolved host %r to FQDN %r", args.host, fqdn)
except socket.gaierror as e:
exit("rdp: could not resolve hostname %r: %s" % (args.host, e))
if args.save:
username, password = ask_credentials(fqdn)
if username and password:
save_credentials(fqdn, username, password)
exit()
else:
username, password = get_credentials(fqdn, ask=(not args.legacy))
if args.x11:
cmd = ["xfreerdp"]
else:
cmd = ["sdl-freerdp"]
if args.flatpak:
cmd = ["flatpak", "run", "--command=%s" % cmd[0], "com.freerdp.FreeRDP"]
else:
if args.dev:
os.environ["PATH"] = "%s:%s" % (os.path.expanduser("~/.local/pkg/FreeRDP/bin"),
os.environ["PATH"])
try:
cmd[0] = which(cmd[0] + "3")
except KeyError:
cmd[0] = which(cmd[0])
logging.debug("using FreeRDP executable: %s", cmd[0])
cmd.append("/t:Remote Desktop: %s" % args.host)
cmd.append("/v:%s" % fqdn.lower())
if username and password:
cmd.append("/u:%s" % username)
cmd.append("/p:%s" % password)
else:
# Try to avoid the interactive pre-prompt with --legacy
cmd.append("/u:")
cmd.append("/p:")
if args.legacy:
cmd.append("/sec:rdp")
cmd.append("/cert:ignore")
if args.restricted_admin:
die("Restricted Admin mode is not supported by legacy servers")
#cmd.append("/tls:seclevel:0")
else:
cmd.append("/ipv6")
cmd.append("/sec:nla")
if args.restricted_admin:
cmd.append("/restricted-admin")
if args.insecure:
cmd.append("/cert:ignore")
cmd.append("/network:auto")
if args.gfx:
cmd.append("/gfx")
#cmd.append("/bpp:32")
#cmd.append("+fonts")
#cmd.append("+aero")
#cmd.append("+window-drag")
#cmd.append("+wallpaper")
#cmd.append("+multitouch")
cmd.append("/sound:sys:pulse")
cmd.append("+clipboard")
#cmd.append("+home-drive")
#cmd.append("/drive:media,/run/media/%s" % os.getlogin())
#cmd.append("/smartcard")
if args.legacy:
cmd.append("/cache:bitmap:on,persist")
if args.workarea:
cmd.append("/workarea")
cmd.append("-decorations")
else:
cmd.append("/f")
cmd.append("+floatbar")
if not args.verbose:
cmd.append("/log-level:WARN")
logging.debug("running with options: %s", argv_join(argv_hide_password(cmd)))
subprocess.run(cmd)