myPKI.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. #!/usr/bin/env python3
  2. import sys, getopt, os
  3. def usage():
  4. print(' USAGE: ./myPKI.py [OPTIONS]')
  5. print(' OPTIONS:')
  6. print('\t-A --initall\t-i -g -d -s')
  7. print('\t-i --init\tInitialise directorys of PKI')
  8. print('\t-g --genca\tGenerate CA root')
  9. print('\t-d --gender\tGenerate DER cert for browser know my self-signed cert')
  10. print('\t-s --gensign\tGenerate and sign certificate for hosts')
  11. print('\t-n --genauth\tGenerate and sign certificate for client authenticationf in .pfx format')
  12. print('\t-h --help\tShows this help')
  13. def generate_client_auth_cert():
  14. print("\n\nGénération d'un certificat client pour authentification")
  15. print("=========================================================\n")
  16. tld = input("=> TLD of your certificate :")
  17. client_name = input("=> Client Name :")
  18. with open('./config/ca.config', 'r') as file:
  19. newText = file.read().replace('DNSCHANGEME', tld)
  20. newText = newText.replace('Root Certificate', tld)
  21. with open('./config/ca.config', 'w') as file:
  22. file.write(newText)
  23. print("=> Création du certificat client")
  24. os.system("openssl genrsa -out ./certificats/" +client_name+ "_" +tld+ ".key 4096")
  25. print("[*] " +client_name+"_"+tld+".key is done")
  26. os.system('openssl req -new -config config/ca.config -key ./certificats/'+client_name+ '_' +tld+ '.key -out ./certificats/'+ client_name +'-remote.csr')
  27. print("[*] CSR Request completed !")
  28. os.system('openssl req -x509 -days 3650 -in ./certificats/'+client_name+'-remote.csr -CA ./certificats/ca.crt -CAkey ./certificats/ca.key -set_serial 001 -out ./certificats/'+client_name+'-remote.pem')
  29. print("[*] Sign OK")
  30. os.system("openssl pkcs12 -export -out ./"+client_name+".full.pfx -inkey ./certificats/"+client_name+'_'+tld+".key -in ./certificats/"+client_name+"-remote.pem -certfile ./certificats/ca.crt")
  31. print("[*] Certificate OK")
  32. # restauration du fichier de config
  33. with open('./config/ca.config', 'r') as file:
  34. newText = file.read().replace(tld, 'DNSCHANGEME')
  35. newText = newText.replace(tld, 'Root Certificate')
  36. with open('./config/ca.config', 'w') as file:
  37. file.write(newText)
  38. def generate_sign():
  39. print("\n\nGénération d'un certificat pour un hôte")
  40. print("=====================================\n")
  41. tld = input("=> TLD of your certificate :")
  42. ip_addr = input("=> IPv4 :")
  43. # Changement du fichier de config
  44. with open('./config/ca.config', 'r') as file:
  45. newText = file.read().replace('DNSCHANGEME', tld)
  46. newText = newText.replace('0.0.0.0', ip_addr)
  47. newText = newText.replace('Root Certificate', tld)
  48. with open('./config/ca.config', 'w') as file:
  49. file.write(newText)
  50. # Création des certificats
  51. print("=> Création du certificat pour " + tld)
  52. os.system("openssl genrsa -out ./certificats/"+tld+".key 4096")
  53. print("[*] "+tld+".key is donei")
  54. print("=> Création de la CSR")
  55. os.system("openssl req -new -config config/ca.config -key ./certificats/"+tld+".key -out certificats/"+tld+".csr")
  56. print("[*] CSR Request completed !")
  57. print("=> Signature du certificat")
  58. os.system("openssl ca -out "+tld+".crt -config config/ca.config -infiles certificats/"+tld+".csr ")
  59. print("[*] Sign OK")
  60. # On restaure ca.config d'origine
  61. with open('./config/ca.config', 'r') as file:
  62. newText = file.read().replace(tld, 'DNSCHANGEME')
  63. newText = newText.replace(ip_addr, '0.0.0.0')
  64. newText = newText.replace(tld, 'Root Certificate')
  65. with open('./config/ca.config', 'w') as file:
  66. file.write(newText)
  67. print("[*] Certificate Signed !")
  68. def generate_der():
  69. print("\n\nGénération d'un certificat DER pour les navigateurs")
  70. print("=================================================\n")
  71. if not os.path.isfile("./certificats/ca.der"):
  72. os.system("openssl x509 -in certificats/ca.crt -outform DER -out certificats/ca.der")
  73. print("[*] Put public CA ./certificats/ca.der on all browser you see !")
  74. else:
  75. print("[x] DER Certificate already exist...")
  76. def generate_ca():
  77. print("\n\nGénération d'une autorité de certification")
  78. print("========================================\n")
  79. if not os.path.isfile("./certificats/ca.key"):
  80. os.system("openssl genrsa -out ./certificats/ca.key 4096")
  81. os.system("openssl req -utf8 -new -x509 -days 3000 -config ./config/ca.config -key ./certificats/ca.key -out ./certificats/ca.crt")
  82. print("[*] CA Certificate done !")
  83. else:
  84. print("[x] CA Certificate already exist...")
  85. def init_dir():
  86. print("\n\nInitialisation des répertoires")
  87. print("================================\n")
  88. if not os.path.exists("./db/ca.db.certs"):
  89. print("[*] Creating directories")
  90. os.makedirs("./db/ca.db.certs")
  91. os.makedirs("./config")
  92. os.makedirs("./certificats")
  93. os.system("echo '01'> ./db/ca.db.serial")
  94. os.system("cp /dev/null ./db/ca.db.index")
  95. os.system("cp ./ca.config.sample ./config/ca.config")
  96. os.system("touch ./db/ca.db.index.attr")
  97. else:
  98. print("[x] Directorys already exist")
  99. def main():
  100. try:
  101. opts, args = getopt.getopt(sys.argv[1:], "Ahigdsn", ["initall", "help", "init", "genca", "gender", "gensign", "genauth"])
  102. for o, a in opts:
  103. if o in ("--help"):
  104. usage()
  105. sys.exit()
  106. elif o in ("--genca"):
  107. generate_ca()
  108. elif o in ("--init"):
  109. init_dir()
  110. elif o in ("--gender"):
  111. generate_der()
  112. elif o in ("--gensign"):
  113. generate_sign()
  114. elif o in ("--genauth"):
  115. generate_client_auth_cert()
  116. elif o in ("--initall"):
  117. init_dir()
  118. generate_ca()
  119. generate_der()
  120. generate_sign()
  121. sys.exit()
  122. if not opts:
  123. usage()
  124. sys.exit()
  125. except getopt.GetoptError as err:
  126. sys.stderr.write(str(err))
  127. usage()
  128. sys.exit(2)
  129. if __name__ == "__main__":
  130. main()