Example #1
0
def new_key_req(key, cert_path, server_host_name, private_key_passwd = None, \
                auto = False):
    from create_cert import generateRSAKey, makePKey, makeRequest,\
                                    passphrase_callback
    rsa = generateRSAKey()
    rsa.save_key(key+'_pub', cipher=None, callback = lambda *unused: None)

    pkey = makePKey(rsa)
    if not passphrase_callback(private_key_passwd):
        pkey.save_key(key, cipher = None, callback = lambda *unused: None)
    else:
        pkey.save_key(key, callback= lambda *unused: str(private_key_passwd))

    req = makeRequest(rsa, pkey, server_host_name, auto)
    crtreq = req.as_pem()

    req_file = cert_path + '/%s.csr' %server_host_name
    crtfile = open(req_file, 'w')
    crtfile.write(crtreq)
    crtfile.close()

    user_name = pwd.getpwuid(os.getuid()).pw_name
    try:
        pwdObj = pwd.getpwnam(user_name)
    except KeyError, e:
        _print (e)
        return None
Example #2
0
def new_key_req(key, cert_path, server_host_name, auto = False):
    rsa = generateRSAKey()
    rsa.save_key(key+'_pub', cipher=None, callback=passphrase_callback)
    
    pkey = makePKey(rsa)
    pkey.save_key(key, cipher=None, callback=passphrase_callback)
    
    req = makeRequest(rsa, pkey, server_host_name, auto)
    crtreq = req.as_pem()
    
    req_file = os.path.join(cert_path, '%s.csr' %server_host_name)
    crtfile = open(req_file, 'w')
    crtfile.write(crtreq)
    crtfile.close()
    return req_file
Example #3
0
def new_key_req(key, cert_path, serv_host_name, port):
    from create_cert import generateRSAKey, makePKey, makeRequest,\
                                    passphrase_callback
    rsa = generateRSAKey()
    rsa.save_key(key+'_pub',\
                        cipher=None, callback=passphrase_callback)

    pkey = makePKey(rsa)
    pkey.save_key(key,\
                        cipher=None, callback=passphrase_callback)

    req = makeRequest(rsa, pkey, serv_host_name, port)
    if not req:
        sys.exit()
    crtreq = req.as_pem()
    crtfile = open(cert_path + '/server.csr', 'w')
    crtfile.write(crtreq)
    crtfile.close()
Example #4
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