예제 #1
0
def makeRequest(pubkey, pkey, serv_host, auto = False):
    """ create query to the signing on server """
    req = X509.Request()
    # Seems to default to 0, but we can now set it as well, so just API test
    req.set_version(req.get_version())
    req.set_pubkey(pkey)
    name = X509.X509_Name()
    if auto:
        c = 'n'
    else:
        c = raw_input (_("Enter the certificate date manually? y/[n]: "))
    # Get HostName
    host_name = socket.getfqdn()
    list_host_name = host_name.split('.')
    result_host_name = list_host_name[0]+"@"+serv_host
    # Get username
    clVars = DataVarsCore()
    if not clVars.flIniFile():
        sys.exit(1)
    username = clVars.Get('ur_fullname')
    # Get language
    lang = clVars.Get('os_locale_locale')[:2]

    if c.lower() in ['y', 'yes']:
        #if serv_host in host_name:
            #host_name = host_name.replace('.'+serv_host, '')
            #list_host_name = host_name.split('.')
            #result_host_name =  \
                        #list_host_name[len(list_host_name)-1]+"@"+serv_host
        #else:
            #host_name = socket.getfqdn()
        name.CN = raw_input (_('Hostname [%s] : ') %result_host_name)
        if name.CN in ['', None]:
            name.CN = result_host_name

        name.OU = raw_input (_('Username [%s]: ') %username)
        if name.OU in ['', None]:
            name.OU = username
        name.O = raw_input (_('Organization name: '))
        name.L = raw_input (_('Network address (hostname or IP) [%s]: ')\
                            %host_name) 
        name.ST = raw_input (_('City: '))
        name.C = raw_input (_('Country: [%s]') %lang)
        if not name.C:
	    name.C = lang
    else:
        name.CN = result_host_name # Имя сертификата (Common Name); 
        name.OU = username # Название отдела (Organization Unit);
        name.O = 'My Company'# Название организации (Organization Name);
        name.L = host_name # Название города (Locality Name); 
        name.ST = 'My State'# Название региона (State Name);
        name.C = lang # Двухсимвольный код страны (Country);
    req.set_subject_name(name)
    
    ext1 = X509.new_extension('Comment', 'Auto Generated')
    extstack = X509.X509_Extension_Stack()
    extstack.push(ext1)
    req.add_extensions(extstack)
    req.sign(pkey, 'md5')
    return req
예제 #2
0
    def connect(self):
        """Connect to a host on a given (SSL) port."""
        if self.host == "127.0.0.1":
            self.host = "localhost"
        sock = socket.create_connection((self.host, self.port), self.timeout, self.source_address)
        if self._tunnel_host:
            self.sock = sock
            self._tunnel()

        clVars = DataVarsCore()
        clVars.importCore()
        clVars.flIniFile()

        user_root_cert = clVars.Get("cl_user_root_cert")
        homePath = clVars.Get("ur_home_path")
        user_root_cert = user_root_cert.replace("~", homePath)
        result_user_root = 1

        if os.path.exists(user_root_cert):
            result_user_root = self.connect_trusted_root(sock, user_root_cert, self.CRL_PATH)
            # print 'rur = ',result_user_root
        if result_user_root == 1:
            glob_root_cert = clVars.Get("cl_glob_root_cert")
            result_root_con = 1
            if os.path.exists(glob_root_cert):
                sock = socket.create_connection((self.host, self.port), self.timeout, self.source_address)
                if self._tunnel_host:
                    self.sock = sock
                    self._tunnel()
                result_root_con = self.connect_trusted_root(sock, glob_root_cert, self.CRL_PATH)
                # print 'rrc = ',result_root_con
            if result_root_con == 1:
                sock = socket.create_connection((self.host, self.port), self.timeout, self.source_address)
                if self._tunnel_host:
                    self.sock = sock
                    self._tunnel()
                result_server_con = self.connect_trusted_server(sock, self.CRL_PATH)
                # print 'rsc = ',result_server_con
                if result_server_con in [1, 2]:
                    raise Exception
                    # sys.exit(1)
            elif result_root_con == 2:
                # sys.exit(1)
                raise Exception
        elif result_user_root == 2:
            # sys.exit(1)
            raise Exception
예제 #3
0
 def variables_vars(self,dv=None):
     if not dv:
         dv = DataVarsCore()
         dv.importCore()
         dv.flIniFile()
     dv.addGroup(None,
         normal=('cl_variable_data',),
         next_label=_("Save"))
     return dv
예제 #4
0
 def variables_show_vars(self,dv=None):
     if not dv:
         dv = DataVarsCore()
         dv.importCore()
         dv.flIniFile()
     dv.addGroup(None,
         normal=('cl_variable_filter','cl_variable_show'),
         next_label=_("Show"))
     return dv
예제 #5
0
def rm_ca_from_trusted(ca_cert):
    clVars = DataVarsCore()
    clVars.importCore()
    clVars.flIniFile()
    
    user_ca_dir = clVars.Get('core.cl_client_cert_dir')
    homePath = clVars.Get('ur_home_path')
    user_ca_dir = user_ca_dir.replace("~",homePath)
    user_ca_dir = os.path.join(user_ca_dir, 'ca')
    user_ca_list = os.path.join(user_ca_dir, 'cert_list')
    user_ca_db = clVars.Get('core.cl_user_root_cert')
    homePath = clVars.Get('ur_home_path')
    user_ca_db = user_ca_db.replace("~",homePath)
    
    system_ca_dir = clVars.Get('core.cl_core_cert_path')
    system_ca_list = os.path.join(system_ca_dir, 'cert_list')
    system_ca_db = clVars.Get('core.cl_glob_root_cert')
    
    import hashlib
    md5 = hashlib.md5()
    md5.update(ca_cert)
    md5sum = md5.hexdigest()

    # search ca certificate in user ca list
    with open(user_ca_list) as fd:
        t = fd.read()
        # See each line
        for line in t.splitlines():
            newfile = ''
            # and each word in line
            words = line.split()
            if words[0] == md5sum:
                filename = os.path.join(user_ca_dir, words[1])
                if ca_cert == open(filename, 'r').read():
                    try:
                        os.unlink(filename)
                    except OSError, e:
                        _print (e.message)
                else:
                    newfile += (line + '\n')
            else:
                newfile += (line + '\n')
예제 #6
0
def client_signal(client):
    Vars = DataVarsCore()
    Vars.importCore()
    Vars.flIniFile()
    try:
        client_active = Vars.Get('core.cl_core_client_active_period')
    except:
        client_active = 15
    while True:
        if os.path.exists(client.SID_FILE) :
            fi = open(client.SID_FILE, 'r')
            temp = fi.read()
            fi.close()
            sid = int(temp)
        else:
            sid = 0
        try:
            client.service.active_client(sid)
        except:
            print _('no connection to the server!')
            raise Exception(1)
        time.sleep(float(client_active))
예제 #7
0
    def connect(self):
        """Connect to a host on a given (SSL) port."""
        timeout = 15
        sock = socket.create_connection((self.host, self.port),
                                        timeout, self.source_address)
        if self._tunnel_host:
            self.sock = sock
            self._tunnel()

        clVars = DataVarsCore()
        clVars.importCore()
        if not clVars.flIniFile():
            sys.exit(1)
        user_root_cert = clVars.Get('cl_user_root_cert')
        homePath = clVars.Get('ur_home_path')
        user_root_cert = user_root_cert.replace("~",homePath)
#        result_user_root = 1
        import ssl
        self.sock = ssl.wrap_socket(sock,\
                            certfile = self.cert_file, \
                            keyfile = self.key_file, \
                            #ca_certs = self.ca_path + self.filename, \
                            ssl_version = ssl.PROTOCOL_SSLv23, \
                            cert_reqs = ssl.CERT_NONE)
예제 #8
0
 def core_patch_vars(self, dv=None):
     if not dv:
         dv = DataVarsCore()
         dv.importCore()
         dv.flIniFile()
         dv.Set("cl_action", "patch", True)
         dv.Set("cl_dispatch_conf", "usenew", True)
     dv.addGroup(
         None,
         normal=("cl_core_pkg_name",),
         expert=(
             "cl_core_pkg_category",
             "cl_core_pkg_version",
             "cl_core_pkg_slot",
             "cl_core_pkg_path",
             "cl_templates_locate",
             "cl_verbose_set",
         ),
         next_label=_("Patch"),
     )
     return dv
예제 #9
0
def client_get_cert(cert_path, args):
    if not os.path.exists(cert_path + 'req_id'):
        print _("request not sent or file %s deleted") \
                %(cert_path + 'req_id')
        return 1
    fc = open(cert_path + 'req_id', 'r')
    req_id = fc.read()
    fc.close()
    
    print '\n'+_("the URL looks like"), "https://%s:[port]/?wsdl" \
                                                    %args.from_host
    port = raw_input (_("Enter the port number: "))
    try:
        port = int(port)
    except:
        print _('The port number must be int')
        return 1
    url = "https://%s:%d/?wsdl" %(args.from_host, port)
    print url + '\n' + _("connecting...")
    
    from sudsds.client import Client
    try:
        client = Client(url, \
                    transport = HTTPSClientCertTransport(None, None, cert_path))
    except KeyboardInterrupt:
        print '\n'+_("Closed. Connection error.")
    
    server_host_name = client.service.get_server_host_name()
    
    if not os.path.exists(cert_path + server_host_name + '.csr'):
        print _('Request %s not found') %(cert_path + server_host_name + '.csr')
        return 1
    request = open(cert_path + server_host_name + '.csr').read()
    md5 = hashlib.md5()
    md5.update(request)
    md5sum = md5.hexdigest()
    
    result = client.service.get_client_cert(req_id, md5sum)
    cert = result[0][0]
    ca_root = result[0][1]
    if cert == '1':
        print _('The signature request was rejected!')
        return 1
    elif cert == '2':
        print _("The signature request has not been examined yet.")
        print _("Your request ID = %s") %req_id
        return 1
    elif cert == '3':
        print _("The signature request does not match earlier data.")
        return 1
    elif cert == '4':
        print _("The request was sent from another IP.")
        return 1
    fc = open(cert_path + server_host_name + '.crt', 'w')
    fc.write(cert)
    fc.close()
    os.unlink(cert_path + 'req_id')
    print 'OK. Certificate saved. Your certificate ID = %s' %req_id
    
    if ca_root:
        clVars = DataVarsCore()
        clVars.importCore()
        clVars.flIniFile()
        system_ca_db = clVars.Get('cl_glob_root_cert')
        if os.path.exists(system_ca_db):
            if ca_root in open(system_ca_db, 'r').read():
                return 0
        
        cl_client_cert_dir = clVars.Get('cl_client_cert_dir')
        homePath = clVars.Get('ur_home_path')
        
        cl_client_cert_dir = cl_client_cert_dir.replace("~",homePath)
        root_cert_md5 = cl_client_cert_dir + "/ca/cert_list"
        
        md5 = hashlib.md5()
        md5.update(ca_root)
        md5sum = md5.hexdigest()

        if not os.path.exists(root_cert_md5):
            fc = open(root_cert_md5,"w")
            fc.close()
        
        filename = None
        with open(root_cert_md5) as fd:
            t = fd.read()
            # for each line
            for line in t.splitlines():
                # Split string into a words list
                words = line.split(' ',1)
                if words[0] == md5sum:
                    filename = words[1]
        if not filename:
            certobj = OpenSSL.crypto.load_certificate \
                                    (OpenSSL.SSL.FILETYPE_PEM, ca_root)
            Issuer = certobj.get_issuer().get_components()
            for item in Issuer:
                if item[0] == 'CN':
                    filename = item[1]
            
            fc = open(root_cert_md5,"a")
            fc.write('%s %s\n' %(md5sum, filename))
            fc.close()
            
            if not filename:
                print _('Field "CN" not found in the certificate!')
                return 1
                
            fd = open(cl_client_cert_dir + '/ca/' + filename, 'w')
            fd.write(ca_root)
            fd.close()
            
            
            user_root_cert = clVars.Get('cl_user_root_cert')
            user_root_cert = user_root_cert.replace("~",homePath)
            fa = open(user_root_cert, 'a')
            fa.write(ca_root)
            fa.close()
            print _("Certificate added")
        else:
            print _("file containing the CA certificate now exists")
    return 0
예제 #10
0
def get_CRL(path_to_cert):
    """ get new CRL (Certificate Revocation List) from all CA """
    # local CRL
    CRL_path = path_to_cert + 'ca/crl/'
    if not os.path.exists(CRL_path):
        if not os.path.exists(path_to_cert + '/ca'):
            if not os.path.exists(path_to_cert):
                try:
                    os.makedirs(path_to_cert)
                except OSError:
                    print _("Error creating directory %s") %path_to_cert
                    sys.exit()
            try:
                os.makedirs(path_to_cert + '/ca')
            except OSError:
                print _("Error creating directory %s") %(path_to_cert + '/ca')
                sys.exit()
        os.makedirs(CRL_path)
    
    clVars = DataVarsCore()
    clVars.importCore()
    clVars.flIniFile()
    # user and system  ca and root certificates
    user_root_cert = clVars.Get('cl_user_root_cert')
    homePath = clVars.Get('ur_home_path')
    user_root_cert = user_root_cert.replace("~",homePath)

    glob_root_cert = clVars.Get('cl_glob_root_cert')
    
    if os.path.exists(user_root_cert):
        user_ca_certs = open(user_root_cert, 'r').read()
    else: user_ca_certs = ''
    if os.path.exists(glob_root_cert):
        glob_ca_certs = open(glob_root_cert, 'r').read()
    else: glob_ca_certs = ''
    
    # get certificates list fron text
    p = re.compile('[-]+[\w ]+[-]+\n+[\w\n\+\\=/]+[-]+[\w ]+[-]+\n?')
    user_ca_certs_list = p.findall(user_ca_certs)
    glob_ca_certs_list = p.findall(glob_ca_certs)
    
    # association in one list
    all_ca_certs_list = user_ca_certs_list + glob_ca_certs_list
    for ca in all_ca_certs_list:
        certobj = OpenSSL.crypto.load_certificate \
                    (OpenSSL.SSL.FILETYPE_PEM, ca)
        # get url from certificates
        url = None
        CN = None
        Subject = certobj.get_subject().get_components()
        for subj in Subject:
            if subj[0] == 'L':
                url = "https://" + subj[1] +"/?wsdl"
            if subj[0] == 'CN':
                CN = subj[1]
        
        if url:
            from calculate.core.client.client_class import Client_suds
            from client_class import HTTPSClientCertTransport
            # connect to ca server (url get from certificates)
            try:
                client = Client_suds(url,\
                    transport = HTTPSClientCertTransport(None, None, \
                                                            path_to_cert))

                client.set_parameters (path_to_cert, None, None)
                new_crl = client.service.get_crl()
            except VerifyError, e:
                print e.value
                #rm_ca_from_trusted(ca)
                sys.exit()
            except:
예제 #11
0
def rm_ca_from_trusted(ca_cert):
    clVars = DataVarsCore()
    clVars.importCore()
    clVars.flIniFile()
    
    user_ca_dir = clVars.Get('cl_client_cert_dir')
    homePath = clVars.Get('ur_home_path')
    user_ca_dir = user_ca_dir.replace("~",homePath)
    user_ca_dir = os.path.join(user_ca_dir, 'ca')
    user_ca_list = os.path.join(user_ca_dir, 'cert_list')
    user_ca_db = clVars.Get('cl_user_root_cert')
    homePath = clVars.Get('ur_home_path')
    user_ca_db = user_ca_db.replace("~",homePath)
    
    system_ca_dir = clVars.Get('cl_core_cert_path')
    system_ca_list = os.path.join(system_ca_dir, 'cert_list')
    system_ca_db = clVars.Get('cl_glob_root_cert')
    
    import hashlib
    md5 = hashlib.md5()
    md5.update(ca_cert)
    md5sum = md5.hexdigest()

    # search ca certificate in user ca list
    with open(user_ca_list) as fd:
        t = fd.read()
        # See each line
        for line in t.splitlines():
            newfile = ''
            # and each word in line
            words = line.split()
            if words[0] == md5sum:
                filename = os.path.join(user_ca_dir, words[1])
                if ca_cert == open(filename, 'r').read():
                    os.unlink(filename)
                else:
                    newfile += (line + '\n')
            else:
                newfile += (line + '\n')
                
    fd.close()
    fn = open(user_ca_list, 'w')
    fn.write(newfile)
    fn.close()
    
    p = re.compile('[-]+[\w ]+[-]+\n+[\w\n\+\\=/]+[-]+[\w ]+[-]+\n?')
    
    # open, write and split user ca certificates
    user_ca_certs = open(user_ca_db, 'r').read()
    user_ca_certs_list = p.findall(user_ca_certs)
    
    if ca_cert in user_ca_certs_list:
        new_user_ca_certs = []
        for cert in user_ca_certs_list:
            if ca_cert != cert:
                new_user_ca_certs.append(cert)
            else:
                print _("CA certificate deleted from the user's trusted "
                        "certificates list")
        
        fd = open(user_ca_db, 'w')
        for cert in new_user_ca_certs:
            fd.write(cert)
        fd.close()
    
    if not os.path.exists(system_ca_db):
        open(system_ca_db, 'w')
    
    system_ca_certs = open(system_ca_db, 'r').read()
    system_ca_certs_list = p.findall(system_ca_certs)
    
    if ca_cert in system_ca_certs_list:
        new_system_ca_certs = []
        for cert in system_ca_certs_list:
            if ca_cert != cert:
                new_system_ca_certs.append(cert)
            else:
                print _('CA certificate deleted from the system trusted '
                        'certificates list')
        
        fd = open(system_ca_db, 'w')
        for cert in new_system_ca_certs:
            fd.write(cert)
        fd.close()
        
    return 0
예제 #12
0
    fc.write(cert)
    fc.close()

    try:
        pwdObj = pwd.getpwnam(user_name)
    except KeyError, e:
        print e
        return None
    os.chown(cert_file, pwdObj.pw_uid, pwdObj.pw_gid)
    os.chmod(cert_file, 0600)

    os.unlink(req_id_file)
    print _('Certificate saved. Your certificate ID: %s') %req_id

    if ca_root:
        clVars = DataVarsCore()
        clVars.importCore()
        clVars.flIniFile()
        system_ca_db = clVars.Get('cl_glob_root_cert')
        if os.path.exists(system_ca_db):
            if ca_root in open(system_ca_db, 'r').read():
                return 0

        ca_dir = os.path.join(client_cert_path, 'ca')
        if not os.path.isdir(ca_dir):
            os.makedirs(ca_dir)
        os.chown(ca_dir, pwdObj.pw_uid, pwdObj.pw_gid)
        os.chmod(ca_dir, 0755)
        root_cert_md5 = os.path.join(ca_dir, "cert_list")

        md5 = hashlib.md5()
예제 #13
0
def main(*args, **keywords):
    if os.path.basename(sys.argv[0]) != 'cl-core':
        parser = cert_cmd.parse(full=False)
        args, unknown_args = parser.parse_known_args()
        args.method = '_temp_'
    else:
        parser = cert_cmd.parse(full=True)
        args, unknown_args = parser.parse_known_args()
        if args.method:
            parser = cert_cmd.parse(full=False)
            args, unknown_args = parser.parse_known_args()

    if not args.method:
        if unknown_args:
            args = parser.parse_args()

    if args.help and not args.method:
        parser.print_help()
        return 0

    from calculate.core.datavars import DataVarsCore
    ob = DataVarsCore()
    ob.importCore()

    # set var env
    if not ob.flIniFile():
        sys.exit(1)
#    cl_wsdl = ob.Get('cl_wsdl')
    cl_wsdl = ob.Get('cl_wsdl_available')
    data_path = ob.Get('cl_core_data')
    local_data_path = ob.Get('cl_core_local_data')
    certbase = ob.Get('cl_core_database')
    serv_certbase = ob.Get('cl_core_serv_database')
    rights = ob.Get('cl_core_rights')
    group_rights = ob.Get('cl_core_group_rights')
    sids = ob.Get('cl_core_sids_path')
    pids = ob.Get('cl_core_pids_path')
    sids_pids = ob.Get('cl_core_sids_pids')
    sids_file = ob.Get('cl_core_sids_file')
    pids_file = ob.Get('cl_core_pids_file')
    max_sid = ob.Get('cl_core_max_sid')
    max_pid = ob.Get('cl_core_max_pid')
    cert_path = ob.Get('cl_core_cert_path')
    cert = ob.Get('cl_core_cert')
    key = ob.Get('cl_core_key')
    cl_ver = ob.Get('cl_ver')
    log_path_var = ob.Get('cl_log_path')

    if args.version:
        print cl_ver
        return 0

    if os.getuid():
        if any("sbin" in x for x in sys.argv[0].split('/')):
            print _("User must be root")
            sys.exit(1)
    elif ob.Get('cl_ebuild_phase') == '':
        import logging
        import logging.handlers

        log_path = args.log_path if args.log_path else log_path_var

        if not os.path.exists(log_path):
            os.makedirs(log_path)
        LOG_FILENAME = os.path.join(log_path, 'logging_cl_core.out')
        file_logger = logging.getLogger('MyLogger')
        file_logger.setLevel(logging.DEBUG)

        # Add the log message handler to the logger
        handler = logging.handlers.RotatingFileHandler(
                    LOG_FILENAME, maxBytes=10000000, backupCount=3)

        file_logger.addHandler(handler)

        # debug
        if args.debug:
            logging.basicConfig(level=logging.DEBUG)
            logger = logging.getLogger('soaplib.wsgi')
            logger.setLevel(logging.DEBUG)

        from urllib2 import URLError

    from traceback import print_exc
    if not args.method:
        try:
            port = args.port
            if args.check:
                import bootstrap
                bootstrap.check(cert, key, cert_path, data_path, certbase, args)
                return 0
            if args.bootstrap_user_name:
                import bootstrap
                bootstrap.init(cert, key, cert_path, data_path, certbase, args, \
                               port, args.bootstrap_user_name)
                return 0
            if args.revoke_cert_id:
                cert_cmd.revoke_signed_cert(args.revoke_cert_id, data_path,
                                            cert_path)
                return 0
            if args.host or args.gen_root_cert or args.root_host or \
                                                               args.use_root_cert:
                cert_cmd.check_server_certificate(cert, key, cert_path, args, port)
                return 0
            if args.id_client_req:
                cert_cmd.sing_req_by_server(args.id_client_req,cert_path,data_path)
                return 0
            if args.Id:
                cert_cmd.view_cert(args, certbase, data_path, rights, group_rights)
                return 0
            if args.cert_id:
                cert_cmd.view_signed_cert(args, serv_certbase, data_path)
                return 0
            if args.req_id:
                cert_cmd.view_client_request(args, certbase, data_path)
                return 0
            # Sign request by root certificate
            if args.id_server_req:
                cert_cmd.sing_req_by_root(args, cert_path, data_path)
                return 0
            if args.id_del_req or args.id_del_client_req:
                cert_cmd.del_request(args.id_del_req, args.id_del_client_req,
                                     serv_certbase, certbase, data_path)
                return 0
        except URLError, e:
            fd = open(LOG_FILENAME,'a')
            file_logger.debug(print_exc(file=fd))
            fd.close()
            print e
예제 #14
0
def monitor(certbase, SID_FILE):
    """ function to delete old session """
    # set default
    period = 180
    sid_live = 240
#    cert_live = 10080
    # Get value of period and lifetime session from DataVars
    try:
        ob = DataVarsCore()
        ob.importCore()

        if not ob.flIniFile():
            sys.exit(1)
        period = float(ob.Get('cl_core_monitor_period'))
        sid_live = float(ob.Get('cl_core_sid_live'))
    except:
        print _("Variable cl_core_monitor_period or cl_core_sid_live not "
                "found")
        raise
        return 1
    # Check lifetime. if necessary, remove
    while True:
        # check session
        try:
            SID_FILE_T = SID_FILE + '_temp'
            fd = open(SID_FILE, 'r')
            ft = open(SID_FILE_T, 'w')
            while 1:
                try:
                    # read all on one record
                    list_sid = pickle.load(fd)
                except:
                    break
                # how time exists session
                delta = datetime.datetime.now() - list_sid[2]
                # if not outdated, then leave
                if (delta.seconds < sid_live * 60):
                    pickle.dump(list_sid, ft)
            fd.close()
            ft.close()
            
            # copy all from temp file
            ft = open(SID_FILE_T, 'rb')
            fd = open(SID_FILE, 'wb')
            ft.seek(0)
            fd.write(ft.read())
            ft.close()
            fd.close()
            
            # Delete temp file
            os.unlink(SID_FILE_T)
        except:
            return 1
        
        ## check certificate
        ##try:
        #if not os.path.exists(CERT_FILE):
            #temp = open(CERT_FILE, 'w')
            #temp.close()
        
        #rst = []
        #CERT_FILE_T = certbase + '_temp'
        #fc = open(CERT_FILE, 'r')
        #fct = open(CERT_FILE_T, 'w')
        #while 1:
            #try:
                ## Считать по одной строке
                #list_cert = pickle.load(fc)
            #except:
                #break
            ## Сколько существует certificate
            #delta = datetime.datetime.now() - list_cert["date"]
            ## Если не устарел, то оставить
            #if (delta.seconds < cert_live * 60):
                #pickle.dump(list_cert, fct)
            #else:
                #cert_met = serv_get_methods(list_cert["cert"])
                #if cert_met[0] != "No Method":
                    #pickle.dump(list_cert, fct)
        #fc.close()
        #fct.close()
        
        ## Скопировать всё из временного файла
        #fct = open(CERT_FILE_T, 'rb')
        #fc = open(CERT_FILE, 'wb')
        #fct.seek(0)
        #fc.write(fct.read())
        #fct.close()
        #fc.close()
        
        ## Удалить временный файл
        #os.unlink(CERT_FILE_T)
        ##except:
            ##print _("file %s not exists") % CERT_FILE
        # Частота проверки
        time.sleep(60 * period)
예제 #15
0
    def add_all_ca_cert(self, list_ca_certs):
        # so root cert be first, ca after
        clVarsCore = DataVarsCore()
        clVarsCore.importCore()
        clVarsCore.flIniFile()

        list_ca_certs.reverse()
        system_ca_db = clVarsCore.Get("core.cl_glob_root_cert")

        clVars = DataVars()
        clVars.flIniFile()
        homePath = clVars.Get("ur_home_path")
        cl_client_cert_dir = clVarsCore.Get("core.cl_client_cert_dir")
        cl_client_cert_dir = cl_client_cert_dir.replace("~", homePath)
        root_cert_md5 = os.path.join(cl_client_cert_dir, "ca/cert_list")

        user_root_cert = clVarsCore.Get("core.cl_user_root_cert")
        user_root_cert = user_root_cert.replace("~", homePath)

        for cert in list_ca_certs:
            if os.path.exists(system_ca_db):
                if cert in open(system_ca_db, "r").read():
                    continue

            if os.path.exists(user_root_cert):
                if cert in open(user_root_cert, "r").read():
                    continue

            md5 = hashlib.md5()
            md5.update(cert)
            md5sum = md5.hexdigest()
            print "\n================================================="
            print "md5sum = ", md5sum

            if not os.path.exists(root_cert_md5):
                fc = open(root_cert_md5, "w")
                fc.close()

            filename = None
            with open(root_cert_md5) as fd:
                t = fd.read()
                # for each line
                for line in t.splitlines():
                    # Split string into a words list
                    words = line.split(" ", 1)
                    if words[0] == md5sum:
                        filename = words[1]
            if not filename:
                certobj = OpenSSL.crypto.load_certificate(OpenSSL.SSL.FILETYPE_PEM, cert)
                Issuer = certobj.get_issuer().get_components()
                for item in Issuer:
                    if item[0] == "CN":
                        filename = item[1]

                fc = open(root_cert_md5, "a")
                fc.write("%s %s\n" % (md5sum, filename))
                fc.close()

                if not filename:
                    print _('Field "CN" not found in the certificate!')
                    return 1

                fd = open(os.path.join(cl_client_cert_dir, "ca/", filename), "w")
                fd.write(cert)
                fd.close()

                fa = open(user_root_cert, "a")
                fa.write(cert)
                fa.close()
                print _("filename = "), filename
                print _("Certificate added")
            else:
                print _("The file containing the CA certificate now exists")
        get_CRL(cl_client_cert_dir)
예제 #16
0
def main(wait_thread):
    parser = parse()
    args, unknown_args = parser.parse_known_args()
    wait_thread.start()

#    if os.path.basename(sys.argv[0]) != 'cl-console':
#        args.method = '_temp_'
#        args.host = 'localhost'

    if not args.method and args.help:
        wait_thread.stop()
        sys.stdout.write('\r')
        sys.stdout.flush()
        parser.print_help()
        return 0

    if not args.method:
        if unknown_args:
            wait_thread.stop()
            sys.stdout.write('\r')
            sys.stdout.flush()
            args = parser.parse_args()

    logging.basicConfig(level=logging.FATAL)
    logging.getLogger('sudsds.client').setLevel(logging.FATAL)
    logging.getLogger('sudsds.transport').setLevel(logging.FATAL)
    logging.getLogger('sudsds.transport.http').setLevel(logging.FATAL)
    logging.getLogger('sudsds.umx.typed').setLevel(logging.ERROR)

    clVarsCore = DataVarsCore()
    clVarsCore.importCore()
    clVarsCore.flIniFile()

    homePath = clVarsCore.Get('ur_home_path')

    port = args.port
    host = args.host
    path_to_cert = args.path_to_cert
    if not path_to_cert:
        path_to_cert = clVarsCore.Get('core.cl_client_cert_dir')
    path_to_cert = path_to_cert.replace("~",homePath)

    for dirs in ['', 'ca', 'trusted']:
        dir_path = os.path.join(path_to_cert, dirs)
        if not os.path.isdir(dir_path):
            if not makeDirectory(dir_path):
                wait_thread.stop()
                sys.stdout.write('\r')
                sys.stdout.flush()
                print _("Failed to create directory %s") %dir_path
                return 1

    if args.update_crl:
        wait_thread.stop()
        getCRL = threading.Thread(target=get_CRL, args = (path_to_cert, ))
        getCRL.start()
        getCRL.join()
        print 'GRL updated'
        return 0

    if args.by_host:
        wait_thread.stop()
        client_post_request (path_to_cert, args)
        return 0
    if args.from_host:
        wait_thread.stop()
        client_get_cert (path_to_cert, args)
        return 0

    url = "https://%s:%d/?wsdl" %(host, port)

    clear()
    serv_hostname = get_server_hostname(host, path_to_cert)
    get_name_flag = False
    if serv_hostname:
        Connect_Error = 1
        crypto_Error = 0
        client, Connect_Error, crypto_Error, passwd_flag, e = \
                    connect_with_cert (serv_hostname, path_to_cert, url, args,
                         wait_thread, clVarsCore, crypto_Error, Connect_Error)
        if not wait_thread.isAlive():
            wait_thread = StoppableThread()
            wait_thread.start()
        get_name_flag = True
        if Connect_Error:
            if crypto_Error and passwd_flag:
                wait_thread.stop()
                sys.stdout.write('\r')
                sys.stdout.flush()
                print _('Invalid password')
                # delete password from daemon list
                clear_password(host, port)
            elif e:
                wait_thread.stop()
                if type(e.message) != int:
                    print _('Error: '), e
            get_name_flag = False

    if get_name_flag:
        try:
            client.port = port
            return_val = 1
            try:
                return_val = https_server(client, args, unknown_args, url, \
                                          clVarsCore, wait_thread)
            except urllib2.URLError, e:
                print _('Error: '), e
            except KeyboardInterrupt:
                wait_thread.stop()
                red = '\n'+'\033[31m * \033[0m'
                print red + _("Manually interrupted")
            except Exception, e:
                wait_thread.stop()
                if type(e.message) != int:
                    if e.message:
                        print e.message
                    elif e.args:
                        print e
#                    tb.print_exc()
                return 1
            wait_thread.stop()
            return return_val
예제 #17
0
    def add_server_cert(self, cert):
        self.wait_thread.stop()
        print _("Untrusted server certificate!")
        certobj = OpenSSL.crypto.load_certificate(OpenSSL.SSL.FILETYPE_PEM, cert)
        print "\n" + _("Fingerprint = %s") % certobj.digest("SHA1")
        print _("Serial Number = "), certobj.get_serial_number()
        Issuer = certobj.get_issuer().get_components()
        print "\n" + _("Issuer")
        for i in Issuer:
            print "%s : %s" % (i[0], i[1])
        Subject = certobj.get_subject().get_components()
        print "\n" + _("Subject")
        for item in Subject:
            print "%s : %s" % (item[0], item[1])

        print "\n" + _("Add this server certificate to trusted (s) or")
        print _("Try to add the CA and root certificates to trusted (c) or")
        choice = raw_input(_("Quit (q)? s/c/[q]: "))
        if choice.lower() in ["s", "c"]:
            # self.sock = ssl.wrap_socket(sock)
            ca_certs = os.path.join(self.trusted_path, "cert.list")

            if not os.path.exists(ca_certs):
                fc = open(ca_certs, "w")
                fc.close()

            if self.host == "127.0.0.1":
                host = "localhost"
            else:
                host = self.host
            filename = host
            fc = open(self.trusted_path + filename, "w")
            fc.write(cert)
            fc.close()
            with open(ca_certs) as fd:
                t = fd.read()
                # for each line
                for line in t.splitlines():
                    # Split string into a words list
                    words = line.split()
                    if len(words) > 1:
                        # if first word...
                        if words[0] == host:
                            return 0
            # Open file with compliance server certificates and server hostname
            fcl = open(ca_certs, "a")
            fcl.write(host + " " + filename + "\n")
            fcl.close()
            if choice.lower() != "c":
                return 3
        if choice.lower() == "c":
            clVars = DataVarsCore()
            clVars.importCore()
            clVars.flIniFile()
            cl_client_cert_dir = clVars.Get("core.cl_client_cert_dir")
            homePath = clVars.Get("ur_home_path")
            cl_client_cert_dir = cl_client_cert_dir.replace("~", homePath)
            root_cert_dir = os.path.join(cl_client_cert_dir, "ca")

            if not os.path.exists(root_cert_dir):
                try:
                    os.makedirs(root_cert_dir)
                except OSError:
                    print _("Failed to create directory %s") % root_cert_dir
                    raise Exception(1)

            print "\n" + _("Add the CA and root certificates")
            self.list_ca_certs = []
            self.add_ca_cert(cert, self.list_ca_certs)
            return 3
        elif not choice.lower() in ["c", "s"]:
            return 4
예제 #18
0
def check_server_certificate(cert, key, cert_path, args, port, auto = False):
    if not os.path.isdir(cert_path):
        os.makedirs(cert_path)
    # generate a root certificate
    if args.gen_root_cert:
        if auto:
            c = 'n'
        else:
            c = raw_input (_("Enter the certificate date manually? [y]/n: "))
        from M2Crypto import X509
        name = X509.X509_Name()

        ob = DataVarsCore()
        ob.importCore()
        if not ob.flIniFile():
            sys.exit(1)

        lang = ob.Get('os_locale_locale')[:2]

        host_name = socket.getfqdn()
        if c.lower() in ['n', 'no']:
            name.CN = host_name #(Common Name); 
            name.OU = 'www.calculate-linux.ru' # (Organization Unit);
            name.O = 'calculate-linux'# (Organization Name);
            name.L = host_name+':'+str(port) # (Locality Name); 
            name.ST = 'Spb'# (State Name);
            name.C = lang # (Country);
        else:
            print _('Do not use spaces or tabs.')
            host_name = socket.getfqdn()
            name.CN = raw_input (_('Hostname [%s] : ') %host_name)
            if name.CN in ['', None]:
                name.CN = host_name
            name.OU = raw_input (_('Organization unit: '))
            if not name.OU:
                name.OU = ''
            else:
                name.OU.replace(' ', '_').replace('\t', '_')
            name.O = raw_input (_('Organization name: '))
            if not name.O:
                name.O = ''
            else:
                name.O.replace(' ', '_').replace('\t', '_')
            network = _('Full network address (host:port)')
            name.L = raw_input (network + ' [%s:%d]: ' \
                                %(host_name, port)) 
            if name.L in ['', None]:
                name.L = host_name + ':' + str(port)
            name.ST = raw_input (_('City: '))
            if not name.ST:
                name.ST = ''
            else:
                name.ST.replace(' ', '_').replace('\t', '_')
            name.C = raw_input (_('Country (two letters only!) [%s]: ') %lang)
            if not name.C:
                name.C = lang

        from create_cert import passphrase_callback, generateRSAKey, \
                                makePKey, makeCert

        # Generating public key
        rsa = generateRSAKey()
        rsa.save_key(cert_path+'/root.key'+'_pub', cipher = None, \
                     callback=passphrase_callback)

        # Generating private key
        pkey = makePKey(rsa)
        pkey.save_key(cert_path+'/root.key', cipher = None, \
                      callback=passphrase_callback)

        # Generating request
#        req = makeRequest(rsa, pkey, host_name, port)
        req = X509.Request()
        req.set_version(req.get_version())
        req.set_pubkey(pkey)
        req.set_subject_name(name)

        ext1 = X509.new_extension('Comment', 'Auto Generated')
        extstack = X509.X509_Extension_Stack()
        extstack.push(ext1)
        req.add_extensions(extstack)
        req.sign(pkey, 'md5')
        req.save_pem(cert_path + '/root.csr')

        # Generating Certificate
        cert = makeCert(req, pkey, name)
        cert.save_pem(cert_path + '/root.crt')

        # add certificate in trusted
        fd = open(cert_path+'/ca_root.crt', 'a')
        try:
            fd.write(open(cert_path+'/root.crt', 'r').read())
        except:
            print _('error writing to (reading from) files in directory %s') \
                                                                %cert_path
        fd.close()
        print _("OK")

    # use self root certificate as server certificate
    elif args.use_root_cert:
        if not os.path.exists(cert_path+'/root.crt'):
            print _('root certificate not found (use cl-core with '
                    'option --gen-root-cert)')
            return 1

        print _('Using the root certificate as the server certificate')
        # use root certificate as server certificate
        ft = open(cert_path+'/root.crt', 'rb')
        fd = open(cert_path+'/server.crt', 'wb')
        ft.seek(0)
        fd.write(ft.read())
        ft.close()
        fd.close()

        ft = open(cert_path+'/root.key', 'rb')
        fd = open(cert_path+'/server.key', 'wb')
        ft.seek(0)
        fd.write(ft.read())
        ft.close()
        fd.close()

        print _("OK")
        return 0

    # send a certificate signing request to another server
    elif args.host:
        port = args.port if args.port else 8888
        url = "https://%s:%d/?wsdl" %(args.host, port)
        print url + '\n' + _("connecting...")
        from sudsds.client import Client
        from client_class import HTTPSClientsCertTransport
        from urllib2 import URLError
        try:
            client = Client(url, \
                       transport = HTTPSClientsCertTransport(None, None, None))
        except (KeyboardInterrupt, URLError):
            print '\n'+_("Close. Connection Error.")
            return 1

        serv_host_name = client.service.get_server_host_name()

        if os.path.exists(key) and os.path.exists(cert_path + '/server.csr'):
            print _("the private key and request now exist")
            ask = raw_input(_("Create a new private key and request?")+\
                            " y/[n]: ")
            if ask.lower() in ['y','yes']:
                new_key_req(key, cert_path, serv_host_name, port)
        else:
            new_key_req(key, cert_path, serv_host_name, port)

        ip = getIpLocal()
        mac = getHwAddr()
        data = open(cert_path + '/server.csr').read()
        res = client.service.post_server_request(request = data, ip = ip,\
                                        mac = mac)
        if int(res) < 0:
            print _("This server is not enabled to sign certificates!")
            return 1
        fc = open(cert_path + '/req_id', 'w')
        fc.write(res)
        fc.close()
        print _("Your request ID = %s") %res
        return 0

    # get a signed certificate from another server
    elif args.root_host:
        if not os.path.exists(cert_path + '/req_id'):
            print _("request not sent or file %s deleted") \
                    %(cert_path + '/req_id')
            return 1
        fc = open(cert_path + '/req_id', 'r')
        req_id = fc.read()
        fc.close()

        port = args.port if args.port else 8888
        url = "https://%s:%d/?wsdl" %(args.root_host, port)
        print url + '\n' + _("connecting...")

        from sudsds.client import Client
        from client_class import HTTPSClientsCertTransport
        try:
            client = Client(url, \
                       transport = HTTPSClientsCertTransport(None, None, None))
        except KeyboardInterrupt:
            print '\n'+_("Close. Connection Error.")

        request = open(cert_path + '/server.csr').read()
        md5 = hashlib.md5()
        md5.update(request)
        md5sum = md5.hexdigest()

        result = client.service.get_server_cert(req_id, md5sum)
        cert = result[0][0]
        ca_root = result[0][1]
        if cert == '1':
            print _('The signature request was rejected!')
            return 1
        elif cert == '2':
            print _("The signature request has not been examined yet.")
            print _("Your request ID = %s") %req_id
            return 1
        elif cert == '3':
            print _('The signature request does not match earlier data.')
            return 1
        elif cert == '4':
            print _("The request was sent from another IP.")
            return 1
        fc = open(cert_path + '/server.crt', 'w')
        fc.write(cert)
        fc.close()
        os.unlink(cert_path + '/req_id')
        print _('Certificate saved. Your certificate ID = %s') %req_id
        fd = open(cert_path + '/ca_root.crt', 'w')
        if ca_root:
            fd.write(ca_root)
        #fd.write(cert)
        if os.path.exists(cert_path + '/ca_root.crt'):
            fd.write(open(cert_path + '/ca_root.crt', 'r').read())
        fd.close()
        return 0