コード例 #1
0
ファイル: win10.py プロジェクト: LawyerWebber/XX-Net
def elevate(cmd):
    # use this if need admin
    import win32elevate
    try:
        win32elevate.elevateAdminRun(cmd)
    except Exception as e:
        xlog.warning('elevate e:%r', e)
コード例 #2
0
ファイル: cert_util.py プロジェクト: lizpark/XX-Net
    def import_windows_ca(common_name, certfile):
        import ctypes
        with open(certfile, 'rb') as fp:
            certdata = fp.read()
            if certdata.startswith(b'-----'):
                begin = b'-----BEGIN CERTIFICATE-----'
                end = b'-----END CERTIFICATE-----'
                certdata = base64.b64decode(b''.join(
                    certdata[certdata.find(begin) + len(begin):certdata.
                             find(end)].strip().splitlines()))
            crypt32 = ctypes.WinDLL(b'crypt32.dll'.decode())
            store_handle = crypt32.CertOpenStore(10, 0, 0, 0x4000 | 0x20000,
                                                 b'ROOT'.decode())
            if not store_handle:
                return False
            CERT_FIND_SUBJECT_STR = 0x00080007
            CERT_FIND_HASH = 0x10000
            X509_ASN_ENCODING = 0x00000001

            class CRYPT_HASH_BLOB(ctypes.Structure):
                _fields_ = [('cbData', ctypes.c_ulong),
                            ('pbData', ctypes.c_char_p)]

            assert CertUtil.ca_thumbprint
            crypt_hash = CRYPT_HASH_BLOB(
                20, binascii.a2b_hex(CertUtil.ca_thumbprint.replace(':', '')))
            crypt_handle = crypt32.CertFindCertificateInStore(
                store_handle, X509_ASN_ENCODING, 0, CERT_FIND_HASH,
                ctypes.byref(crypt_hash), None)
            if crypt_handle:
                crypt32.CertFreeCertificateContext(crypt_handle)
                return True

            ret = crypt32.CertAddEncodedCertificateToStore(
                store_handle, 0x1, certdata, len(certdata), 4, None)
            crypt32.CertCloseStore(store_handle, 0)
            del crypt32

            if not ret and __name__ != "__main__":
                #res = CertUtil.win32_notify(msg=u'Import GoAgent Ca?', title=u'Authority need')
                #if res == 2:
                #    return -1

                import win32elevate
                try:
                    win32elevate.elevateAdminRun(os.path.abspath(__file__))
                except Exception as e:
                    xlog.warning('CertUtil.import_windows_ca failed: %r', e)
                return True
            else:
                CertUtil.win32_notify(
                    msg=u'已经导入GoAgent证书,请重启浏览器.',
                    title=u'Restart browser need.')

            return True if ret else False
コード例 #3
0
ファイル: cert_util.py プロジェクト: FanQiangHui/goagent-1
    def import_windows_ca(common_name, certfile):
        import ctypes

        with open(certfile, "rb") as fp:
            certdata = fp.read()
            if certdata.startswith(b"-----"):
                begin = b"-----BEGIN CERTIFICATE-----"
                end = b"-----END CERTIFICATE-----"
                certdata = base64.b64decode(
                    b"".join(certdata[certdata.find(begin) + len(begin) : certdata.find(end)].strip().splitlines())
                )
            crypt32 = ctypes.WinDLL(b"crypt32.dll".decode())
            store_handle = crypt32.CertOpenStore(10, 0, 0, 0x4000 | 0x20000, b"ROOT".decode())
            if not store_handle:
                return False
            CERT_FIND_SUBJECT_STR = 0x00080007
            CERT_FIND_HASH = 0x10000
            X509_ASN_ENCODING = 0x00000001

            class CRYPT_HASH_BLOB(ctypes.Structure):
                _fields_ = [("cbData", ctypes.c_ulong), ("pbData", ctypes.c_char_p)]

            assert CertUtil.ca_thumbprint
            crypt_hash = CRYPT_HASH_BLOB(20, binascii.a2b_hex(CertUtil.ca_thumbprint.replace(":", "")))
            crypt_handle = crypt32.CertFindCertificateInStore(
                store_handle, X509_ASN_ENCODING, 0, CERT_FIND_HASH, ctypes.byref(crypt_hash), None
            )
            if crypt_handle:
                crypt32.CertFreeCertificateContext(crypt_handle)
                return True

            ret = crypt32.CertAddEncodedCertificateToStore(store_handle, 0x1, certdata, len(certdata), 4, None)
            crypt32.CertCloseStore(store_handle, 0)
            del crypt32

            if not ret and __name__ != "__main__":
                # res = CertUtil.win32_notify(msg=u'Import GoAgent Ca?', title=u'Authority need')
                # if res == 2:
                #    return -1

                import win32elevate

                win32elevate.elevateAdminRun(os.path.abspath(__file__))
                return True
            # else:
            # CertUtil.win32_notify(msg=u'Import GoAgent Ca finished, please restart browser.', title=u'Restart browser need.')

            return True if ret else False
コード例 #4
0
ファイル: win10.py プロジェクト: w23ta0/XX-Net
def elevate(script_path, clear_log=True):
    global script_is_running
    if not script_is_running:
        script_is_running = True

        if clear_log and os.path.isfile(log_file):
            try:
                os.remove(log_file)
            except Exception as e:
                xlog.warn("remove %s fail:%r", log_file, e)

        try:
            win32elevate.elevateAdminRun(None, script_path, True, False)
            return True
        except Exception as e:
            xlog.warning('elevate e:%r', e)
        finally:
            script_is_running = False
コード例 #5
0
ファイル: cert_util.py プロジェクト: zzw0598/XX-Net
    def import_windows_ca(certfile):
        xlog.debug("Begin to import Windows CA")
        with open(certfile, 'rb') as fp:
            certdata = fp.read()
            if certdata.startswith(b'-----'):
                begin = b'-----BEGIN CERTIFICATE-----'
                end = b'-----END CERTIFICATE-----'
                certdata = base64.b64decode(b''.join(
                    certdata[certdata.find(begin) + len(begin):certdata.
                             find(end)].strip().splitlines()))
        try:
            common_name = OpenSSL.crypto.load_certificate(
                OpenSSL.crypto.FILETYPE_ASN1, certdata).get_subject().CN
        except Exception as e:
            #logging.error('load_certificate(certfile=%r) 失败:%s', certfile, e)
            return -1

        assert certdata, 'cert file %r is broken' % certfile
        import ctypes.wintypes

        class CERT_CONTEXT(ctypes.Structure):
            _fields_ = [
                ('dwCertEncodingType', ctypes.wintypes.DWORD),
                ('pbCertEncoded', ctypes.POINTER(ctypes.wintypes.BYTE)),
                ('cbCertEncoded', ctypes.wintypes.DWORD),
                ('pCertInfo', ctypes.c_void_p),
                ('hCertStore', ctypes.c_void_p),
            ]

        X509_ASN_ENCODING = 0x1
        CERT_STORE_ADD_ALWAYS = 4
        CERT_STORE_PROV_SYSTEM = 10
        CERT_STORE_OPEN_EXISTING_FLAG = 0x4000
        CERT_SYSTEM_STORE_CURRENT_USER = 1 << 16
        CERT_SYSTEM_STORE_LOCAL_MACHINE = 2 << 16
        CERT_FIND_SUBJECT_STR = 8 << 16 | 7
        crypt32 = ctypes.windll.crypt32
        ca_exists = False
        store_handle = None
        pCertCtx = None
        ret = 0
        for store in (CERT_SYSTEM_STORE_LOCAL_MACHINE,
                      CERT_SYSTEM_STORE_CURRENT_USER):
            try:
                store_handle = crypt32.CertOpenStore(
                    CERT_STORE_PROV_SYSTEM, 0, None,
                    CERT_STORE_OPEN_EXISTING_FLAG | store, 'root')
                if not store_handle:
                    if store == CERT_SYSTEM_STORE_CURRENT_USER and not ca_exists:
                        xlog.warning(
                            'CertUtil.import_windows_ca failed: could not open system cert store'
                        )
                        return False
                    else:
                        continue

                pCertCtx = crypt32.CertFindCertificateInStore(
                    store_handle, X509_ASN_ENCODING, 0, CERT_FIND_SUBJECT_STR,
                    common_name, None)
                while pCertCtx:
                    certCtx = CERT_CONTEXT.from_address(pCertCtx)
                    _certdata = ctypes.string_at(certCtx.pbCertEncoded,
                                                 certCtx.cbCertEncoded)
                    if _certdata == certdata:
                        ca_exists = True
                        xlog.debug("XX-Net CA already exists")
                    else:
                        cert = OpenSSL.crypto.load_certificate(
                            OpenSSL.crypto.FILETYPE_ASN1, _certdata)
                        if hasattr(cert, 'get_subject'):
                            cert = cert.get_subject()
                        cert_name = next(
                            (v for k, v in cert.get_components() if k == 'CN'),
                            '')
                        if cert_name == common_name:
                            ret = crypt32.CertDeleteCertificateFromStore(
                                crypt32.CertDuplicateCertificateContext(
                                    pCertCtx))
                            if ret == 1:
                                xlog.debug(
                                    "Invalid Windows CA %r has been removed",
                                    common_name)
                            elif ret == 0 and store == CERT_SYSTEM_STORE_LOCAL_MACHINE:
                                # to elevate
                                break
                    pCertCtx = crypt32.CertFindCertificateInStore(
                        store_handle, X509_ASN_ENCODING, 0,
                        CERT_FIND_SUBJECT_STR, common_name, pCertCtx)

                # Only add to current user
                if store == CERT_SYSTEM_STORE_CURRENT_USER and not ca_exists:
                    ret = crypt32.CertAddEncodedCertificateToStore(
                        store_handle, X509_ASN_ENCODING, certdata,
                        len(certdata), CERT_STORE_ADD_ALWAYS, None)
            except Exception as e:
                xlog.warning('CertUtil.import_windows_ca failed: %r', e)
                if isinstance(e, OSError):
                    store_handle = None
                    continue
                return False
            finally:
                if pCertCtx:
                    crypt32.CertFreeCertificateContext(pCertCtx)
                    pCertCtx = None
                if store_handle:
                    crypt32.CertCloseStore(store_handle, 0)
                    store_handle = None

        if ca_exists:
            return True

        if ret == 0 and __name__ != "__main__":
            #res = CertUtil.win32_notify(msg=u'Import GoAgent Ca?', title=u'Authority need')
            #if res == 2:
            #    return -1

            import win32elevate
            try:
                win32elevate.elevateAdminRun(os.path.abspath(__file__))
            except Exception as e:
                xlog.warning('CertUtil.import_windows_ca failed: %r', e)
            return True
        elif ret == 1:
            CertUtil.win32_notify(msg='已经导入GoAgent证书,请重启浏览器.',
                                  title='Restart browser need.')

        return ret == 1
コード例 #6
0
ファイル: cert_util.py プロジェクト: saiddy/XX-Net
    def import_ca(certfile):
        commonname = os.path.splitext(os.path.basename(certfile))[0]
        if sys.platform.startswith('win'):
            import ctypes
            with open(certfile, 'rb') as fp:
                certdata = fp.read()
                if certdata.startswith(b'-----'):
                    begin = b'-----BEGIN CERTIFICATE-----'
                    end = b'-----END CERTIFICATE-----'
                    certdata = base64.b64decode(b''.join(
                        certdata[certdata.find(begin) + len(begin):certdata.
                                 find(end)].strip().splitlines()))
                crypt32 = ctypes.WinDLL(b'crypt32.dll'.decode())
                store_handle = crypt32.CertOpenStore(10, 0, 0,
                                                     0x4000 | 0x20000,
                                                     b'ROOT'.decode())
                if not store_handle:
                    return -1
                CERT_FIND_SUBJECT_STR = 0x00080007
                CERT_FIND_HASH = 0x10000
                X509_ASN_ENCODING = 0x00000001

                class CRYPT_HASH_BLOB(ctypes.Structure):
                    _fields_ = [('cbData', ctypes.c_ulong),
                                ('pbData', ctypes.c_char_p)]

                assert CertUtil.ca_thumbprint
                crypt_hash = CRYPT_HASH_BLOB(
                    20,
                    binascii.a2b_hex(CertUtil.ca_thumbprint.replace(':', '')))
                crypt_handle = crypt32.CertFindCertificateInStore(
                    store_handle, X509_ASN_ENCODING, 0, CERT_FIND_HASH,
                    ctypes.byref(crypt_hash), None)
                if crypt_handle:
                    crypt32.CertFreeCertificateContext(crypt_handle)
                    return 0

                ret = crypt32.CertAddEncodedCertificateToStore(
                    store_handle, 0x1, certdata, len(certdata), 4, None)
                crypt32.CertCloseStore(store_handle, 0)
                del crypt32

                if not ret and __name__ != "__main__":
                    #res = CertUtil.win32_notify(msg=u'Import GoAgent Ca?', title=u'Authority need')
                    #if res == 2:
                    #    return -1

                    import win32elevate
                    win32elevate.elevateAdminRun(os.path.abspath(__file__))
                    return 0

                return 0 if ret else -1
        elif sys.platform == 'darwin':
            return os.system((
                'security find-certificate -a -c "%s" | grep "%s" >/dev/null || security add-trusted-cert -d -r trustRoot -k "/Library/Keychains/System.keychain" "%s"'
                % (commonname, commonname,
                   certfile.decode('utf-8'))).encode('utf-8'))
        elif sys.platform.startswith('linux'):
            import platform
            platform_distname = platform.dist()[0]
            if platform_distname == 'Ubuntu':
                pemfile = "/etc/ssl/certs/%s.pem" % commonname
                new_certfile = "/usr/local/share/ca-certificates/%s.crt" % commonname
                if not os.path.exists(pemfile):
                    return os.system('cp "%s" "%s" && update-ca-certificates' %
                                     (certfile, new_certfile))
            elif any(
                    os.path.isfile('%s/certutil' % x)
                    for x in os.environ['PATH'].split(os.pathsep)):
                return os.system(
                    'certutil -L -d sql:$HOME/.pki/nssdb | grep "%s" || certutil -d sql:$HOME/.pki/nssdb -A -t "C,," -n "%s" -i "%s"'
                    % (commonname, commonname, certfile))
            else:
                logging.warning(
                    'please install *libnss3-tools* package to import GoAgent root ca'
                )
        return 0
コード例 #7
0
 def change_reserved_port_range():
     exec = b"netsh"
     args = b"int ipv4 set dynamic tcp start=49152 num=16384"
     import win32elevate
     win32elevate.elevateAdminRun(args, exec)
コード例 #8
0
ファイル: cert_util.py プロジェクト: CyrusYzGTt/XX-Net
    def import_windows_ca(common_name, certfile):
        xlog.debug("Begin to import Windows CA")
        with open(certfile, 'rb') as fp:
            certdata = fp.read()
            if certdata.startswith(b'-----'):
                begin = b'-----BEGIN CERTIFICATE-----'
                end = b'-----END CERTIFICATE-----'
                certdata = base64.b64decode(b''.join(certdata[certdata.find(begin)+len(begin):certdata.find(end)].strip().splitlines()))

        assert certdata, 'cert file %r is broken' % certfile
        import ctypes
        import ctypes.wintypes
        class CERT_CONTEXT(ctypes.Structure):
            _fields_ = [
                ('dwCertEncodingType', ctypes.wintypes.DWORD),
                ('pbCertEncoded', ctypes.POINTER(ctypes.wintypes.BYTE)),
                ('cbCertEncoded', ctypes.wintypes.DWORD),
                ('pCertInfo', ctypes.c_void_p),
                ('hCertStore', ctypes.c_void_p),]
        CERT_STORE_PROV_SYSTEM = 10
        CERT_STORE_OPEN_EXISTING_FLAG = 0x4000
        CERT_SYSTEM_STORE_CURRENT_USER = 1 << 16
        CERT_SYSTEM_STORE_LOCAL_MACHINE = 2 << 16
        crypt32 = ctypes.windll.crypt32
        ca_exists = False
        for store in (CERT_SYSTEM_STORE_LOCAL_MACHINE, CERT_SYSTEM_STORE_CURRENT_USER):
            try:
                store_handle = crypt32.CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, None, CERT_STORE_OPEN_EXISTING_FLAG | store, u'root')
                if not store_handle:
                    if store == CERT_SYSTEM_STORE_CURRENT_USER and not ca_exists:
                        xlog.warning('CertUtil.import_windows_ca failed: could not open system cert store')
                        return False
                    else:
                        continue

                pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, None)
                while pCertCtx:
                    certCtx = CERT_CONTEXT.from_address(pCertCtx)
                    _certdata = ctypes.string_at(certCtx.pbCertEncoded, certCtx.cbCertEncoded)
                    if _certdata == certdata:
                        ca_exists = True
                        xlog.debug("XX-Net CA already exists")
                    else:
                        cert =  OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, _certdata)
                        if hasattr(cert, 'get_subject'):
                             cert = cert.get_subject()
                        cert_name = next((v for k, v in cert.get_components() if k == 'CN'), '')
                        if cert_name == common_name:
                            ret = crypt32.CertDeleteCertificateFromStore(crypt32.CertDuplicateCertificateContext(pCertCtx))
                            if ret == 1:
                                xlog.debug("Invalid Windows CA %r has been removed", common_name)
                            elif ret == 0 and store == CERT_SYSTEM_STORE_LOCAL_MACHINE:
                                # to elevate
                                break
                    pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, pCertCtx)

                # Only add to current user
                if store == CERT_SYSTEM_STORE_CURRENT_USER and not ca_exists:
                    ret = crypt32.CertAddEncodedCertificateToStore(store_handle, 0x1, certdata, len(certdata), 4, None)
            except Exception as e:
                xlog.warning('CertUtil.import_windows_ca failed: %r', e)
                return False
            finally:
                if pCertCtx:
                    crypt32.CertFreeCertificateContext(pCertCtx)
                if store_handle:
                    crypt32.CertCloseStore(store_handle, 0)

        if ca_exists:
            return True

        if ret == 0 and __name__ != "__main__":
            #res = CertUtil.win32_notify(msg=u'Import GoAgent Ca?', title=u'Authority need')
            #if res == 2:
            #    return -1

            import win32elevate
            try:
                win32elevate.elevateAdminRun(os.path.abspath(__file__))
            except Exception as e:
                xlog.warning('CertUtil.import_windows_ca failed: %r', e)
            return True
        elif ret == 1:
            CertUtil.win32_notify(msg=u'已经导入GoAgent证书,请重启浏览器.', title=u'Restart browser need.')

        return ret == 1