Skip to content

Commit

Permalink
- compatibility for python3
Browse files Browse the repository at this point in the history
- compatibility to use the plugin on a windows box
- new flag to disable TLS1.2 protocol (to connect to windows 2008 servers)
  • Loading branch information
ltamaster committed Apr 8, 2019
1 parent a057fed commit 776b7f5
Show file tree
Hide file tree
Showing 6 changed files with 204 additions and 114 deletions.
6 changes: 3 additions & 3 deletions contents/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,16 +60,16 @@ def _raw_get_command_output(protocol,shell_id, command_id, out_stream=None, err_
if not stream_node.text:
continue

content = str(base64.b64decode(stream_node.text.encode('ascii')))
content = base64.b64decode(stream_node.text.encode('ascii')).decode("Windows-1252")

if stream_node.attrib['Name'] == 'stdout':
if out_stream:
out_stream.write(content)
stdout += content
stdout += content.encode('Windows-1252')
elif stream_node.attrib['Name'] == 'stderr':
if err_stream:
err_stream.write(content)
stderr += content
stderr += content.encode('Windows-1252')

command_done = len([
node for node in root.findall('.//*')
Expand Down
37 changes: 25 additions & 12 deletions contents/winrm-check.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import winrm
import os
try:
import os; os.environ['PATH']
except:
import os
os.environ.setdefault('PATH', '')
import sys
import argparse
import requests.packages.urllib3
Expand All @@ -13,6 +17,7 @@
parser.add_argument('--transport', help='transport',default="http")
parser.add_argument('--port', help='port',default="5985")
parser.add_argument('--nossl', help='nossl',default="False")
parser.add_argument('--diabletls12', help='diabletls12',default="False")
parser.add_argument('--debug', help='nossl',default="False")
parser.add_argument('--certpath', help='certpath')

Expand Down Expand Up @@ -47,6 +52,12 @@
else:
nossl = False

if args.diabletls12:
if args.diabletls12 == "true":
diabletls12 = True
else:
diabletls12 = False

if args.debug:
if args.debug == "true":
debug = True
Expand Down Expand Up @@ -75,16 +86,16 @@
endpoint=transport+'://'+hostname+':'+port

if(debug):
print "------------------------------------------"
print "endpoint:" +endpoint
print "authentication:" +authentication
print "username:" +username
print "nossl:" + str(nossl)
print "transport:" + transport
print("------------------------------------------")
print("endpoint:" +endpoint)
print("authentication:" +authentication)
print("username:" +username)
print("nossl:" + str(nossl))
print("diabletls12:" + str(diabletls12))
print("transport:" + transport)
if(certpath):
print "certpath:" + certpath
print "------------------------------------------"

print("certpath:" + certpath)
print("------------------------------------------")

arguments={}
arguments["transport"] = authentication
Expand All @@ -96,6 +107,8 @@
arguments["server_cert_validation"] = "validate"
arguments["ca_trust_path"] = certpath

arguments["credssp_disable_tlsv1_2"] = diabletls12

session = winrm.Session(target=endpoint,
auth=(username, password),
**arguments)
Expand All @@ -104,7 +117,7 @@
result = session.run_cmd(exec_command)

if(result.std_err):
print "Connection with host %s fail" % hostname
print("Connection with host %s fail" % hostname)
sys.exit(1)
else:
print "Connection with host %s successfull" % hostname
print("Connection with host %s successfull" % hostname)
33 changes: 28 additions & 5 deletions contents/winrm-exec.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import argparse
import os
try:
import os; os.environ['PATH']
except:
import os
os.environ.setdefault('PATH', '')
import sys
import requests.packages.urllib3
import winrm_session
import threading
import traceback
import winrm

requests.packages.urllib3.disable_warnings()

Expand All @@ -16,6 +22,7 @@
transport = "http"
port = "5985"
nossl=False
diabletls12=False
debug=False
shell = "cmd"
certpath = None
Expand All @@ -35,6 +42,12 @@
else:
nossl = False

if "RD_CONFIG_DISABLETLS12" in os.environ:
if os.getenv("RD_CONFIG_DISABLETLS12") == "true":
diabletls12 = True
else:
diabletls12 = False

if "RD_CONFIG_SHELL" in os.environ:
shell = os.getenv("RD_CONFIG_SHELL")

Expand Down Expand Up @@ -73,6 +86,7 @@
print("authentication:" + authentication)
print("username:" + username)
print("nossl:" + str(nossl))
print("diabletls12:" + str(diabletls12))
print("------------------------------------------")

arguments = {}
Expand All @@ -85,10 +99,16 @@
arguments["server_cert_validation"] = "validate"
arguments["ca_trust_path"] = certpath

session = winrm_session.Session(target=endpoint,
arguments["credssp_disable_tlsv1_2"] = diabletls12

session = winrm.Session(target=endpoint,
auth=(username, password),
**arguments)

winrm.Session.run_cmd = winrm_session.run_cmd
winrm.Session.run_ps = winrm_session.run_ps
winrm.Session._clean_error_msg = winrm_session._clean_error_msg

tsk = winrm_session.RunCommand(session, shell, exec_command)
t = threading.Thread(target=tsk.get_response)
t.start()
Expand All @@ -109,9 +129,12 @@
lastpos = sys.stdout.tell()

if sys.stderr.tell() != lasterrorpos:
sys.stderr.seek(lasterrorpos)
realstderr.write(session._clean_error_msg(sys.stderr.read()))
lasterrorpos = sys.stderr.tell()
try:
sys.stderr.seek(lasterrorpos)
realstderr.write(session._clean_error_msg(sys.stderr.read()))
lasterrorpos = sys.stderr.tell()
except Exception as e:
traceback.print_exc(file=sys.stdout)

if not t.is_alive():
break
Expand Down
62 changes: 59 additions & 3 deletions contents/winrm-filecopier.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,55 @@
import winrm
import argparse
import os
try:
import os; os.environ['PATH']
except:
import os
os.environ.setdefault('PATH', '')
import sys
import base64
import time
import common
import requests.packages.urllib3
import logging
import ntpath
import xml.etree.ElementTree as ET


def _clean_error_msg(self, msg):
"""converts a Powershell CLIXML message to a more human readable string
"""
# TODO prepare unit test, beautify code
# if the msg does not start with this, return it as is
if type(msg) == bytes and msg.startswith(b"#< CLIXML\r\n"):
# for proper xml, we need to remove the CLIXML part
# (the first line)
msg_xml = msg[11:]
try:
# remove the namespaces from the xml for easier processing
msg_xml = self._strip_namespace(msg_xml)
root = ET.fromstring(msg_xml)
# the S node is the error message, find all S nodes
nodes = root.findall("./S")
new_msg = ""
for s in nodes:
# append error msg string to result, also
# the hex chars represent CRLF so we replace with newline
print(s.text)
new_msg += s.text.replace("_x000D__x000A_", "\n")
except Exception as e:
# if any of the above fails, the msg was not true xml
# print a warning and return the orignal string
# TODO do not print, raise user defined error instead
print("Warning: there was a problem converting the Powershell"
" error message: %s" % (e))
else:
# if new_msg was populated, that's our error message
# otherwise the original error message will be used
if len(new_msg):
# remove leading and trailing whitespace while we are here
msg = new_msg.strip()
return msg


requests.packages.urllib3.disable_warnings()

Expand Down Expand Up @@ -67,7 +109,7 @@ def winrm_upload(self,
'add-content -value '
'$([System.Convert]::FromBase64String("{}")) '
'-encoding byte -path {}'.format(
base64.b64encode(f.read(step)),
base64.b64encode(f.read(step)).decode(),
full_path
)
)
Expand Down Expand Up @@ -107,14 +149,15 @@ def winrm_upload(self,
args = parser.parse_args()

#it is necesarry to avoid the debug error
print args.destination
print(args.destination)

password=None
authentication = "basic"
transport = "http"
port = "5985"
nossl = False
debug = False
diabletls12 = False

if "RD_CONFIG_AUTHTYPE" in os.environ:
authentication = os.getenv("RD_CONFIG_AUTHTYPE")
Expand All @@ -131,6 +174,12 @@ def winrm_upload(self,
else:
nossl = False

if "RD_CONFIG_DISABLETLS12" in os.environ:
if os.getenv("RD_CONFIG_DISABLETLS12") == "true":
diabletls12 = True
else:
diabletls12 = False

if "RD_CONFIG_CERTPATH" in os.environ:
certpath = os.getenv("RD_CONFIG_CERTPATH")

Expand Down Expand Up @@ -169,14 +218,21 @@ def winrm_upload(self,
arguments["server_cert_validation"] = "validate"
arguments["ca_trust_path"] = certpath

arguments["credssp_disable_tlsv1_2"] = diabletls12

session = winrm.Session(target=endpoint,
auth=(username, password),
**arguments)


winrm.Session._clean_error_msg = _clean_error_msg

copy = CopyFiles(session)

destination = args.destination
filename = ntpath.basename(args.destination)
if filename is None:
filename = os.path.basename(args.source)

if filename in args.destination:
destination = destination.replace(filename, '')
Expand Down
Loading

0 comments on commit 776b7f5

Please sign in to comment.