acme.sh 113 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576
  1. #!/usr/bin/env sh
  2. VER=2.6.5
  3. PROJECT_NAME="acme.sh"
  4. PROJECT_ENTRY="acme.sh"
  5. PROJECT="https://github.com/Neilpang/$PROJECT_NAME"
  6. DEFAULT_INSTALL_HOME="$HOME/.$PROJECT_NAME"
  7. _SCRIPT_="$0"
  8. _SUB_FOLDERS="dnsapi deploy"
  9. DEFAULT_CA="https://acme-v01.api.letsencrypt.org"
  10. DEFAULT_AGREEMENT="https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf"
  11. DEFAULT_USER_AGENT="$PROJECT_NAME/$VER ($PROJECT)"
  12. DEFAULT_ACCOUNT_EMAIL=""
  13. DEFAULT_ACCOUNT_KEY_LENGTH=2048
  14. DEFAULT_DOMAIN_KEY_LENGTH=2048
  15. DEFAULT_OPENSSL_BIN="openssl"
  16. STAGE_CA="https://acme-staging.api.letsencrypt.org"
  17. VTYPE_HTTP="http-01"
  18. VTYPE_DNS="dns-01"
  19. VTYPE_TLS="tls-sni-01"
  20. #VTYPE_TLS2="tls-sni-02"
  21. LOCAL_ANY_ADDRESS="0.0.0.0"
  22. MAX_RENEW=60
  23. DEFAULT_DNS_SLEEP=120
  24. NO_VALUE="no"
  25. W_TLS="tls"
  26. STATE_VERIFIED="verified_ok"
  27. BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
  28. END_CSR="-----END CERTIFICATE REQUEST-----"
  29. BEGIN_CERT="-----BEGIN CERTIFICATE-----"
  30. END_CERT="-----END CERTIFICATE-----"
  31. RENEW_SKIP=2
  32. ECC_SEP="_"
  33. ECC_SUFFIX="${ECC_SEP}ecc"
  34. LOG_LEVEL_1=1
  35. LOG_LEVEL_2=2
  36. LOG_LEVEL_3=3
  37. DEFAULT_LOG_LEVEL="$LOG_LEVEL_1"
  38. _DEBUG_WIKI="https://github.com/Neilpang/acme.sh/wiki/How-to-debug-acme.sh"
  39. __INTERACTIVE=""
  40. if [ -t 1 ]; then
  41. __INTERACTIVE="1"
  42. fi
  43. __green() {
  44. if [ "$__INTERACTIVE" ]; then
  45. printf '\033[1;31;32m'
  46. fi
  47. printf -- "$1"
  48. if [ "$__INTERACTIVE" ]; then
  49. printf '\033[0m'
  50. fi
  51. }
  52. __red() {
  53. if [ "$__INTERACTIVE" ]; then
  54. printf '\033[1;31;40m'
  55. fi
  56. printf -- "$1"
  57. if [ "$__INTERACTIVE" ]; then
  58. printf '\033[0m'
  59. fi
  60. }
  61. _printargs() {
  62. if [ -z "$NO_TIMESTAMP" ] || [ "$NO_TIMESTAMP" = "0" ]; then
  63. printf -- "%s" "[$(date)] "
  64. fi
  65. if [ -z "$2" ]; then
  66. printf -- "%s" "$1"
  67. else
  68. printf -- "%s" "$1='$2'"
  69. fi
  70. printf "\n"
  71. }
  72. _dlg_versions() {
  73. echo "Diagnosis versions: "
  74. echo "openssl:$OPENSSL_BIN"
  75. if _exists "$OPENSSL_BIN"; then
  76. $OPENSSL_BIN version 2>&1
  77. else
  78. echo "$OPENSSL_BIN doesn't exists."
  79. fi
  80. echo "apache:"
  81. if [ "$_APACHECTL" ] && _exists "$_APACHECTL"; then
  82. _APACHECTL -V 2>&1
  83. else
  84. echo "apache doesn't exists."
  85. fi
  86. echo "nc:"
  87. if _exists "nc"; then
  88. nc -h 2>&1
  89. else
  90. _debug "nc doesn't exists."
  91. fi
  92. }
  93. _log() {
  94. [ -z "$LOG_FILE" ] && return
  95. _printargs "$@" >>"$LOG_FILE"
  96. }
  97. _info() {
  98. _log "$@"
  99. _printargs "$@"
  100. }
  101. _err() {
  102. _log "$@"
  103. if [ -z "$NO_TIMESTAMP" ] || [ "$NO_TIMESTAMP" = "0" ]; then
  104. printf -- "%s" "[$(date)] " >&2
  105. fi
  106. if [ -z "$2" ]; then
  107. __red "$1" >&2
  108. else
  109. __red "$1='$2'" >&2
  110. fi
  111. printf "\n" >&2
  112. return 1
  113. }
  114. _usage() {
  115. __red "$@" >&2
  116. printf "\n" >&2
  117. }
  118. _debug() {
  119. if [ -z "$LOG_LEVEL" ] || [ "$LOG_LEVEL" -ge "$LOG_LEVEL_1" ]; then
  120. _log "$@"
  121. fi
  122. if [ -z "$DEBUG" ]; then
  123. return
  124. fi
  125. _printargs "$@" >&2
  126. }
  127. _debug2() {
  128. if [ "$LOG_LEVEL" ] && [ "$LOG_LEVEL" -ge "$LOG_LEVEL_2" ]; then
  129. _log "$@"
  130. fi
  131. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  132. _debug "$@"
  133. fi
  134. }
  135. _debug3() {
  136. if [ "$LOG_LEVEL" ] && [ "$LOG_LEVEL" -ge "$LOG_LEVEL_3" ]; then
  137. _log "$@"
  138. fi
  139. if [ "$DEBUG" ] && [ "$DEBUG" -ge "3" ]; then
  140. _debug "$@"
  141. fi
  142. }
  143. _startswith() {
  144. _str="$1"
  145. _sub="$2"
  146. echo "$_str" | grep "^$_sub" >/dev/null 2>&1
  147. }
  148. _endswith() {
  149. _str="$1"
  150. _sub="$2"
  151. echo "$_str" | grep -- "$_sub\$" >/dev/null 2>&1
  152. }
  153. _contains() {
  154. _str="$1"
  155. _sub="$2"
  156. echo "$_str" | grep -- "$_sub" >/dev/null 2>&1
  157. }
  158. _hasfield() {
  159. _str="$1"
  160. _field="$2"
  161. _sep="$3"
  162. if [ -z "$_field" ]; then
  163. _usage "Usage: str field [sep]"
  164. return 1
  165. fi
  166. if [ -z "$_sep" ]; then
  167. _sep=","
  168. fi
  169. for f in $(echo "$_str" | tr ',' ' '); do
  170. if [ "$f" = "$_field" ]; then
  171. _debug2 "'$_str' contains '$_field'"
  172. return 0 #contains ok
  173. fi
  174. done
  175. _debug2 "'$_str' does not contain '$_field'"
  176. return 1 #not contains
  177. }
  178. _getfield() {
  179. _str="$1"
  180. _findex="$2"
  181. _sep="$3"
  182. if [ -z "$_findex" ]; then
  183. _usage "Usage: str field [sep]"
  184. return 1
  185. fi
  186. if [ -z "$_sep" ]; then
  187. _sep=","
  188. fi
  189. _ffi="$_findex"
  190. while [ "$_ffi" -gt "0" ]; do
  191. _fv="$(echo "$_str" | cut -d "$_sep" -f "$_ffi")"
  192. if [ "$_fv" ]; then
  193. printf -- "%s" "$_fv"
  194. return 0
  195. fi
  196. _ffi="$(_math "$_ffi" - 1)"
  197. done
  198. printf -- "%s" "$_str"
  199. }
  200. _exists() {
  201. cmd="$1"
  202. if [ -z "$cmd" ]; then
  203. _usage "Usage: _exists cmd"
  204. return 1
  205. fi
  206. if eval type type >/dev/null 2>&1; then
  207. eval type "$cmd" >/dev/null 2>&1
  208. elif command >/dev/null 2>&1; then
  209. command -v "$cmd" >/dev/null 2>&1
  210. else
  211. which "$cmd" >/dev/null 2>&1
  212. fi
  213. ret="$?"
  214. _debug3 "$cmd exists=$ret"
  215. return $ret
  216. }
  217. #a + b
  218. _math() {
  219. _m_opts="$@"
  220. printf "%s" "$(($_m_opts))"
  221. }
  222. _h_char_2_dec() {
  223. _ch=$1
  224. case "${_ch}" in
  225. a | A)
  226. printf "10"
  227. ;;
  228. b | B)
  229. printf "11"
  230. ;;
  231. c | C)
  232. printf "12"
  233. ;;
  234. d | D)
  235. printf "13"
  236. ;;
  237. e | E)
  238. printf "14"
  239. ;;
  240. f | F)
  241. printf "15"
  242. ;;
  243. *)
  244. printf "%s" "$_ch"
  245. ;;
  246. esac
  247. }
  248. _URGLY_PRINTF=""
  249. if [ "$(printf '\x41')" != 'A' ]; then
  250. _URGLY_PRINTF=1
  251. fi
  252. _h2b() {
  253. hex=$(cat)
  254. i=1
  255. j=2
  256. _debug3 _URGLY_PRINTF "$_URGLY_PRINTF"
  257. while true; do
  258. if [ -z "$_URGLY_PRINTF" ]; then
  259. h="$(printf "%s" "$hex" | cut -c $i-$j)"
  260. if [ -z "$h" ]; then
  261. break
  262. fi
  263. printf "\x$h%s"
  264. else
  265. ic="$(printf "%s" "$hex" | cut -c $i)"
  266. jc="$(printf "%s" "$hex" | cut -c $j)"
  267. if [ -z "$ic$jc" ]; then
  268. break
  269. fi
  270. ic="$(_h_char_2_dec "$ic")"
  271. jc="$(_h_char_2_dec "$jc")"
  272. printf '\'"$(printf "%o" "$(_math "$ic" \* 16 + $jc)")""%s"
  273. fi
  274. i="$(_math "$i" + 2)"
  275. j="$(_math "$j" + 2)"
  276. done
  277. }
  278. #hex string
  279. _hex() {
  280. _str="$1"
  281. _str_len=${#_str}
  282. _h_i=1
  283. while [ "$_h_i" -le "$_str_len" ]; do
  284. _str_c="$(printf "%s" "$_str" | cut -c "$_h_i")"
  285. printf "%02x" "'$_str_c"
  286. _h_i="$(_math "$_h_i" + 1)"
  287. done
  288. }
  289. #options file
  290. _sed_i() {
  291. options="$1"
  292. filename="$2"
  293. if [ -z "$filename" ]; then
  294. _usage "Usage:_sed_i options filename"
  295. return 1
  296. fi
  297. _debug2 options "$options"
  298. if sed -h 2>&1 | grep "\-i\[SUFFIX]" >/dev/null 2>&1; then
  299. _debug "Using sed -i"
  300. sed -i "$options" "$filename"
  301. else
  302. _debug "No -i support in sed"
  303. text="$(cat "$filename")"
  304. echo "$text" | sed "$options" >"$filename"
  305. fi
  306. }
  307. _egrep_o() {
  308. if ! egrep -o "$1" 2>/dev/null; then
  309. sed -n 's/.*\('"$1"'\).*/\1/p'
  310. fi
  311. }
  312. #Usage: file startline endline
  313. _getfile() {
  314. filename="$1"
  315. startline="$2"
  316. endline="$3"
  317. if [ -z "$endline" ]; then
  318. _usage "Usage: file startline endline"
  319. return 1
  320. fi
  321. i="$(grep -n -- "$startline" "$filename" | cut -d : -f 1)"
  322. if [ -z "$i" ]; then
  323. _err "Can not find start line: $startline"
  324. return 1
  325. fi
  326. i="$(_math "$i" + 1)"
  327. _debug i "$i"
  328. j="$(grep -n -- "$endline" "$filename" | cut -d : -f 1)"
  329. if [ -z "$j" ]; then
  330. _err "Can not find end line: $endline"
  331. return 1
  332. fi
  333. j="$(_math "$j" - 1)"
  334. _debug j "$j"
  335. sed -n "$i,${j}p" "$filename"
  336. }
  337. #Usage: multiline
  338. _base64() {
  339. if [ "$1" ]; then
  340. $OPENSSL_BIN base64 -e
  341. else
  342. $OPENSSL_BIN base64 -e | tr -d '\r\n'
  343. fi
  344. }
  345. #Usage: multiline
  346. _dbase64() {
  347. if [ "$1" ]; then
  348. $OPENSSL_BIN base64 -d -A
  349. else
  350. $OPENSSL_BIN base64 -d
  351. fi
  352. }
  353. #Usage: hashalg [outputhex]
  354. #Output Base64-encoded digest
  355. _digest() {
  356. alg="$1"
  357. if [ -z "$alg" ]; then
  358. _usage "Usage: _digest hashalg"
  359. return 1
  360. fi
  361. outputhex="$2"
  362. if [ "$alg" = "sha256" ] || [ "$alg" = "sha1" ] || [ "$alg" = "md5" ]; then
  363. if [ "$outputhex" ]; then
  364. $OPENSSL_BIN dgst -"$alg" -hex | cut -d = -f 2 | tr -d ' '
  365. else
  366. $OPENSSL_BIN dgst -"$alg" -binary | _base64
  367. fi
  368. else
  369. _err "$alg is not supported yet"
  370. return 1
  371. fi
  372. }
  373. #Usage: hashalg secret_hex [outputhex]
  374. #Output binary hmac
  375. _hmac() {
  376. alg="$1"
  377. secret_hex="$2"
  378. outputhex="$3"
  379. if [ -z "$secret_hex" ]; then
  380. _usage "Usage: _hmac hashalg secret [outputhex]"
  381. return 1
  382. fi
  383. if [ "$alg" = "sha256" ] || [ "$alg" = "sha1" ]; then
  384. if [ "$outputhex" ]; then
  385. $OPENSSL_BIN dgst -"$alg" -mac HMAC -macopt "hexkey:$secret_hex" | cut -d = -f 2 | tr -d ' '
  386. else
  387. $OPENSSL_BIN dgst -"$alg" -mac HMAC -macopt "hexkey:$secret_hex" -binary
  388. fi
  389. else
  390. _err "$alg is not supported yet"
  391. return 1
  392. fi
  393. }
  394. #Usage: keyfile hashalg
  395. #Output: Base64-encoded signature value
  396. _sign() {
  397. keyfile="$1"
  398. alg="$2"
  399. if [ -z "$alg" ]; then
  400. _usage "Usage: _sign keyfile hashalg"
  401. return 1
  402. fi
  403. _sign_openssl="$OPENSSL_BIN dgst -sign $keyfile "
  404. if [ "$alg" = "sha256" ]; then
  405. _sign_openssl="$_sign_openssl -$alg"
  406. else
  407. _err "$alg is not supported yet"
  408. return 1
  409. fi
  410. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  411. $_sign_openssl | _base64
  412. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  413. if ! _signedECText="$($_sign_openssl | $OPENSSL_BIN asn1parse -inform DER)"; then
  414. _err "Sign failed: $_sign_openssl"
  415. _err "Key file: $keyfile"
  416. _err "Key content:$(wc -l <"$keyfile") lises"
  417. return 1
  418. fi
  419. _debug3 "_signedECText" "$_signedECText"
  420. _ec_r="$(echo "$_signedECText" | _head_n 2 | _tail_n 1 | cut -d : -f 4 | tr -d "\r\n")"
  421. _debug3 "_ec_r" "$_ec_r"
  422. _ec_s="$(echo "$_signedECText" | _head_n 3 | _tail_n 1 | cut -d : -f 4 | tr -d "\r\n")"
  423. _debug3 "_ec_s" "$_ec_s"
  424. printf "%s" "$_ec_r$_ec_s" | _h2b | _base64
  425. else
  426. _err "Unknown key file format."
  427. return 1
  428. fi
  429. }
  430. #keylength
  431. _isEccKey() {
  432. _length="$1"
  433. if [ -z "$_length" ]; then
  434. return 1
  435. fi
  436. [ "$_length" != "1024" ] \
  437. && [ "$_length" != "2048" ] \
  438. && [ "$_length" != "3072" ] \
  439. && [ "$_length" != "4096" ] \
  440. && [ "$_length" != "8192" ]
  441. }
  442. # _createkey 2048|ec-256 file
  443. _createkey() {
  444. length="$1"
  445. f="$2"
  446. eccname="$length"
  447. if _startswith "$length" "ec-"; then
  448. length=$(printf "%s" "$length" | cut -d '-' -f 2-100)
  449. if [ "$length" = "256" ]; then
  450. eccname="prime256v1"
  451. fi
  452. if [ "$length" = "384" ]; then
  453. eccname="secp384r1"
  454. fi
  455. if [ "$length" = "521" ]; then
  456. eccname="secp521r1"
  457. fi
  458. fi
  459. if [ -z "$length" ]; then
  460. length=2048
  461. fi
  462. _debug "Use length $length"
  463. if _isEccKey "$length"; then
  464. _debug "Using ec name: $eccname"
  465. $OPENSSL_BIN ecparam -name "$eccname" -genkey 2>/dev/null >"$f"
  466. else
  467. _debug "Using RSA: $length"
  468. $OPENSSL_BIN genrsa "$length" 2>/dev/null >"$f"
  469. fi
  470. if [ "$?" != "0" ]; then
  471. _err "Create key error."
  472. return 1
  473. fi
  474. }
  475. #domain
  476. _is_idn() {
  477. _is_idn_d="$1"
  478. _debug2 _is_idn_d "$_is_idn_d"
  479. _idn_temp=$(printf "%s" "$_is_idn_d" | tr -d '[0-9]' | tr -d '[a-z]' | tr -d '[A-Z]' | tr -d '.,-')
  480. _debug2 _idn_temp "$_idn_temp"
  481. [ "$_idn_temp" ]
  482. }
  483. #aa.com
  484. #aa.com,bb.com,cc.com
  485. _idn() {
  486. __idn_d="$1"
  487. if ! _is_idn "$__idn_d"; then
  488. printf "%s" "$__idn_d"
  489. return 0
  490. fi
  491. if _exists idn; then
  492. if _contains "$__idn_d" ','; then
  493. _i_first="1"
  494. for f in $(echo "$__idn_d" | tr ',' ' '); do
  495. [ -z "$f" ] && continue
  496. if [ -z "$_i_first" ]; then
  497. printf "%s" ","
  498. else
  499. _i_first=""
  500. fi
  501. idn --quiet "$f" | tr -d "\r\n"
  502. done
  503. else
  504. idn "$__idn_d" | tr -d "\r\n"
  505. fi
  506. else
  507. _err "Please install idn to process IDN names."
  508. fi
  509. }
  510. #_createcsr cn san_list keyfile csrfile conf
  511. _createcsr() {
  512. _debug _createcsr
  513. domain="$1"
  514. domainlist="$2"
  515. csrkey="$3"
  516. csr="$4"
  517. csrconf="$5"
  518. _debug2 domain "$domain"
  519. _debug2 domainlist "$domainlist"
  520. _debug2 csrkey "$csrkey"
  521. _debug2 csr "$csr"
  522. _debug2 csrconf "$csrconf"
  523. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\nreq_extensions = v3_req\n[ v3_req ]\n\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment" >"$csrconf"
  524. if [ -z "$domainlist" ] || [ "$domainlist" = "$NO_VALUE" ]; then
  525. #single domain
  526. _info "Single domain" "$domain"
  527. else
  528. domainlist="$(_idn "$domainlist")"
  529. _debug2 domainlist "$domainlist"
  530. if _contains "$domainlist" ","; then
  531. alt="DNS:$(echo "$domainlist" | sed "s/,/,DNS:/g")"
  532. else
  533. alt="DNS:$domainlist"
  534. fi
  535. #multi
  536. _info "Multi domain" "$alt"
  537. printf -- "\nsubjectAltName=$alt" >>"$csrconf"
  538. fi
  539. if [ "$Le_OCSP_Stable" ]; then
  540. _savedomainconf Le_OCSP_Stable "$Le_OCSP_Stable"
  541. printf -- "\nbasicConstraints = CA:FALSE\n1.3.6.1.5.5.7.1.24=DER:30:03:02:01:05" >>"$csrconf"
  542. fi
  543. _csr_cn="$(_idn "$domain")"
  544. _debug2 _csr_cn "$_csr_cn"
  545. $OPENSSL_BIN req -new -sha256 -key "$csrkey" -subj "/CN=$_csr_cn" -config "$csrconf" -out "$csr"
  546. }
  547. #_signcsr key csr conf cert
  548. _signcsr() {
  549. key="$1"
  550. csr="$2"
  551. conf="$3"
  552. cert="$4"
  553. _debug "_signcsr"
  554. _msg="$($OPENSSL_BIN x509 -req -days 365 -in "$csr" -signkey "$key" -extensions v3_req -extfile "$conf" -out "$cert" 2>&1)"
  555. _ret="$?"
  556. _debug "$_msg"
  557. return $_ret
  558. }
  559. #_csrfile
  560. _readSubjectFromCSR() {
  561. _csrfile="$1"
  562. if [ -z "$_csrfile" ]; then
  563. _usage "_readSubjectFromCSR mycsr.csr"
  564. return 1
  565. fi
  566. $OPENSSL_BIN req -noout -in "$_csrfile" -subject | _egrep_o "CN=.*" | cut -d = -f 2 | cut -d / -f 1 | tr -d '\n'
  567. }
  568. #_csrfile
  569. #echo comma separated domain list
  570. _readSubjectAltNamesFromCSR() {
  571. _csrfile="$1"
  572. if [ -z "$_csrfile" ]; then
  573. _usage "_readSubjectAltNamesFromCSR mycsr.csr"
  574. return 1
  575. fi
  576. _csrsubj="$(_readSubjectFromCSR "$_csrfile")"
  577. _debug _csrsubj "$_csrsubj"
  578. _dnsAltnames="$($OPENSSL_BIN req -noout -text -in "$_csrfile" | grep "^ *DNS:.*" | tr -d ' \n')"
  579. _debug _dnsAltnames "$_dnsAltnames"
  580. if _contains "$_dnsAltnames," "DNS:$_csrsubj,"; then
  581. _debug "AltNames contains subject"
  582. _dnsAltnames="$(printf "%s" "$_dnsAltnames," | sed "s/DNS:$_csrsubj,//g")"
  583. else
  584. _debug "AltNames doesn't contain subject"
  585. fi
  586. printf "%s" "$_dnsAltnames" | sed "s/DNS://g"
  587. }
  588. #_csrfile
  589. _readKeyLengthFromCSR() {
  590. _csrfile="$1"
  591. if [ -z "$_csrfile" ]; then
  592. _usage "_readKeyLengthFromCSR mycsr.csr"
  593. return 1
  594. fi
  595. _outcsr="$($OPENSSL_BIN req -noout -text -in "$_csrfile")"
  596. if _contains "$_outcsr" "Public Key Algorithm: id-ecPublicKey"; then
  597. _debug "ECC CSR"
  598. echo "$_outcsr" | _egrep_o "^ *ASN1 OID:.*" | cut -d ':' -f 2 | tr -d ' '
  599. else
  600. _debug "RSA CSR"
  601. echo "$_outcsr" | _egrep_o "^ *Public-Key:.*" | cut -d '(' -f 2 | cut -d ' ' -f 1
  602. fi
  603. }
  604. _ss() {
  605. _port="$1"
  606. if _exists "ss"; then
  607. _debug "Using: ss"
  608. ss -ntpl | grep ":$_port "
  609. return 0
  610. fi
  611. if _exists "netstat"; then
  612. _debug "Using: netstat"
  613. if netstat -h 2>&1 | grep "\-p proto" >/dev/null; then
  614. #for windows version netstat tool
  615. netstat -an -p tcp | grep "LISTENING" | grep ":$_port "
  616. else
  617. if netstat -help 2>&1 | grep "\-p protocol" >/dev/null; then
  618. netstat -an -p tcp | grep LISTEN | grep ":$_port "
  619. elif netstat -help 2>&1 | grep -- '-P protocol' >/dev/null; then
  620. #for solaris
  621. netstat -an -P tcp | grep "\.$_port " | grep "LISTEN"
  622. else
  623. netstat -ntpl | grep ":$_port "
  624. fi
  625. fi
  626. return 0
  627. fi
  628. return 1
  629. }
  630. #domain [password] [isEcc]
  631. toPkcs() {
  632. domain="$1"
  633. pfxPassword="$2"
  634. if [ -z "$domain" ]; then
  635. _usage "Usage: $PROJECT_ENTRY --toPkcs -d domain [--password pfx-password]"
  636. return 1
  637. fi
  638. _isEcc="$3"
  639. _initpath "$domain" "$_isEcc"
  640. if [ "$pfxPassword" ]; then
  641. $OPENSSL_BIN pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH" -password "pass:$pfxPassword"
  642. else
  643. $OPENSSL_BIN pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH"
  644. fi
  645. if [ "$?" = "0" ]; then
  646. _info "Success, Pfx is exported to: $CERT_PFX_PATH"
  647. fi
  648. }
  649. #[2048]
  650. createAccountKey() {
  651. _info "Creating account key"
  652. if [ -z "$1" ]; then
  653. _usage "Usage: $PROJECT_ENTRY --createAccountKey --accountkeylength 2048"
  654. return
  655. fi
  656. length=$1
  657. _create_account_key "$length"
  658. }
  659. _create_account_key() {
  660. length=$1
  661. if [ -z "$length" ] || [ "$length" = "$NO_VALUE" ]; then
  662. _debug "Use default length $DEFAULT_ACCOUNT_KEY_LENGTH"
  663. length="$DEFAULT_ACCOUNT_KEY_LENGTH"
  664. fi
  665. _debug length "$length"
  666. _initpath
  667. mkdir -p "$CA_DIR"
  668. if [ -f "$ACCOUNT_KEY_PATH" ]; then
  669. _info "Account key exists, skip"
  670. return
  671. else
  672. #generate account key
  673. _createkey "$length" "$ACCOUNT_KEY_PATH"
  674. fi
  675. }
  676. #domain [length]
  677. createDomainKey() {
  678. _info "Creating domain key"
  679. if [ -z "$1" ]; then
  680. _usage "Usage: $PROJECT_ENTRY --createDomainKey -d domain.com [ --keylength 2048 ]"
  681. return
  682. fi
  683. domain=$1
  684. length=$2
  685. if [ -z "$length" ]; then
  686. _debug "Use DEFAULT_DOMAIN_KEY_LENGTH=$DEFAULT_DOMAIN_KEY_LENGTH"
  687. length="$DEFAULT_DOMAIN_KEY_LENGTH"
  688. fi
  689. _initpath "$domain" "$length"
  690. if [ ! -f "$CERT_KEY_PATH" ] || ([ "$FORCE" ] && ! [ "$IS_RENEW" ]); then
  691. _createkey "$length" "$CERT_KEY_PATH"
  692. else
  693. if [ "$IS_RENEW" ]; then
  694. _info "Domain key exists, skip"
  695. return 0
  696. else
  697. _err "Domain key exists, do you want to overwrite the key?"
  698. _err "Add '--force', and try again."
  699. return 1
  700. fi
  701. fi
  702. }
  703. # domain domainlist isEcc
  704. createCSR() {
  705. _info "Creating csr"
  706. if [ -z "$1" ]; then
  707. _usage "Usage: $PROJECT_ENTRY --createCSR -d domain1.com [-d domain2.com -d domain3.com ... ]"
  708. return
  709. fi
  710. domain="$1"
  711. domainlist="$2"
  712. _isEcc="$3"
  713. _initpath "$domain" "$_isEcc"
  714. if [ -f "$CSR_PATH" ] && [ "$IS_RENEW" ] && [ -z "$FORCE" ]; then
  715. _info "CSR exists, skip"
  716. return
  717. fi
  718. if [ ! -f "$CERT_KEY_PATH" ]; then
  719. _err "The key file is not found: $CERT_KEY_PATH"
  720. _err "Please create the key file first."
  721. return 1
  722. fi
  723. _createcsr "$domain" "$domainlist" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"
  724. }
  725. _urlencode() {
  726. tr '/+' '_-' | tr -d '= '
  727. }
  728. _time2str() {
  729. #BSD
  730. if date -u -d@"$1" 2>/dev/null; then
  731. return
  732. fi
  733. #Linux
  734. if date -u -r "$1" 2>/dev/null; then
  735. return
  736. fi
  737. #Soaris
  738. if _exists adb; then
  739. _t_s_a=$(echo "0t${1}=Y" | adb)
  740. echo "$_t_s_a"
  741. fi
  742. }
  743. _normalizeJson() {
  744. sed "s/\" *: *\([\"{\[]\)/\":\1/g" | sed "s/^ *\([^ ]\)/\1/" | tr -d "\r\n"
  745. }
  746. _stat() {
  747. #Linux
  748. if stat -c '%U:%G' "$1" 2>/dev/null; then
  749. return
  750. fi
  751. #BSD
  752. if stat -f '%Su:%Sg' "$1" 2>/dev/null; then
  753. return
  754. fi
  755. return 1 #error, 'stat' not found
  756. }
  757. #keyfile
  758. _calcjwk() {
  759. keyfile="$1"
  760. if [ -z "$keyfile" ]; then
  761. _usage "Usage: _calcjwk keyfile"
  762. return 1
  763. fi
  764. if [ "$JWK_HEADER" ] && [ "$__CACHED_JWK_KEY_FILE" = "$keyfile" ]; then
  765. _debug2 "Use cached jwk for file: $__CACHED_JWK_KEY_FILE"
  766. return 0
  767. fi
  768. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  769. _debug "RSA key"
  770. pub_exp=$($OPENSSL_BIN rsa -in "$keyfile" -noout -text | grep "^publicExponent:" | cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
  771. if [ "${#pub_exp}" = "5" ]; then
  772. pub_exp=0$pub_exp
  773. fi
  774. _debug3 pub_exp "$pub_exp"
  775. e=$(echo "$pub_exp" | _h2b | _base64)
  776. _debug3 e "$e"
  777. modulus=$($OPENSSL_BIN rsa -in "$keyfile" -modulus -noout | cut -d '=' -f 2)
  778. _debug3 modulus "$modulus"
  779. n="$(printf "%s" "$modulus" | _h2b | _base64 | _urlencode)"
  780. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  781. _debug3 jwk "$jwk"
  782. JWK_HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  783. JWK_HEADERPLACE_PART1='{"nonce": "'
  784. JWK_HEADERPLACE_PART2='", "alg": "RS256", "jwk": '$jwk'}'
  785. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  786. _debug "EC key"
  787. crv="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
  788. _debug3 crv "$crv"
  789. if [ -z "$crv" ]; then
  790. _debug "Let's try ASN1 OID"
  791. crv_oid="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | grep "^ASN1 OID:" | cut -d ":" -f 2 | tr -d " \r\n")"
  792. _debug3 crv_oid "$crv_oid"
  793. case "${crv_oid}" in
  794. "prime256v1")
  795. crv="P-256"
  796. ;;
  797. "secp384r1")
  798. crv="P-384"
  799. ;;
  800. "secp521r1")
  801. crv="P-521"
  802. ;;
  803. *)
  804. _err "ECC oid : $crv_oid"
  805. return 1
  806. ;;
  807. esac
  808. _debug3 crv "$crv"
  809. fi
  810. pubi="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
  811. pubi=$(_math "$pubi" + 1)
  812. _debug3 pubi "$pubi"
  813. pubj="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
  814. pubj=$(_math "$pubj" - 1)
  815. _debug3 pubj "$pubj"
  816. pubtext="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
  817. _debug3 pubtext "$pubtext"
  818. xlen="$(printf "%s" "$pubtext" | tr -d ':' | wc -c)"
  819. xlen=$(_math "$xlen" / 4)
  820. _debug3 xlen "$xlen"
  821. xend=$(_math "$xlen" + 1)
  822. x="$(printf "%s" "$pubtext" | cut -d : -f 2-"$xend")"
  823. _debug3 x "$x"
  824. x64="$(printf "%s" "$x" | tr -d : | _h2b | _base64 | _urlencode)"
  825. _debug3 x64 "$x64"
  826. xend=$(_math "$xend" + 1)
  827. y="$(printf "%s" "$pubtext" | cut -d : -f "$xend"-10000)"
  828. _debug3 y "$y"
  829. y64="$(printf "%s" "$y" | tr -d : | _h2b | _base64 | _urlencode)"
  830. _debug3 y64 "$y64"
  831. jwk='{"crv": "'$crv'", "kty": "EC", "x": "'$x64'", "y": "'$y64'"}'
  832. _debug3 jwk "$jwk"
  833. JWK_HEADER='{"alg": "ES256", "jwk": '$jwk'}'
  834. JWK_HEADERPLACE_PART1='{"nonce": "'
  835. JWK_HEADERPLACE_PART2='", "alg": "ES256", "jwk": '$jwk'}'
  836. else
  837. _err "Only RSA or EC key is supported."
  838. return 1
  839. fi
  840. _debug3 JWK_HEADER "$JWK_HEADER"
  841. __CACHED_JWK_KEY_FILE="$keyfile"
  842. }
  843. _time() {
  844. date -u "+%s"
  845. }
  846. _mktemp() {
  847. if _exists mktemp; then
  848. if mktemp 2>/dev/null; then
  849. return 0
  850. elif _contains "$(mktemp 2>&1)" "-t prefix" && mktemp -t "$PROJECT_NAME" 2>/dev/null; then
  851. #for Mac osx
  852. return 0
  853. fi
  854. fi
  855. if [ -d "/tmp" ]; then
  856. echo "/tmp/${PROJECT_NAME}wefADf24sf.$(_time).tmp"
  857. return 0
  858. elif [ "$LE_TEMP_DIR" ] && mkdir -p "$LE_TEMP_DIR"; then
  859. echo "/$LE_TEMP_DIR/wefADf24sf.$(_time).tmp"
  860. return 0
  861. fi
  862. _err "Can not create temp file."
  863. }
  864. _inithttp() {
  865. if [ -z "$HTTP_HEADER" ] || ! touch "$HTTP_HEADER"; then
  866. HTTP_HEADER="$(_mktemp)"
  867. _debug2 HTTP_HEADER "$HTTP_HEADER"
  868. fi
  869. if [ "$__HTTP_INITIALIZED" ]; then
  870. if [ "$_ACME_CURL$_ACME_WGET" ]; then
  871. _debug2 "Http already initialized."
  872. return 0
  873. fi
  874. fi
  875. if [ -z "$_ACME_CURL" ] && _exists "curl"; then
  876. _ACME_CURL="curl -L --silent --dump-header $HTTP_HEADER "
  877. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  878. _CURL_DUMP="$(_mktemp)"
  879. _ACME_CURL="$_ACME_CURL --trace-ascii $_CURL_DUMP "
  880. fi
  881. if [ "$CA_BUNDLE" ]; then
  882. _ACME_CURL="$_ACME_CURL --cacert $CA_BUNDLE "
  883. fi
  884. fi
  885. if [ -z "$_ACME_WGET" ] && _exists "wget"; then
  886. _ACME_WGET="wget -q"
  887. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  888. _ACME_WGET="$_ACME_WGET -d "
  889. fi
  890. if [ "$CA_BUNDLE" ]; then
  891. _ACME_WGET="$_ACME_WGET --ca-certificate $CA_BUNDLE "
  892. fi
  893. fi
  894. __HTTP_INITIALIZED=1
  895. }
  896. # body url [needbase64] [POST|PUT]
  897. _post() {
  898. body="$1"
  899. url="$2"
  900. needbase64="$3"
  901. httpmethod="$4"
  902. if [ -z "$httpmethod" ]; then
  903. httpmethod="POST"
  904. fi
  905. _debug $httpmethod
  906. _debug "url" "$url"
  907. _debug2 "body" "$body"
  908. _inithttp
  909. if [ "$_ACME_CURL" ]; then
  910. _CURL="$_ACME_CURL"
  911. if [ "$HTTPS_INSECURE" ]; then
  912. _CURL="$_CURL --insecure "
  913. fi
  914. _debug "_CURL" "$_CURL"
  915. if [ "$needbase64" ]; then
  916. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$url" | _base64)"
  917. else
  918. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$url")"
  919. fi
  920. _ret="$?"
  921. if [ "$_ret" != "0" ]; then
  922. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $_ret"
  923. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  924. _err "Here is the curl dump log:"
  925. _err "$(cat "$_CURL_DUMP")"
  926. fi
  927. fi
  928. elif [ "$_ACME_WGET" ]; then
  929. _WGET="$_ACME_WGET"
  930. if [ "$HTTPS_INSECURE" ]; then
  931. _WGET="$_WGET --no-check-certificate "
  932. fi
  933. _debug "_WGET" "$_WGET"
  934. if [ "$needbase64" ]; then
  935. if [ "$httpmethod" = "POST" ]; then
  936. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$url" 2>"$HTTP_HEADER" | _base64)"
  937. else
  938. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$url" 2>"$HTTP_HEADER" | _base64)"
  939. fi
  940. else
  941. if [ "$httpmethod" = "POST" ]; then
  942. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$url" 2>"$HTTP_HEADER")"
  943. else
  944. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$url" 2>"$HTTP_HEADER")"
  945. fi
  946. fi
  947. _ret="$?"
  948. if [ "$_ret" = "8" ]; then
  949. _ret=0
  950. _debug "wget returns 8, the server returns a 'Bad request' respons, lets process the response later."
  951. fi
  952. if [ "$_ret" != "0" ]; then
  953. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $_ret"
  954. fi
  955. _sed_i "s/^ *//g" "$HTTP_HEADER"
  956. else
  957. _ret="$?"
  958. _err "Neither curl nor wget is found, can not do $httpmethod."
  959. fi
  960. _debug "_ret" "$_ret"
  961. printf "%s" "$response"
  962. return $_ret
  963. }
  964. # url getheader timeout
  965. _get() {
  966. _debug GET
  967. url="$1"
  968. onlyheader="$2"
  969. t="$3"
  970. _debug url "$url"
  971. _debug "timeout" "$t"
  972. _inithttp
  973. if [ "$_ACME_CURL" ]; then
  974. _CURL="$_ACME_CURL"
  975. if [ "$HTTPS_INSECURE" ]; then
  976. _CURL="$_CURL --insecure "
  977. fi
  978. if [ "$t" ]; then
  979. _CURL="$_CURL --connect-timeout $t"
  980. fi
  981. _debug "_CURL" "$_CURL"
  982. if [ "$onlyheader" ]; then
  983. $_CURL -I --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$url"
  984. else
  985. $_CURL --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$url"
  986. fi
  987. ret=$?
  988. if [ "$ret" != "0" ]; then
  989. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $ret"
  990. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  991. _err "Here is the curl dump log:"
  992. _err "$(cat "$_CURL_DUMP")"
  993. fi
  994. fi
  995. elif [ "$_ACME_WGET" ]; then
  996. _WGET="$_ACME_WGET"
  997. if [ "$HTTPS_INSECURE" ]; then
  998. _WGET="$_WGET --no-check-certificate "
  999. fi
  1000. if [ "$t" ]; then
  1001. _WGET="$_WGET --timeout=$t"
  1002. fi
  1003. _debug "_WGET" "$_WGET"
  1004. if [ "$onlyheader" ]; then
  1005. $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -S -O /dev/null "$url" 2>&1 | sed 's/^[ ]*//g'
  1006. else
  1007. $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -O - "$url"
  1008. fi
  1009. ret=$?
  1010. if [ "$_ret" = "8" ]; then
  1011. _ret=0
  1012. _debug "wget returns 8, the server returns a 'Bad request' respons, lets process the response later."
  1013. fi
  1014. if [ "$ret" != "0" ]; then
  1015. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $ret"
  1016. fi
  1017. else
  1018. ret=$?
  1019. _err "Neither curl nor wget is found, can not do GET."
  1020. fi
  1021. _debug "ret" "$ret"
  1022. return $ret
  1023. }
  1024. _head_n() {
  1025. head -n "$1"
  1026. }
  1027. _tail_n() {
  1028. if ! tail -n "$1" 2>/dev/null; then
  1029. #fix for solaris
  1030. tail -"$1"
  1031. fi
  1032. }
  1033. # url payload needbase64 keyfile
  1034. _send_signed_request() {
  1035. url=$1
  1036. payload=$2
  1037. needbase64=$3
  1038. keyfile=$4
  1039. if [ -z "$keyfile" ]; then
  1040. keyfile="$ACCOUNT_KEY_PATH"
  1041. fi
  1042. _debug url "$url"
  1043. _debug payload "$payload"
  1044. if ! _calcjwk "$keyfile"; then
  1045. return 1
  1046. fi
  1047. payload64=$(printf "%s" "$payload" | _base64 | _urlencode)
  1048. _debug3 payload64 "$payload64"
  1049. if [ -z "$_CACHED_NONCE" ]; then
  1050. _debug2 "Get nonce."
  1051. nonceurl="$API/directory"
  1052. _headers="$(_get "$nonceurl" "onlyheader")"
  1053. if [ "$?" != "0" ]; then
  1054. _err "Can not connect to $nonceurl to get nonce."
  1055. return 1
  1056. fi
  1057. _debug2 _headers "$_headers"
  1058. _CACHED_NONCE="$(echo "$_headers" | grep "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1059. _debug2 _CACHED_NONCE "$_CACHED_NONCE"
  1060. else
  1061. _debug2 "Use _CACHED_NONCE" "$_CACHED_NONCE"
  1062. fi
  1063. nonce="$_CACHED_NONCE"
  1064. _debug2 nonce "$nonce"
  1065. protected="$JWK_HEADERPLACE_PART1$nonce$JWK_HEADERPLACE_PART2"
  1066. _debug3 protected "$protected"
  1067. protected64="$(printf "%s" "$protected" | _base64 | _urlencode)"
  1068. _debug3 protected64 "$protected64"
  1069. if ! _sig_t="$(printf "%s" "$protected64.$payload64" | _sign "$keyfile" "sha256")"; then
  1070. _err "Sign request failed."
  1071. return 1
  1072. fi
  1073. _debug3 _sig_t "$_sig_t"
  1074. sig="$(printf "%s" "$_sig_t" | _urlencode)"
  1075. _debug3 sig "$sig"
  1076. body="{\"header\": $JWK_HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  1077. _debug3 body "$body"
  1078. response="$(_post "$body" "$url" "$needbase64")"
  1079. _CACHED_NONCE=""
  1080. if [ "$?" != "0" ]; then
  1081. _err "Can not post to $url"
  1082. return 1
  1083. fi
  1084. _debug2 original "$response"
  1085. response="$(echo "$response" | _normalizeJson)"
  1086. responseHeaders="$(cat "$HTTP_HEADER")"
  1087. _debug2 responseHeaders "$responseHeaders"
  1088. _debug2 response "$response"
  1089. code="$(grep "^HTTP" "$HTTP_HEADER" | _tail_n 1 | cut -d " " -f 2 | tr -d "\r\n")"
  1090. _debug code "$code"
  1091. _CACHED_NONCE="$(echo "$responseHeaders" | grep "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1092. }
  1093. #setopt "file" "opt" "=" "value" [";"]
  1094. _setopt() {
  1095. __conf="$1"
  1096. __opt="$2"
  1097. __sep="$3"
  1098. __val="$4"
  1099. __end="$5"
  1100. if [ -z "$__opt" ]; then
  1101. _usage usage: _setopt '"file" "opt" "=" "value" [";"]'
  1102. return
  1103. fi
  1104. if [ ! -f "$__conf" ]; then
  1105. touch "$__conf"
  1106. fi
  1107. if grep -n "^$__opt$__sep" "$__conf" >/dev/null; then
  1108. _debug3 OK
  1109. if _contains "$__val" "&"; then
  1110. __val="$(echo "$__val" | sed 's/&/\\&/g')"
  1111. fi
  1112. text="$(cat "$__conf")"
  1113. echo "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
  1114. elif grep -n "^#$__opt$__sep" "$__conf" >/dev/null; then
  1115. if _contains "$__val" "&"; then
  1116. __val="$(echo "$__val" | sed 's/&/\\&/g')"
  1117. fi
  1118. text="$(cat "$__conf")"
  1119. echo "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
  1120. else
  1121. _debug3 APP
  1122. echo "$__opt$__sep$__val$__end" >>"$__conf"
  1123. fi
  1124. _debug2 "$(grep -n "^$__opt$__sep" "$__conf")"
  1125. }
  1126. #_save_conf file key value
  1127. #save to conf
  1128. _save_conf() {
  1129. _s_c_f="$1"
  1130. _sdkey="$2"
  1131. _sdvalue="$3"
  1132. if [ "$_s_c_f" ]; then
  1133. _setopt "$_s_c_f" "$_sdkey" "=" "'$_sdvalue'"
  1134. else
  1135. _err "config file is empty, can not save $_sdkey=$_sdvalue"
  1136. fi
  1137. }
  1138. #_clear_conf file key
  1139. _clear_conf() {
  1140. _c_c_f="$1"
  1141. _sdkey="$2"
  1142. if [ "$_c_c_f" ]; then
  1143. _conf_data="$(cat "$_c_c_f")"
  1144. echo "$_conf_data" | sed "s/^$_sdkey *=.*$//" >"$_c_c_f"
  1145. else
  1146. _err "config file is empty, can not clear"
  1147. fi
  1148. }
  1149. #_read_conf file key
  1150. _read_conf() {
  1151. _r_c_f="$1"
  1152. _sdkey="$2"
  1153. if [ -f "$_r_c_f" ]; then
  1154. (
  1155. eval "$(grep "^$_sdkey *=" "$_r_c_f")"
  1156. eval "printf \"%s\" \"\$$_sdkey\""
  1157. )
  1158. else
  1159. _debug "config file is empty, can not read $_sdkey"
  1160. fi
  1161. }
  1162. #_savedomainconf key value
  1163. #save to domain.conf
  1164. _savedomainconf() {
  1165. _save_conf "$DOMAIN_CONF" "$1" "$2"
  1166. }
  1167. #_cleardomainconf key
  1168. _cleardomainconf() {
  1169. _clear_conf "$DOMAIN_CONF" "$1"
  1170. }
  1171. #_readdomainconf key
  1172. _readdomainconf() {
  1173. _read_conf "$DOMAIN_CONF" "$1"
  1174. }
  1175. #_saveaccountconf key value
  1176. _saveaccountconf() {
  1177. _save_conf "$ACCOUNT_CONF_PATH" "$1" "$2"
  1178. }
  1179. #_clearaccountconf key
  1180. _clearaccountconf() {
  1181. _clear_conf "$ACCOUNT_CONF_PATH" "$1"
  1182. }
  1183. #_savecaconf key value
  1184. _savecaconf() {
  1185. _save_conf "$CA_CONF" "$1" "$2"
  1186. }
  1187. #_readcaconf key
  1188. _readcaconf() {
  1189. _read_conf "$CA_CONF" "$1"
  1190. }
  1191. #_clearaccountconf key
  1192. _clearcaconf() {
  1193. _clear_conf "$CA_CONF" "$1"
  1194. }
  1195. # content localaddress
  1196. _startserver() {
  1197. content="$1"
  1198. ncaddr="$2"
  1199. _debug "ncaddr" "$ncaddr"
  1200. _debug "startserver: $$"
  1201. nchelp="$(nc -h 2>&1)"
  1202. _debug Le_HTTPPort "$Le_HTTPPort"
  1203. _debug Le_Listen_V4 "$Le_Listen_V4"
  1204. _debug Le_Listen_V6 "$Le_Listen_V6"
  1205. _NC="nc"
  1206. if [ "$Le_Listen_V4" ]; then
  1207. _NC="$_NC -4"
  1208. elif [ "$Le_Listen_V6" ]; then
  1209. _NC="$_NC -6"
  1210. fi
  1211. if echo "$nchelp" | grep "\-q[ ,]" >/dev/null; then
  1212. _NC="$_NC -q 1 -l $ncaddr"
  1213. else
  1214. if echo "$nchelp" | grep "GNU netcat" >/dev/null && echo "$nchelp" | grep "\-c, \-\-close" >/dev/null; then
  1215. _NC="$_NC -c -l $ncaddr"
  1216. elif echo "$nchelp" | grep "\-N" | grep "Shutdown the network socket after EOF on stdin" >/dev/null; then
  1217. _NC="$_NC -N -l $ncaddr"
  1218. else
  1219. _NC="$_NC -l $ncaddr"
  1220. fi
  1221. fi
  1222. _debug "_NC" "$_NC"
  1223. #for centos ncat
  1224. if _contains "$nchelp" "nmap.org"; then
  1225. _debug "Using ncat: nmap.org"
  1226. if ! _exec "printf \"%s\r\n\r\n%s\" \"HTTP/1.1 200 OK\" \"$content\" | $_NC \"$Le_HTTPPort\" >&2"; then
  1227. _exec_err
  1228. return 1
  1229. fi
  1230. if [ "$DEBUG" ]; then
  1231. _exec_err
  1232. fi
  1233. return
  1234. fi
  1235. # while true ; do
  1236. if ! _exec "printf \"%s\r\n\r\n%s\" \"HTTP/1.1 200 OK\" \"$content\" | $_NC -p \"$Le_HTTPPort\" >&2"; then
  1237. _exec "printf \"%s\r\n\r\n%s\" \"HTTP/1.1 200 OK\" \"$content\" | $_NC \"$Le_HTTPPort\" >&2"
  1238. fi
  1239. if [ "$?" != "0" ]; then
  1240. _err "nc listen error."
  1241. _exec_err
  1242. exit 1
  1243. fi
  1244. if [ "$DEBUG" ]; then
  1245. _exec_err
  1246. fi
  1247. # done
  1248. }
  1249. _stopserver() {
  1250. pid="$1"
  1251. _debug "pid" "$pid"
  1252. if [ -z "$pid" ]; then
  1253. return
  1254. fi
  1255. _debug2 "Le_HTTPPort" "$Le_HTTPPort"
  1256. if [ "$Le_HTTPPort" ]; then
  1257. if [ "$DEBUG" ] && [ "$DEBUG" -gt "3" ]; then
  1258. _get "http://localhost:$Le_HTTPPort" "" 1
  1259. else
  1260. _get "http://localhost:$Le_HTTPPort" "" 1 >/dev/null 2>&1
  1261. fi
  1262. fi
  1263. _debug2 "Le_TLSPort" "$Le_TLSPort"
  1264. if [ "$Le_TLSPort" ]; then
  1265. if [ "$DEBUG" ] && [ "$DEBUG" -gt "3" ]; then
  1266. _get "https://localhost:$Le_TLSPort" "" 1
  1267. _get "https://localhost:$Le_TLSPort" "" 1
  1268. else
  1269. _get "https://localhost:$Le_TLSPort" "" 1 >/dev/null 2>&1
  1270. _get "https://localhost:$Le_TLSPort" "" 1 >/dev/null 2>&1
  1271. fi
  1272. fi
  1273. }
  1274. # sleep sec
  1275. _sleep() {
  1276. _sleep_sec="$1"
  1277. if [ "$__INTERACTIVE" ]; then
  1278. _sleep_c="$_sleep_sec"
  1279. while [ "$_sleep_c" -ge "0" ]; do
  1280. printf "\r \r"
  1281. __green "$_sleep_c"
  1282. _sleep_c="$(_math "$_sleep_c" - 1)"
  1283. sleep 1
  1284. done
  1285. printf "\r"
  1286. else
  1287. sleep "$_sleep_sec"
  1288. fi
  1289. }
  1290. # _starttlsserver san_a san_b port content _ncaddr
  1291. _starttlsserver() {
  1292. _info "Starting tls server."
  1293. san_a="$1"
  1294. san_b="$2"
  1295. port="$3"
  1296. content="$4"
  1297. opaddr="$5"
  1298. _debug san_a "$san_a"
  1299. _debug san_b "$san_b"
  1300. _debug port "$port"
  1301. #create key TLS_KEY
  1302. if ! _createkey "2048" "$TLS_KEY"; then
  1303. _err "Create tls validation key error."
  1304. return 1
  1305. fi
  1306. #create csr
  1307. alt="$san_a"
  1308. if [ "$san_b" ]; then
  1309. alt="$alt,$san_b"
  1310. fi
  1311. if ! _createcsr "tls.acme.sh" "$alt" "$TLS_KEY" "$TLS_CSR" "$TLS_CONF"; then
  1312. _err "Create tls validation csr error."
  1313. return 1
  1314. fi
  1315. #self signed
  1316. if ! _signcsr "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$TLS_CERT"; then
  1317. _err "Create tls validation cert error."
  1318. return 1
  1319. fi
  1320. __S_OPENSSL="$OPENSSL_BIN s_server -cert $TLS_CERT -key $TLS_KEY "
  1321. if [ "$opaddr" ]; then
  1322. __S_OPENSSL="$__S_OPENSSL -accept $opaddr:$port"
  1323. else
  1324. __S_OPENSSL="$__S_OPENSSL -accept $port"
  1325. fi
  1326. _debug Le_Listen_V4 "$Le_Listen_V4"
  1327. _debug Le_Listen_V6 "$Le_Listen_V6"
  1328. if [ "$Le_Listen_V4" ]; then
  1329. __S_OPENSSL="$__S_OPENSSL -4"
  1330. elif [ "$Le_Listen_V6" ]; then
  1331. __S_OPENSSL="$__S_OPENSSL -6"
  1332. fi
  1333. _debug "$__S_OPENSSL"
  1334. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1335. (printf "%s\r\n\r\n%s" "HTTP/1.1 200 OK" "$content" | $__S_OPENSSL -tlsextdebug) &
  1336. else
  1337. (printf "%s\r\n\r\n%s" "HTTP/1.1 200 OK" "$content" | $__S_OPENSSL >/dev/null 2>&1) &
  1338. fi
  1339. serverproc="$!"
  1340. sleep 1
  1341. _debug serverproc "$serverproc"
  1342. }
  1343. #file
  1344. _readlink() {
  1345. _rf="$1"
  1346. if ! readlink -f "$_rf" 2>/dev/null; then
  1347. if _startswith "$_rf" "\./$PROJECT_ENTRY"; then
  1348. printf -- "%s" "$(pwd)/$PROJECT_ENTRY"
  1349. return 0
  1350. fi
  1351. readlink "$_rf"
  1352. fi
  1353. }
  1354. __initHome() {
  1355. if [ -z "$_SCRIPT_HOME" ]; then
  1356. if _exists readlink && _exists dirname; then
  1357. _debug "Lets find script dir."
  1358. _debug "_SCRIPT_" "$_SCRIPT_"
  1359. _script="$(_readlink "$_SCRIPT_")"
  1360. _debug "_script" "$_script"
  1361. _script_home="$(dirname "$_script")"
  1362. _debug "_script_home" "$_script_home"
  1363. if [ -d "$_script_home" ]; then
  1364. _SCRIPT_HOME="$_script_home"
  1365. else
  1366. _err "It seems the script home is not correct:$_script_home"
  1367. fi
  1368. fi
  1369. fi
  1370. # if [ -z "$LE_WORKING_DIR" ]; then
  1371. # if [ -f "$DEFAULT_INSTALL_HOME/account.conf" ]; then
  1372. # _debug "It seems that $PROJECT_NAME is already installed in $DEFAULT_INSTALL_HOME"
  1373. # LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  1374. # else
  1375. # LE_WORKING_DIR="$_SCRIPT_HOME"
  1376. # fi
  1377. # fi
  1378. if [ -z "$LE_WORKING_DIR" ]; then
  1379. _debug "Using default home:$DEFAULT_INSTALL_HOME"
  1380. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  1381. fi
  1382. export LE_WORKING_DIR
  1383. _DEFAULT_ACCOUNT_CONF_PATH="$LE_WORKING_DIR/account.conf"
  1384. if [ -z "$ACCOUNT_CONF_PATH" ]; then
  1385. if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ]; then
  1386. . "$_DEFAULT_ACCOUNT_CONF_PATH"
  1387. fi
  1388. fi
  1389. if [ -z "$ACCOUNT_CONF_PATH" ]; then
  1390. ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
  1391. fi
  1392. DEFAULT_LOG_FILE="$LE_WORKING_DIR/$PROJECT_NAME.log"
  1393. DEFAULT_CA_HOME="$LE_WORKING_DIR/ca"
  1394. if [ -z "$LE_TEMP_DIR" ]; then
  1395. LE_TEMP_DIR="$LE_WORKING_DIR/tmp"
  1396. fi
  1397. }
  1398. #[domain] [keylength]
  1399. _initpath() {
  1400. __initHome
  1401. if [ -f "$ACCOUNT_CONF_PATH" ]; then
  1402. . "$ACCOUNT_CONF_PATH"
  1403. fi
  1404. if [ "$IN_CRON" ]; then
  1405. if [ ! "$_USER_PATH_EXPORTED" ]; then
  1406. _USER_PATH_EXPORTED=1
  1407. export PATH="$USER_PATH:$PATH"
  1408. fi
  1409. fi
  1410. if [ -z "$CA_HOME" ]; then
  1411. CA_HOME="$DEFAULT_CA_HOME"
  1412. fi
  1413. if [ -z "$API" ]; then
  1414. if [ -z "$STAGE" ]; then
  1415. API="$DEFAULT_CA"
  1416. else
  1417. API="$STAGE_CA"
  1418. _info "Using stage api:$API"
  1419. fi
  1420. fi
  1421. _API_HOST="$(echo "$API" | cut -d : -f 2 | tr -d '/')"
  1422. CA_DIR="$CA_HOME/$_API_HOST"
  1423. _DEFAULT_CA_CONF="$CA_DIR/ca.conf"
  1424. if [ -z "$CA_CONF" ]; then
  1425. CA_CONF="$_DEFAULT_CA_CONF"
  1426. fi
  1427. if [ -f "$CA_CONF" ]; then
  1428. . "$CA_CONF"
  1429. fi
  1430. if [ -z "$ACME_DIR" ]; then
  1431. ACME_DIR="/home/.acme"
  1432. fi
  1433. if [ -z "$APACHE_CONF_BACKUP_DIR" ]; then
  1434. APACHE_CONF_BACKUP_DIR="$LE_WORKING_DIR"
  1435. fi
  1436. if [ -z "$USER_AGENT" ]; then
  1437. USER_AGENT="$DEFAULT_USER_AGENT"
  1438. fi
  1439. if [ -z "$HTTP_HEADER" ]; then
  1440. HTTP_HEADER="$LE_WORKING_DIR/http.header"
  1441. fi
  1442. _OLD_ACCOUNT_KEY="$LE_WORKING_DIR/account.key"
  1443. _OLD_ACCOUNT_JSON="$LE_WORKING_DIR/account.json"
  1444. _DEFAULT_ACCOUNT_KEY_PATH="$CA_DIR/account.key"
  1445. _DEFAULT_ACCOUNT_JSON_PATH="$CA_DIR/account.json"
  1446. if [ -z "$ACCOUNT_KEY_PATH" ]; then
  1447. ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
  1448. fi
  1449. if [ -z "$ACCOUNT_JSON_PATH" ]; then
  1450. ACCOUNT_JSON_PATH="$_DEFAULT_ACCOUNT_JSON_PATH"
  1451. fi
  1452. _DEFAULT_CERT_HOME="$LE_WORKING_DIR"
  1453. if [ -z "$CERT_HOME" ]; then
  1454. CERT_HOME="$_DEFAULT_CERT_HOME"
  1455. fi
  1456. if [ -z "$OPENSSL_BIN" ]; then
  1457. OPENSSL_BIN="$DEFAULT_OPENSSL_BIN"
  1458. fi
  1459. if [ -z "$1" ]; then
  1460. return 0
  1461. fi
  1462. domain="$1"
  1463. _ilength="$2"
  1464. if [ -z "$DOMAIN_PATH" ]; then
  1465. domainhome="$CERT_HOME/$domain"
  1466. domainhomeecc="$CERT_HOME/$domain$ECC_SUFFIX"
  1467. DOMAIN_PATH="$domainhome"
  1468. if _isEccKey "$_ilength"; then
  1469. DOMAIN_PATH="$domainhomeecc"
  1470. else
  1471. if [ ! -d "$domainhome" ] && [ -d "$domainhomeecc" ]; then
  1472. _info "The domain '$domain' seems to have a ECC cert already, please add '$(__red "--ecc")' parameter if you want to use that cert."
  1473. fi
  1474. fi
  1475. _debug DOMAIN_PATH "$DOMAIN_PATH"
  1476. fi
  1477. if [ -z "$DOMAIN_CONF" ]; then
  1478. DOMAIN_CONF="$DOMAIN_PATH/$domain.conf"
  1479. fi
  1480. if [ -z "$DOMAIN_SSL_CONF" ]; then
  1481. DOMAIN_SSL_CONF="$DOMAIN_PATH/$domain.csr.conf"
  1482. fi
  1483. if [ -z "$CSR_PATH" ]; then
  1484. CSR_PATH="$DOMAIN_PATH/$domain.csr"
  1485. fi
  1486. if [ -z "$CERT_KEY_PATH" ]; then
  1487. CERT_KEY_PATH="$DOMAIN_PATH/$domain.key"
  1488. fi
  1489. if [ -z "$CERT_PATH" ]; then
  1490. CERT_PATH="$DOMAIN_PATH/$domain.cer"
  1491. fi
  1492. if [ -z "$CA_CERT_PATH" ]; then
  1493. CA_CERT_PATH="$DOMAIN_PATH/ca.cer"
  1494. fi
  1495. if [ -z "$CERT_FULLCHAIN_PATH" ]; then
  1496. CERT_FULLCHAIN_PATH="$DOMAIN_PATH/fullchain.cer"
  1497. fi
  1498. if [ -z "$CERT_PFX_PATH" ]; then
  1499. CERT_PFX_PATH="$DOMAIN_PATH/$domain.pfx"
  1500. fi
  1501. if [ -z "$TLS_CONF" ]; then
  1502. TLS_CONF="$DOMAIN_PATH/tls.valdation.conf"
  1503. fi
  1504. if [ -z "$TLS_CERT" ]; then
  1505. TLS_CERT="$DOMAIN_PATH/tls.valdation.cert"
  1506. fi
  1507. if [ -z "$TLS_KEY" ]; then
  1508. TLS_KEY="$DOMAIN_PATH/tls.valdation.key"
  1509. fi
  1510. if [ -z "$TLS_CSR" ]; then
  1511. TLS_CSR="$DOMAIN_PATH/tls.valdation.csr"
  1512. fi
  1513. }
  1514. _exec() {
  1515. if [ -z "$_EXEC_TEMP_ERR" ]; then
  1516. _EXEC_TEMP_ERR="$(_mktemp)"
  1517. fi
  1518. if [ "$_EXEC_TEMP_ERR" ]; then
  1519. eval "$@ 2>>$_EXEC_TEMP_ERR"
  1520. else
  1521. eval "$@"
  1522. fi
  1523. }
  1524. _exec_err() {
  1525. [ "$_EXEC_TEMP_ERR" ] && _err "$(cat "$_EXEC_TEMP_ERR")" && echo "" >"$_EXEC_TEMP_ERR"
  1526. }
  1527. _apachePath() {
  1528. _APACHECTL="apachectl"
  1529. if ! _exists apachectl; then
  1530. if _exists apache2ctl; then
  1531. _APACHECTL="apache2ctl"
  1532. else
  1533. _err "'apachectl not found. It seems that apache is not installed, or you are not root user.'"
  1534. _err "Please use webroot mode to try again."
  1535. return 1
  1536. fi
  1537. fi
  1538. if ! _exec $_APACHECTL -V >/dev/null; then
  1539. _exec_err
  1540. return 1
  1541. fi
  1542. if [ "$APACHE_HTTPD_CONF" ]; then
  1543. _saveaccountconf APACHE_HTTPD_CONF "$APACHE_HTTPD_CONF"
  1544. httpdconf="$APACHE_HTTPD_CONF"
  1545. httpdconfname="$(basename "$httpdconfname")"
  1546. else
  1547. httpdconfname="$($_APACHECTL -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"')"
  1548. _debug httpdconfname "$httpdconfname"
  1549. if [ -z "$httpdconfname" ]; then
  1550. _err "Can not read apache config file."
  1551. return 1
  1552. fi
  1553. if _startswith "$httpdconfname" '/'; then
  1554. httpdconf="$httpdconfname"
  1555. httpdconfname="$(basename "$httpdconfname")"
  1556. else
  1557. httpdroot="$($_APACHECTL -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"')"
  1558. _debug httpdroot "$httpdroot"
  1559. httpdconf="$httpdroot/$httpdconfname"
  1560. httpdconfname="$(basename "$httpdconfname")"
  1561. fi
  1562. fi
  1563. _debug httpdconf "$httpdconf"
  1564. _debug httpdconfname "$httpdconfname"
  1565. if [ ! -f "$httpdconf" ]; then
  1566. _err "Apache Config file not found" "$httpdconf"
  1567. return 1
  1568. fi
  1569. return 0
  1570. }
  1571. _restoreApache() {
  1572. if [ -z "$usingApache" ]; then
  1573. return 0
  1574. fi
  1575. _initpath
  1576. if ! _apachePath; then
  1577. return 1
  1578. fi
  1579. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ]; then
  1580. _debug "No config file to restore."
  1581. return 0
  1582. fi
  1583. cat "$APACHE_CONF_BACKUP_DIR/$httpdconfname" >"$httpdconf"
  1584. _debug "Restored: $httpdconf."
  1585. if ! _exec $_APACHECTL -t; then
  1586. _exec_err
  1587. _err "Sorry, restore apache config error, please contact me."
  1588. return 1
  1589. fi
  1590. _debug "Restored successfully."
  1591. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  1592. return 0
  1593. }
  1594. _setApache() {
  1595. _initpath
  1596. if ! _apachePath; then
  1597. return 1
  1598. fi
  1599. #test the conf first
  1600. _info "Checking if there is an error in the apache config file before starting."
  1601. if ! _exec "$_APACHECTL" -t >/dev/null; then
  1602. _exec_err
  1603. _err "The apache config file has error, please fix it first, then try again."
  1604. _err "Don't worry, there is nothing changed to your system."
  1605. return 1
  1606. else
  1607. _info "OK"
  1608. fi
  1609. #backup the conf
  1610. _debug "Backup apache config file" "$httpdconf"
  1611. if ! cp "$httpdconf" "$APACHE_CONF_BACKUP_DIR/"; then
  1612. _err "Can not backup apache config file, so abort. Don't worry, the apache config is not changed."
  1613. _err "This might be a bug of $PROJECT_NAME , pleae report issue: $PROJECT"
  1614. return 1
  1615. fi
  1616. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  1617. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  1618. _info "The backup file will be deleted on sucess, just forget it."
  1619. #add alias
  1620. apacheVer="$($_APACHECTL -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2)"
  1621. _debug "apacheVer" "$apacheVer"
  1622. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  1623. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  1624. if [ "$apacheVer" ] && [ "$apacheMajer$apacheMinor" -ge "24" ]; then
  1625. echo "
  1626. Alias /.well-known/acme-challenge $ACME_DIR
  1627. <Directory $ACME_DIR >
  1628. Require all granted
  1629. </Directory>
  1630. " >>"$httpdconf"
  1631. else
  1632. echo "
  1633. Alias /.well-known/acme-challenge $ACME_DIR
  1634. <Directory $ACME_DIR >
  1635. Order allow,deny
  1636. Allow from all
  1637. </Directory>
  1638. " >>"$httpdconf"
  1639. fi
  1640. _msg="$($_APACHECTL -t 2>&1)"
  1641. if [ "$?" != "0" ]; then
  1642. _err "Sorry, apache config error"
  1643. if _restoreApache; then
  1644. _err "The apache config file is restored."
  1645. else
  1646. _err "Sorry, The apache config file can not be restored, please report bug."
  1647. fi
  1648. return 1
  1649. fi
  1650. if [ ! -d "$ACME_DIR" ]; then
  1651. mkdir -p "$ACME_DIR"
  1652. chmod 755 "$ACME_DIR"
  1653. fi
  1654. if ! _exec "$_APACHECTL" graceful; then
  1655. _exec_err
  1656. _err "$_APACHECTL graceful error, please contact me."
  1657. _restoreApache
  1658. return 1
  1659. fi
  1660. usingApache="1"
  1661. return 0
  1662. }
  1663. _clearup() {
  1664. _stopserver "$serverproc"
  1665. serverproc=""
  1666. _restoreApache
  1667. _clearupdns
  1668. if [ -z "$DEBUG" ]; then
  1669. rm -f "$TLS_CONF"
  1670. rm -f "$TLS_CERT"
  1671. rm -f "$TLS_KEY"
  1672. rm -f "$TLS_CSR"
  1673. fi
  1674. }
  1675. _clearupdns() {
  1676. _debug "_clearupdns"
  1677. if [ "$dnsadded" != 1 ] || [ -z "$vlist" ]; then
  1678. _debug "Dns not added, skip."
  1679. return
  1680. fi
  1681. ventries=$(echo "$vlist" | tr ',' ' ')
  1682. for ventry in $ventries; do
  1683. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  1684. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  1685. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  1686. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  1687. txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _urlencode)"
  1688. _debug txt "$txt"
  1689. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  1690. _info "$d is already verified, skip $vtype."
  1691. continue
  1692. fi
  1693. if [ "$vtype" != "$VTYPE_DNS" ]; then
  1694. _info "Skip $d for $vtype"
  1695. continue
  1696. fi
  1697. d_api="$(_findHook "$d" dnsapi "$_currentRoot")"
  1698. _debug d_api "$d_api"
  1699. if [ -z "$d_api" ]; then
  1700. _info "Not Found domain api file: $d_api"
  1701. continue
  1702. fi
  1703. (
  1704. if ! . "$d_api"; then
  1705. _err "Load file $d_api error. Please check your api file and try again."
  1706. return 1
  1707. fi
  1708. rmcommand="${_currentRoot}_rm"
  1709. if ! _exists "$rmcommand"; then
  1710. _err "It seems that your api file doesn't define $rmcommand"
  1711. return 1
  1712. fi
  1713. txtdomain="_acme-challenge.$d"
  1714. if ! $rmcommand "$txtdomain" "$txt"; then
  1715. _err "Error removing txt for domain:$txtdomain"
  1716. return 1
  1717. fi
  1718. )
  1719. done
  1720. }
  1721. # webroot removelevel tokenfile
  1722. _clearupwebbroot() {
  1723. __webroot="$1"
  1724. if [ -z "$__webroot" ]; then
  1725. _debug "no webroot specified, skip"
  1726. return 0
  1727. fi
  1728. _rmpath=""
  1729. if [ "$2" = '1' ]; then
  1730. _rmpath="$__webroot/.well-known"
  1731. elif [ "$2" = '2' ]; then
  1732. _rmpath="$__webroot/.well-known/acme-challenge"
  1733. elif [ "$2" = '3' ]; then
  1734. _rmpath="$__webroot/.well-known/acme-challenge/$3"
  1735. else
  1736. _debug "Skip for removelevel:$2"
  1737. fi
  1738. if [ "$_rmpath" ]; then
  1739. if [ "$DEBUG" ]; then
  1740. _debug "Debugging, skip removing: $_rmpath"
  1741. else
  1742. rm -rf "$_rmpath"
  1743. fi
  1744. fi
  1745. return 0
  1746. }
  1747. _on_before_issue() {
  1748. _debug _on_before_issue
  1749. if _hasfield "$Le_Webroot" "$NO_VALUE"; then
  1750. if ! _exists "nc"; then
  1751. _err "Please install netcat(nc) tools first."
  1752. return 1
  1753. fi
  1754. fi
  1755. _debug Le_LocalAddress "$Le_LocalAddress"
  1756. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ')
  1757. _index=1
  1758. _currentRoot=""
  1759. _addrIndex=1
  1760. for d in $alldomains; do
  1761. _debug "Check for domain" "$d"
  1762. _currentRoot="$(_getfield "$Le_Webroot" $_index)"
  1763. _debug "_currentRoot" "$_currentRoot"
  1764. _index=$(_math $_index + 1)
  1765. _checkport=""
  1766. if [ "$_currentRoot" = "$NO_VALUE" ]; then
  1767. _info "Standalone mode."
  1768. if [ -z "$Le_HTTPPort" ]; then
  1769. Le_HTTPPort=80
  1770. else
  1771. _savedomainconf "Le_HTTPPort" "$Le_HTTPPort"
  1772. fi
  1773. _checkport="$Le_HTTPPort"
  1774. elif [ "$_currentRoot" = "$W_TLS" ]; then
  1775. _info "Standalone tls mode."
  1776. if [ -z "$Le_TLSPort" ]; then
  1777. Le_TLSPort=443
  1778. else
  1779. _savedomainconf "Le_TLSPort" "$Le_TLSPort"
  1780. fi
  1781. _checkport="$Le_TLSPort"
  1782. fi
  1783. if [ "$_checkport" ]; then
  1784. _debug _checkport "$_checkport"
  1785. _checkaddr="$(_getfield "$Le_LocalAddress" $_addrIndex)"
  1786. _debug _checkaddr "$_checkaddr"
  1787. _addrIndex="$(_math $_addrIndex + 1)"
  1788. _netprc="$(_ss "$_checkport" | grep "$_checkport")"
  1789. netprc="$(echo "$_netprc" | grep "$_checkaddr")"
  1790. if [ -z "$netprc" ]; then
  1791. netprc="$(echo "$_netprc" | grep "$LOCAL_ANY_ADDRESS")"
  1792. fi
  1793. if [ "$netprc" ]; then
  1794. _err "$netprc"
  1795. _err "tcp port $_checkport is already used by $(echo "$netprc" | cut -d : -f 4)"
  1796. _err "Please stop it first"
  1797. return 1
  1798. fi
  1799. fi
  1800. done
  1801. if _hasfield "$Le_Webroot" "apache"; then
  1802. if ! _setApache; then
  1803. _err "set up apache error. Report error to me."
  1804. return 1
  1805. fi
  1806. else
  1807. usingApache=""
  1808. fi
  1809. #run pre hook
  1810. if [ "$Le_PreHook" ]; then
  1811. _info "Run pre hook:'$Le_PreHook'"
  1812. if ! (
  1813. cd "$DOMAIN_PATH" && eval "$Le_PreHook"
  1814. ); then
  1815. _err "Error when run pre hook."
  1816. return 1
  1817. fi
  1818. fi
  1819. }
  1820. _on_issue_err() {
  1821. _debug _on_issue_err
  1822. if [ "$LOG_FILE" ]; then
  1823. _err "Please check log file for more details: $LOG_FILE"
  1824. else
  1825. _err "Please add '--debug' or '--log' to check more details."
  1826. _err "See: $_DEBUG_WIKI"
  1827. fi
  1828. if [ "$DEBUG" ] && [ "$DEBUG" -gt "0" ]; then
  1829. _debug "$(_dlg_versions)"
  1830. fi
  1831. #run the post hook
  1832. if [ "$Le_PostHook" ]; then
  1833. _info "Run post hook:'$Le_PostHook'"
  1834. if ! (
  1835. cd "$DOMAIN_PATH" && eval "$Le_PostHook"
  1836. ); then
  1837. _err "Error when run post hook."
  1838. return 1
  1839. fi
  1840. fi
  1841. }
  1842. _on_issue_success() {
  1843. _debug _on_issue_success
  1844. #run the post hook
  1845. if [ "$Le_PostHook" ]; then
  1846. _info "Run post hook:'$Le_PostHook'"
  1847. if ! (
  1848. cd "$DOMAIN_PATH" && eval "$Le_PostHook"
  1849. ); then
  1850. _err "Error when run post hook."
  1851. return 1
  1852. fi
  1853. fi
  1854. #run renew hook
  1855. if [ "$IS_RENEW" ] && [ "$Le_RenewHook" ]; then
  1856. _info "Run renew hook:'$Le_RenewHook'"
  1857. if ! (
  1858. cd "$DOMAIN_PATH" && eval "$Le_RenewHook"
  1859. ); then
  1860. _err "Error when run renew hook."
  1861. return 1
  1862. fi
  1863. fi
  1864. }
  1865. updateaccount() {
  1866. _initpath
  1867. _regAccount
  1868. }
  1869. registeraccount() {
  1870. _reg_length="$1"
  1871. _initpath
  1872. _regAccount "$_reg_length"
  1873. }
  1874. __calcAccountKeyHash() {
  1875. [ -f "$ACCOUNT_KEY_PATH" ] && _digest sha256 <"$ACCOUNT_KEY_PATH"
  1876. }
  1877. #keylength
  1878. _regAccount() {
  1879. _initpath
  1880. _reg_length="$1"
  1881. if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
  1882. _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
  1883. mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
  1884. fi
  1885. if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
  1886. _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
  1887. mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
  1888. fi
  1889. if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
  1890. if ! _create_account_key "$_reg_length"; then
  1891. _err "Create account key error."
  1892. return 1
  1893. fi
  1894. fi
  1895. if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
  1896. return 1
  1897. fi
  1898. _updateTos=""
  1899. _reg_res="new-reg"
  1900. while true; do
  1901. _debug AGREEMENT "$AGREEMENT"
  1902. regjson='{"resource": "'$_reg_res'", "agreement": "'$AGREEMENT'"}'
  1903. if [ "$ACCOUNT_EMAIL" ]; then
  1904. regjson='{"resource": "'$_reg_res'", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  1905. fi
  1906. if [ -z "$_updateTos" ]; then
  1907. _info "Registering account"
  1908. if ! _send_signed_request "$API/acme/new-reg" "$regjson"; then
  1909. _err "Register account Error: $response"
  1910. return 1
  1911. fi
  1912. if [ "$code" = "" ] || [ "$code" = '201' ]; then
  1913. echo "$response" >"$ACCOUNT_JSON_PATH"
  1914. _info "Registered"
  1915. elif [ "$code" = '409' ]; then
  1916. _info "Already registered"
  1917. else
  1918. _err "Register account Error: $response"
  1919. return 1
  1920. fi
  1921. _accUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
  1922. _debug "_accUri" "$_accUri"
  1923. _tos="$(echo "$responseHeaders" | grep "^Link:.*rel=\"terms-of-service\"" | _head_n 1 | _egrep_o "<.*>" | tr -d '<>')"
  1924. _debug "_tos" "$_tos"
  1925. if [ -z "$_tos" ]; then
  1926. _debug "Use default tos: $DEFAULT_AGREEMENT"
  1927. _tos="$DEFAULT_AGREEMENT"
  1928. fi
  1929. if [ "$_tos" != "$AGREEMENT" ]; then
  1930. _updateTos=1
  1931. AGREEMENT="$_tos"
  1932. _reg_res="reg"
  1933. continue
  1934. fi
  1935. else
  1936. _debug "Update tos: $_tos"
  1937. if ! _send_signed_request "$_accUri" "$regjson"; then
  1938. _err "Update tos error."
  1939. return 1
  1940. fi
  1941. if [ "$code" = '202' ]; then
  1942. _info "Update success."
  1943. CA_KEY_HASH="$(__calcAccountKeyHash)"
  1944. _debug "Calc CA_KEY_HASH" "$CA_KEY_HASH"
  1945. _savecaconf CA_KEY_HASH "$CA_KEY_HASH"
  1946. else
  1947. _err "Update account error."
  1948. return 1
  1949. fi
  1950. fi
  1951. return 0
  1952. done
  1953. }
  1954. # domain folder file
  1955. _findHook() {
  1956. _hookdomain="$1"
  1957. _hookcat="$2"
  1958. _hookname="$3"
  1959. if [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname" ]; then
  1960. d_api="$_SCRIPT_HOME/$_hookcat/$_hookname"
  1961. elif [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname.sh" ]; then
  1962. d_api="$_SCRIPT_HOME/$_hookcat/$_hookname.sh"
  1963. elif [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname" ]; then
  1964. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname"
  1965. elif [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname.sh" ]; then
  1966. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname.sh"
  1967. elif [ -f "$LE_WORKING_DIR/$_hookname" ]; then
  1968. d_api="$LE_WORKING_DIR/$_hookname"
  1969. elif [ -f "$LE_WORKING_DIR/$_hookname.sh" ]; then
  1970. d_api="$LE_WORKING_DIR/$_hookname.sh"
  1971. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname" ]; then
  1972. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname"
  1973. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname.sh" ]; then
  1974. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname.sh"
  1975. fi
  1976. printf "%s" "$d_api"
  1977. }
  1978. #domain
  1979. __get_domain_new_authz() {
  1980. _gdnd="$1"
  1981. _info "Getting new-authz for domain" "$_gdnd"
  1982. _Max_new_authz_retry_times=5
  1983. _authz_i=0
  1984. while [ "$_authz_i" -lt "$_Max_new_authz_retry_times" ]; do
  1985. _debug "Try new-authz for the $_authz_i time."
  1986. if ! _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$(_idn "$_gdnd")\"}}"; then
  1987. _err "Can not get domain new authz."
  1988. return 1
  1989. fi
  1990. if ! _contains "$response" "An error occurred while processing your request"; then
  1991. _info "The new-authz request is ok."
  1992. break
  1993. fi
  1994. _authz_i="$(_math "$_authz_i" + 1)"
  1995. _info "The server is busy, Sleep $_authz_i to retry."
  1996. _sleep "$_authz_i"
  1997. done
  1998. if [ "$_authz_i" = "$_Max_new_authz_retry_times" ]; then
  1999. _err "new-authz retry reach the max $_Max_new_authz_retry_times times."
  2000. fi
  2001. if [ ! -z "$code" ] && [ ! "$code" = '201' ]; then
  2002. _err "new-authz error: $response"
  2003. return 1
  2004. fi
  2005. }
  2006. #webroot, domain domainlist keylength
  2007. issue() {
  2008. if [ -z "$2" ]; then
  2009. _usage "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
  2010. return 1
  2011. fi
  2012. Le_Webroot="$1"
  2013. Le_Domain="$2"
  2014. Le_Alt="$3"
  2015. Le_Keylength="$4"
  2016. Le_RealCertPath="$5"
  2017. Le_RealKeyPath="$6"
  2018. Le_RealCACertPath="$7"
  2019. Le_ReloadCmd="$8"
  2020. Le_RealFullChainPath="$9"
  2021. Le_PreHook="${10}"
  2022. Le_PostHook="${11}"
  2023. Le_RenewHook="${12}"
  2024. Le_LocalAddress="${13}"
  2025. #remove these later.
  2026. if [ "$Le_Webroot" = "dns-cf" ]; then
  2027. Le_Webroot="dns_cf"
  2028. fi
  2029. if [ "$Le_Webroot" = "dns-dp" ]; then
  2030. Le_Webroot="dns_dp"
  2031. fi
  2032. if [ "$Le_Webroot" = "dns-cx" ]; then
  2033. Le_Webroot="dns_cx"
  2034. fi
  2035. _debug "Using api: $API"
  2036. if [ ! "$IS_RENEW" ]; then
  2037. _initpath "$Le_Domain" "$Le_Keylength"
  2038. mkdir -p "$DOMAIN_PATH"
  2039. fi
  2040. if [ -f "$DOMAIN_CONF" ]; then
  2041. Le_NextRenewTime=$(_readdomainconf Le_NextRenewTime)
  2042. _debug Le_NextRenewTime "$Le_NextRenewTime"
  2043. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
  2044. _saved_domain=$(_readdomainconf Le_Domain)
  2045. _debug _saved_domain "$_saved_domain"
  2046. _saved_alt=$(_readdomainconf Le_Alt)
  2047. _debug _saved_alt "$_saved_alt"
  2048. if [ "$_saved_domain,$_saved_alt" = "$Le_Domain,$Le_Alt" ]; then
  2049. _info "Domains not changed."
  2050. _info "Skip, Next renewal time is: $(__green "$(_readdomainconf Le_NextRenewTimeStr)")"
  2051. _info "Add '$(__red '--force')' to force to renew."
  2052. return $RENEW_SKIP
  2053. else
  2054. _info "Domains have changed."
  2055. fi
  2056. fi
  2057. fi
  2058. _savedomainconf "Le_Domain" "$Le_Domain"
  2059. _savedomainconf "Le_Alt" "$Le_Alt"
  2060. _savedomainconf "Le_Webroot" "$Le_Webroot"
  2061. _savedomainconf "Le_PreHook" "$Le_PreHook"
  2062. _savedomainconf "Le_PostHook" "$Le_PostHook"
  2063. _savedomainconf "Le_RenewHook" "$Le_RenewHook"
  2064. if [ "$Le_LocalAddress" ]; then
  2065. _savedomainconf "Le_LocalAddress" "$Le_LocalAddress"
  2066. else
  2067. _cleardomainconf "Le_LocalAddress"
  2068. fi
  2069. Le_API="$API"
  2070. _savedomainconf "Le_API" "$Le_API"
  2071. if [ "$Le_Alt" = "$NO_VALUE" ]; then
  2072. Le_Alt=""
  2073. fi
  2074. if [ "$Le_Keylength" = "$NO_VALUE" ]; then
  2075. Le_Keylength=""
  2076. fi
  2077. if ! _on_before_issue; then
  2078. _err "_on_before_issue."
  2079. return 1
  2080. fi
  2081. _saved_account_key_hash="$(_readcaconf "CA_KEY_HASH")"
  2082. _debug2 _saved_account_key_hash "$_saved_account_key_hash"
  2083. if [ -z "$_saved_account_key_hash" ] || [ "$_saved_account_key_hash" != "$(__calcAccountKeyHash)" ]; then
  2084. if ! _regAccount "$_accountkeylength"; then
  2085. _on_issue_err
  2086. return 1
  2087. fi
  2088. else
  2089. _debug "_saved_account_key_hash is not changed, skip register account."
  2090. fi
  2091. if [ -f "$CSR_PATH" ] && [ ! -f "$CERT_KEY_PATH" ]; then
  2092. _info "Signing from existing CSR."
  2093. else
  2094. _key=$(_readdomainconf Le_Keylength)
  2095. _debug "Read key length:$_key"
  2096. if [ ! -f "$CERT_KEY_PATH" ] || [ "$Le_Keylength" != "$_key" ]; then
  2097. if ! createDomainKey "$Le_Domain" "$Le_Keylength"; then
  2098. _err "Create domain key error."
  2099. _clearup
  2100. _on_issue_err
  2101. return 1
  2102. fi
  2103. fi
  2104. if ! _createcsr "$Le_Domain" "$Le_Alt" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"; then
  2105. _err "Create CSR error."
  2106. _clearup
  2107. _on_issue_err
  2108. return 1
  2109. fi
  2110. fi
  2111. _savedomainconf "Le_Keylength" "$Le_Keylength"
  2112. vlist="$Le_Vlist"
  2113. _info "Getting domain auth token for each domain"
  2114. sep='#'
  2115. if [ -z "$vlist" ]; then
  2116. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ')
  2117. _index=1
  2118. _currentRoot=""
  2119. for d in $alldomains; do
  2120. _info "Getting webroot for domain" "$d"
  2121. _w="$(echo $Le_Webroot | cut -d , -f $_index)"
  2122. _info _w "$_w"
  2123. if [ "$_w" ]; then
  2124. _currentRoot="$_w"
  2125. fi
  2126. _debug "_currentRoot" "$_currentRoot"
  2127. _index=$(_math $_index + 1)
  2128. vtype="$VTYPE_HTTP"
  2129. if _startswith "$_currentRoot" "dns"; then
  2130. vtype="$VTYPE_DNS"
  2131. fi
  2132. if [ "$_currentRoot" = "$W_TLS" ]; then
  2133. vtype="$VTYPE_TLS"
  2134. fi
  2135. if ! __get_domain_new_authz "$d"; then
  2136. _clearup
  2137. _on_issue_err
  2138. return 1
  2139. fi
  2140. if [ -z "$thumbprint" ]; then
  2141. accountkey_json=$(printf "%s" "$jwk" | tr -d ' ')
  2142. thumbprint=$(printf "%s" "$accountkey_json" | _digest "sha256" | _urlencode)
  2143. fi
  2144. entry="$(printf "%s\n" "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
  2145. _debug entry "$entry"
  2146. if [ -z "$entry" ]; then
  2147. _err "Error, can not get domain token $d"
  2148. _clearup
  2149. _on_issue_err
  2150. return 1
  2151. fi
  2152. token="$(printf "%s\n" "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  2153. _debug token "$token"
  2154. uri="$(printf "%s\n" "$entry" | _egrep_o '"uri":"[^"]*' | cut -d : -f 2,3 | tr -d '"')"
  2155. _debug uri "$uri"
  2156. keyauthorization="$token.$thumbprint"
  2157. _debug keyauthorization "$keyauthorization"
  2158. if printf "%s" "$response" | grep '"status":"valid"' >/dev/null 2>&1; then
  2159. _info "$d is already verified, skip."
  2160. keyauthorization="$STATE_VERIFIED"
  2161. _debug keyauthorization "$keyauthorization"
  2162. fi
  2163. dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
  2164. _debug dvlist "$dvlist"
  2165. vlist="$vlist$dvlist,"
  2166. done
  2167. #add entry
  2168. dnsadded=""
  2169. ventries=$(echo "$vlist" | tr ',' ' ')
  2170. for ventry in $ventries; do
  2171. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  2172. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  2173. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  2174. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  2175. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  2176. _info "$d is already verified, skip $vtype."
  2177. continue
  2178. fi
  2179. if [ "$vtype" = "$VTYPE_DNS" ]; then
  2180. dnsadded='0'
  2181. txtdomain="_acme-challenge.$d"
  2182. _debug txtdomain "$txtdomain"
  2183. txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _urlencode)"
  2184. _debug txt "$txt"
  2185. d_api="$(_findHook "$d" dnsapi "$_currentRoot")"
  2186. _debug d_api "$d_api"
  2187. if [ "$d_api" ]; then
  2188. _info "Found domain api file: $d_api"
  2189. else
  2190. _err "Add the following TXT record:"
  2191. _err "Domain: '$(__green "$txtdomain")'"
  2192. _err "TXT value: '$(__green "$txt")'"
  2193. _err "Please be aware that you prepend _acme-challenge. before your domain"
  2194. _err "so the resulting subdomain will be: $txtdomain"
  2195. continue
  2196. fi
  2197. (
  2198. if ! . "$d_api"; then
  2199. _err "Load file $d_api error. Please check your api file and try again."
  2200. return 1
  2201. fi
  2202. addcommand="${_currentRoot}_add"
  2203. if ! _exists "$addcommand"; then
  2204. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  2205. return 1
  2206. fi
  2207. if ! $addcommand "$txtdomain" "$txt"; then
  2208. _err "Error add txt for domain:$txtdomain"
  2209. return 1
  2210. fi
  2211. )
  2212. if [ "$?" != "0" ]; then
  2213. _clearup
  2214. _on_issue_err
  2215. return 1
  2216. fi
  2217. dnsadded='1'
  2218. fi
  2219. done
  2220. if [ "$dnsadded" = '0' ]; then
  2221. _savedomainconf "Le_Vlist" "$vlist"
  2222. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  2223. _err "Please add the TXT records to the domains, and retry again."
  2224. _clearup
  2225. _on_issue_err
  2226. return 1
  2227. fi
  2228. fi
  2229. if [ "$dnsadded" = '1' ]; then
  2230. if [ -z "$Le_DNSSleep" ]; then
  2231. Le_DNSSleep="$DEFAULT_DNS_SLEEP"
  2232. else
  2233. _savedomainconf "Le_DNSSleep" "$Le_DNSSleep"
  2234. fi
  2235. _info "Sleep $(__green $Le_DNSSleep) seconds for the txt records to take effect"
  2236. _sleep "$Le_DNSSleep"
  2237. fi
  2238. _debug "ok, let's start to verify"
  2239. _ncIndex=1
  2240. ventries=$(echo "$vlist" | tr ',' ' ')
  2241. for ventry in $ventries; do
  2242. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  2243. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  2244. uri=$(echo "$ventry" | cut -d "$sep" -f 3)
  2245. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  2246. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  2247. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  2248. _info "$d is already verified, skip $vtype."
  2249. continue
  2250. fi
  2251. _info "Verifying:$d"
  2252. _debug "d" "$d"
  2253. _debug "keyauthorization" "$keyauthorization"
  2254. _debug "uri" "$uri"
  2255. removelevel=""
  2256. token="$(printf "%s" "$keyauthorization" | cut -d '.' -f 1)"
  2257. _debug "_currentRoot" "$_currentRoot"
  2258. if [ "$vtype" = "$VTYPE_HTTP" ]; then
  2259. if [ "$_currentRoot" = "$NO_VALUE" ]; then
  2260. _info "Standalone mode server"
  2261. _ncaddr="$(_getfield "$Le_LocalAddress" "$_ncIndex")"
  2262. _ncIndex="$(_math $_ncIndex + 1)"
  2263. _startserver "$keyauthorization" "$_ncaddr" &
  2264. if [ "$?" != "0" ]; then
  2265. _clearup
  2266. _on_issue_err
  2267. return 1
  2268. fi
  2269. serverproc="$!"
  2270. sleep 1
  2271. _debug serverproc "$serverproc"
  2272. else
  2273. if [ "$_currentRoot" = "apache" ]; then
  2274. wellknown_path="$ACME_DIR"
  2275. else
  2276. wellknown_path="$_currentRoot/.well-known/acme-challenge"
  2277. if [ ! -d "$_currentRoot/.well-known" ]; then
  2278. removelevel='1'
  2279. elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ]; then
  2280. removelevel='2'
  2281. else
  2282. removelevel='3'
  2283. fi
  2284. fi
  2285. _debug wellknown_path "$wellknown_path"
  2286. _debug "writing token:$token to $wellknown_path/$token"
  2287. mkdir -p "$wellknown_path"
  2288. if ! printf "%s" "$keyauthorization" >"$wellknown_path/$token"; then
  2289. _err "$d:Can not write token to file : $wellknown_path/$token"
  2290. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2291. _clearup
  2292. _on_issue_err
  2293. return 1
  2294. fi
  2295. if [ ! "$usingApache" ]; then
  2296. if webroot_owner=$(_stat "$_currentRoot"); then
  2297. _debug "Changing owner/group of .well-known to $webroot_owner"
  2298. chown -R "$webroot_owner" "$_currentRoot/.well-known"
  2299. else
  2300. _debug "not chaning owner/group of webroot"
  2301. fi
  2302. fi
  2303. fi
  2304. elif [ "$vtype" = "$VTYPE_TLS" ]; then
  2305. #create A
  2306. #_hash_A="$(printf "%s" $token | _digest "sha256" "hex" )"
  2307. #_debug2 _hash_A "$_hash_A"
  2308. #_x="$(echo $_hash_A | cut -c 1-32)"
  2309. #_debug2 _x "$_x"
  2310. #_y="$(echo $_hash_A | cut -c 33-64)"
  2311. #_debug2 _y "$_y"
  2312. #_SAN_A="$_x.$_y.token.acme.invalid"
  2313. #_debug2 _SAN_A "$_SAN_A"
  2314. #create B
  2315. _hash_B="$(printf "%s" "$keyauthorization" | _digest "sha256" "hex")"
  2316. _debug2 _hash_B "$_hash_B"
  2317. _x="$(echo "$_hash_B" | cut -c 1-32)"
  2318. _debug2 _x "$_x"
  2319. _y="$(echo "$_hash_B" | cut -c 33-64)"
  2320. _debug2 _y "$_y"
  2321. #_SAN_B="$_x.$_y.ka.acme.invalid"
  2322. _SAN_B="$_x.$_y.acme.invalid"
  2323. _debug2 _SAN_B "$_SAN_B"
  2324. _ncaddr="$(_getfield "$Le_LocalAddress" "$_ncIndex")"
  2325. _ncIndex="$(_math "$_ncIndex" + 1)"
  2326. if ! _starttlsserver "$_SAN_B" "$_SAN_A" "$Le_TLSPort" "$keyauthorization" "$_ncaddr"; then
  2327. _err "Start tls server error."
  2328. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2329. _clearup
  2330. _on_issue_err
  2331. return 1
  2332. fi
  2333. fi
  2334. if ! _send_signed_request "$uri" "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"; then
  2335. _err "$d:Can not get challenge: $response"
  2336. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2337. _clearup
  2338. _on_issue_err
  2339. return 1
  2340. fi
  2341. if [ ! -z "$code" ] && [ ! "$code" = '202' ]; then
  2342. _err "$d:Challenge error: $response"
  2343. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2344. _clearup
  2345. _on_issue_err
  2346. return 1
  2347. fi
  2348. waittimes=0
  2349. if [ -z "$MAX_RETRY_TIMES" ]; then
  2350. MAX_RETRY_TIMES=30
  2351. fi
  2352. while true; do
  2353. waittimes=$(_math "$waittimes" + 1)
  2354. if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ]; then
  2355. _err "$d:Timeout"
  2356. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2357. _clearup
  2358. _on_issue_err
  2359. return 1
  2360. fi
  2361. _debug "sleep 2 secs to verify"
  2362. sleep 2
  2363. _debug "checking"
  2364. response="$(_get "$uri")"
  2365. if [ "$?" != "0" ]; then
  2366. _err "$d:Verify error:$response"
  2367. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2368. _clearup
  2369. _on_issue_err
  2370. return 1
  2371. fi
  2372. _debug2 original "$response"
  2373. response="$(echo "$response" | _normalizeJson)"
  2374. _debug2 response "$response"
  2375. status=$(echo "$response" | _egrep_o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  2376. if [ "$status" = "valid" ]; then
  2377. _info "$(__green Success)"
  2378. _stopserver "$serverproc"
  2379. serverproc=""
  2380. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2381. break
  2382. fi
  2383. if [ "$status" = "invalid" ]; then
  2384. error="$(echo "$response" | tr -d "\r\n" | _egrep_o '"error":\{[^\}]*')"
  2385. _debug2 error "$error"
  2386. errordetail="$(echo "$error" | _egrep_o '"detail": *"[^"]*' | cut -d '"' -f 4)"
  2387. _debug2 errordetail "$errordetail"
  2388. if [ "$errordetail" ]; then
  2389. _err "$d:Verify error:$errordetail"
  2390. else
  2391. _err "$d:Verify error:$error"
  2392. fi
  2393. if [ "$DEBUG" ]; then
  2394. if [ "$vtype" = "$VTYPE_HTTP" ]; then
  2395. _debug "Debug: get token url."
  2396. _get "http://$d/.well-known/acme-challenge/$token" "" 1
  2397. fi
  2398. fi
  2399. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2400. _clearup
  2401. _on_issue_err
  2402. return 1
  2403. fi
  2404. if [ "$status" = "pending" ]; then
  2405. _info "Pending"
  2406. else
  2407. _err "$d:Verify error:$response"
  2408. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2409. _clearup
  2410. _on_issue_err
  2411. return 1
  2412. fi
  2413. done
  2414. done
  2415. _clearup
  2416. _info "Verify finished, start to sign."
  2417. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _urlencode)"
  2418. if ! _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"; then
  2419. _err "Sign failed."
  2420. _on_issue_err
  2421. return 1
  2422. fi
  2423. _rcert="$response"
  2424. Le_LinkCert="$(grep -i '^Location.*$' "$HTTP_HEADER" | _head_n 1 | tr -d "\r\n" | cut -d " " -f 2)"
  2425. _savedomainconf "Le_LinkCert" "$Le_LinkCert"
  2426. if [ "$Le_LinkCert" ]; then
  2427. echo "$BEGIN_CERT" >"$CERT_PATH"
  2428. #if ! _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH" ; then
  2429. # _debug "Get cert failed. Let's try last response."
  2430. # printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >> "$CERT_PATH"
  2431. #fi
  2432. if ! printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >>"$CERT_PATH"; then
  2433. _debug "Try cert link."
  2434. _get "$Le_LinkCert" | _base64 "multiline" >>"$CERT_PATH"
  2435. fi
  2436. echo "$END_CERT" >>"$CERT_PATH"
  2437. _info "$(__green "Cert success.")"
  2438. cat "$CERT_PATH"
  2439. _info "Your cert is in $(__green " $CERT_PATH ")"
  2440. if [ -f "$CERT_KEY_PATH" ]; then
  2441. _info "Your cert key is in $(__green " $CERT_KEY_PATH ")"
  2442. fi
  2443. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  2444. if [ ! "$USER_PATH" ] || [ ! "$IN_CRON" ]; then
  2445. USER_PATH="$PATH"
  2446. _saveaccountconf "USER_PATH" "$USER_PATH"
  2447. fi
  2448. fi
  2449. if [ -z "$Le_LinkCert" ]; then
  2450. response="$(echo "$response" | _dbase64 "multiline" | _normalizeJson)"
  2451. _err "Sign failed: $(echo "$response" | _egrep_o '"detail":"[^"]*"')"
  2452. _on_issue_err
  2453. return 1
  2454. fi
  2455. _cleardomainconf "Le_Vlist"
  2456. Le_LinkIssuer=$(grep -i '^Link' "$HTTP_HEADER" | _head_n 1 | cut -d " " -f 2 | cut -d ';' -f 1 | tr -d '<>')
  2457. if ! _contains "$Le_LinkIssuer" ":"; then
  2458. Le_LinkIssuer="$API$Le_LinkIssuer"
  2459. fi
  2460. _savedomainconf "Le_LinkIssuer" "$Le_LinkIssuer"
  2461. if [ "$Le_LinkIssuer" ]; then
  2462. echo "$BEGIN_CERT" >"$CA_CERT_PATH"
  2463. _get "$Le_LinkIssuer" | _base64 "multiline" >>"$CA_CERT_PATH"
  2464. echo "$END_CERT" >>"$CA_CERT_PATH"
  2465. _info "The intermediate CA cert is in $(__green " $CA_CERT_PATH ")"
  2466. cat "$CA_CERT_PATH" >>"$CERT_FULLCHAIN_PATH"
  2467. _info "And the full chain certs is there: $(__green " $CERT_FULLCHAIN_PATH ")"
  2468. fi
  2469. Le_CertCreateTime=$(_time)
  2470. _savedomainconf "Le_CertCreateTime" "$Le_CertCreateTime"
  2471. Le_CertCreateTimeStr=$(date -u)
  2472. _savedomainconf "Le_CertCreateTimeStr" "$Le_CertCreateTimeStr"
  2473. if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ] || [ "$Le_RenewalDays" -gt "$MAX_RENEW" ]; then
  2474. Le_RenewalDays="$MAX_RENEW"
  2475. else
  2476. _savedomainconf "Le_RenewalDays" "$Le_RenewalDays"
  2477. fi
  2478. if [ "$CA_BUNDLE" ]; then
  2479. _saveaccountconf CA_BUNDLE "$CA_BUNDLE"
  2480. else
  2481. _clearaccountconf "CA_BUNDLE"
  2482. fi
  2483. if [ "$HTTPS_INSECURE" ]; then
  2484. _saveaccountconf HTTPS_INSECURE "$HTTPS_INSECURE"
  2485. else
  2486. _clearaccountconf "HTTPS_INSECURE"
  2487. fi
  2488. if [ "$Le_Listen_V4" ]; then
  2489. _savedomainconf "Le_Listen_V4" "$Le_Listen_V4"
  2490. _cleardomainconf Le_Listen_V6
  2491. elif [ "$Le_Listen_V6" ]; then
  2492. _savedomainconf "Le_Listen_V6" "$Le_Listen_V6"
  2493. _cleardomainconf Le_Listen_V4
  2494. fi
  2495. Le_NextRenewTime=$(_math "$Le_CertCreateTime" + "$Le_RenewalDays" \* 24 \* 60 \* 60)
  2496. Le_NextRenewTimeStr=$(_time2str "$Le_NextRenewTime")
  2497. _savedomainconf "Le_NextRenewTimeStr" "$Le_NextRenewTimeStr"
  2498. Le_NextRenewTime=$(_math "$Le_NextRenewTime" - 86400)
  2499. _savedomainconf "Le_NextRenewTime" "$Le_NextRenewTime"
  2500. _on_issue_success
  2501. if [ "$Le_RealCertPath$Le_RealKeyPath$Le_RealCACertPath$Le_ReloadCmd$Le_RealFullChainPath" ]; then
  2502. _installcert
  2503. fi
  2504. }
  2505. #domain [isEcc]
  2506. renew() {
  2507. Le_Domain="$1"
  2508. if [ -z "$Le_Domain" ]; then
  2509. _usage "Usage: $PROJECT_ENTRY --renew -d domain.com [--ecc]"
  2510. return 1
  2511. fi
  2512. _isEcc="$2"
  2513. _initpath "$Le_Domain" "$_isEcc"
  2514. _info "$(__green "Renew: '$Le_Domain'")"
  2515. if [ ! -f "$DOMAIN_CONF" ]; then
  2516. _info "'$Le_Domain' is not a issued domain, skip."
  2517. return 0
  2518. fi
  2519. if [ "$Le_RenewalDays" ]; then
  2520. _savedomainconf Le_RenewalDays "$Le_RenewalDays"
  2521. fi
  2522. . "$DOMAIN_CONF"
  2523. if [ "$Le_API" ]; then
  2524. API="$Le_API"
  2525. fi
  2526. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
  2527. _info "Skip, Next renewal time is: $(__green "$Le_NextRenewTimeStr")"
  2528. _info "Add '$(__red '--force')' to force to renew."
  2529. return "$RENEW_SKIP"
  2530. fi
  2531. IS_RENEW="1"
  2532. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath" "$Le_PreHook" "$Le_PostHook" "$Le_RenewHook" "$Le_LocalAddress"
  2533. res="$?"
  2534. if [ "$res" != "0" ]; then
  2535. return "$res"
  2536. fi
  2537. if [ "$Le_DeployHook" ]; then
  2538. deploy "$Le_Domain" "$Le_DeployHook" "$Le_Keylength"
  2539. res="$?"
  2540. fi
  2541. IS_RENEW=""
  2542. return "$res"
  2543. }
  2544. #renewAll [stopRenewOnError]
  2545. renewAll() {
  2546. _initpath
  2547. _stopRenewOnError="$1"
  2548. _debug "_stopRenewOnError" "$_stopRenewOnError"
  2549. _ret="0"
  2550. for di in "${CERT_HOME}"/*.*/; do
  2551. _debug di "$di"
  2552. if ! [ -d "$di" ]; then
  2553. _debug "Not directory, skip: $di"
  2554. continue
  2555. fi
  2556. d=$(basename "$di")
  2557. _debug d "$d"
  2558. (
  2559. if _endswith "$d" "$ECC_SUFFIX"; then
  2560. _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
  2561. d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
  2562. fi
  2563. renew "$d" "$_isEcc"
  2564. )
  2565. rc="$?"
  2566. _debug "Return code: $rc"
  2567. if [ "$rc" != "0" ]; then
  2568. if [ "$rc" = "$RENEW_SKIP" ]; then
  2569. _info "Skipped $d"
  2570. elif [ "$_stopRenewOnError" ]; then
  2571. _err "Error renew $d, stop now."
  2572. return "$rc"
  2573. else
  2574. _ret="$rc"
  2575. _err "Error renew $d, Go ahead to next one."
  2576. fi
  2577. fi
  2578. done
  2579. return "$_ret"
  2580. }
  2581. #csr webroot
  2582. signcsr() {
  2583. _csrfile="$1"
  2584. _csrW="$2"
  2585. if [ -z "$_csrfile" ] || [ -z "$_csrW" ]; then
  2586. _usage "Usage: $PROJECT_ENTRY --signcsr --csr mycsr.csr -w /path/to/webroot/a.com/ "
  2587. return 1
  2588. fi
  2589. _initpath
  2590. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  2591. if [ "$?" != "0" ]; then
  2592. _err "Can not read subject from csr: $_csrfile"
  2593. return 1
  2594. fi
  2595. _debug _csrsubj "$_csrsubj"
  2596. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  2597. if [ "$?" != "0" ]; then
  2598. _err "Can not read domain list from csr: $_csrfile"
  2599. return 1
  2600. fi
  2601. _debug "_csrdomainlist" "$_csrdomainlist"
  2602. if [ -z "$_csrsubj" ]; then
  2603. _csrsubj="$(_getfield "$_csrdomainlist" 1)"
  2604. _debug _csrsubj "$_csrsubj"
  2605. _csrdomainlist="$(echo "$_csrdomainlist" | cut -d , -f 2-)"
  2606. _debug "_csrdomainlist" "$_csrdomainlist"
  2607. fi
  2608. if [ -z "$_csrsubj" ]; then
  2609. _err "Can not read subject from csr: $_csrfile"
  2610. return 1
  2611. fi
  2612. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  2613. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
  2614. _err "Can not read key length from csr: $_csrfile"
  2615. return 1
  2616. fi
  2617. _initpath "$_csrsubj" "$_csrkeylength"
  2618. mkdir -p "$DOMAIN_PATH"
  2619. _info "Copy csr to: $CSR_PATH"
  2620. cp "$_csrfile" "$CSR_PATH"
  2621. issue "$_csrW" "$_csrsubj" "$_csrdomainlist" "$_csrkeylength"
  2622. }
  2623. showcsr() {
  2624. _csrfile="$1"
  2625. _csrd="$2"
  2626. if [ -z "$_csrfile" ] && [ -z "$_csrd" ]; then
  2627. _usage "Usage: $PROJECT_ENTRY --showcsr --csr mycsr.csr"
  2628. return 1
  2629. fi
  2630. _initpath
  2631. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  2632. if [ "$?" != "0" ] || [ -z "$_csrsubj" ]; then
  2633. _err "Can not read subject from csr: $_csrfile"
  2634. return 1
  2635. fi
  2636. _info "Subject=$_csrsubj"
  2637. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  2638. if [ "$?" != "0" ]; then
  2639. _err "Can not read domain list from csr: $_csrfile"
  2640. return 1
  2641. fi
  2642. _debug "_csrdomainlist" "$_csrdomainlist"
  2643. _info "SubjectAltNames=$_csrdomainlist"
  2644. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  2645. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
  2646. _err "Can not read key length from csr: $_csrfile"
  2647. return 1
  2648. fi
  2649. _info "KeyLength=$_csrkeylength"
  2650. }
  2651. list() {
  2652. _raw="$1"
  2653. _initpath
  2654. _sep="|"
  2655. if [ "$_raw" ]; then
  2656. printf "%s\n" "Main_Domain${_sep}KeyLength${_sep}SAN_Domains${_sep}Created${_sep}Renew"
  2657. for di in "${CERT_HOME}"/*.*/; do
  2658. if ! [ -d "$di" ]; then
  2659. _debug "Not directory, skip: $di"
  2660. continue
  2661. fi
  2662. d=$(basename "$di")
  2663. _debug d "$d"
  2664. (
  2665. if _endswith "$d" "$ECC_SUFFIX"; then
  2666. _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
  2667. d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
  2668. fi
  2669. _initpath "$d" "$_isEcc"
  2670. if [ -f "$DOMAIN_CONF" ]; then
  2671. . "$DOMAIN_CONF"
  2672. printf "%s\n" "$Le_Domain${_sep}\"$Le_Keylength\"${_sep}$Le_Alt${_sep}$Le_CertCreateTimeStr${_sep}$Le_NextRenewTimeStr"
  2673. fi
  2674. )
  2675. done
  2676. else
  2677. if _exists column; then
  2678. list "raw" | column -t -s "$_sep"
  2679. else
  2680. list "raw" | tr "$_sep" '\t'
  2681. fi
  2682. fi
  2683. }
  2684. deploy() {
  2685. Le_Domain="$1"
  2686. Le_DeployHook="$2"
  2687. _isEcc="$3"
  2688. if [ -z "$Le_DeployHook" ]; then
  2689. _usage "Usage: $PROJECT_ENTRY --deploy -d domain.com --deploy-hook cpanel [--ecc] "
  2690. return 1
  2691. fi
  2692. _initpath "$Le_Domain" "$_isEcc"
  2693. if [ ! -d "$DOMAIN_PATH" ]; then
  2694. _err "Domain is not valid:'$Le_Domain'"
  2695. return 1
  2696. fi
  2697. _deployApi="$(_findHook "$Le_Domain" deploy "$Le_DeployHook")"
  2698. if [ -z "$_deployApi" ]; then
  2699. _err "The deploy hook $Le_DeployHook is not found."
  2700. return 1
  2701. fi
  2702. _debug _deployApi "$_deployApi"
  2703. _savedomainconf Le_DeployHook "$Le_DeployHook"
  2704. if ! (
  2705. if ! . "$_deployApi"; then
  2706. _err "Load file $_deployApi error. Please check your api file and try again."
  2707. return 1
  2708. fi
  2709. d_command="${Le_DeployHook}_deploy"
  2710. if ! _exists "$d_command"; then
  2711. _err "It seems that your api file is not correct, it must have a function named: $d_command"
  2712. return 1
  2713. fi
  2714. if ! $d_command "$Le_Domain" "$CERT_KEY_PATH" "$CERT_PATH" "$CA_CERT_PATH" "$CERT_FULLCHAIN_PATH"; then
  2715. _err "Error deploy for domain:$Le_Domain"
  2716. _on_issue_err
  2717. return 1
  2718. fi
  2719. ); then
  2720. _err "Deploy error."
  2721. return 1
  2722. else
  2723. _info "$(__green Success)"
  2724. fi
  2725. }
  2726. installcert() {
  2727. Le_Domain="$1"
  2728. if [ -z "$Le_Domain" ]; then
  2729. _usage "Usage: $PROJECT_ENTRY --installcert -d domain.com [--ecc] [--certpath cert-file-path] [--keypath key-file-path] [--capath ca-cert-file-path] [ --reloadCmd reloadCmd] [--fullchainpath fullchain-path]"
  2730. return 1
  2731. fi
  2732. Le_RealCertPath="$2"
  2733. Le_RealKeyPath="$3"
  2734. Le_RealCACertPath="$4"
  2735. Le_ReloadCmd="$5"
  2736. Le_RealFullChainPath="$6"
  2737. _isEcc="$7"
  2738. _initpath "$Le_Domain" "$_isEcc"
  2739. if [ ! -d "$DOMAIN_PATH" ]; then
  2740. _err "Domain is not valid:'$Le_Domain'"
  2741. return 1
  2742. fi
  2743. _installcert
  2744. }
  2745. _installcert() {
  2746. _savedomainconf "Le_RealCertPath" "$Le_RealCertPath"
  2747. _savedomainconf "Le_RealCACertPath" "$Le_RealCACertPath"
  2748. _savedomainconf "Le_RealKeyPath" "$Le_RealKeyPath"
  2749. _savedomainconf "Le_ReloadCmd" "$Le_ReloadCmd"
  2750. _savedomainconf "Le_RealFullChainPath" "$Le_RealFullChainPath"
  2751. if [ "$Le_RealCertPath" = "$NO_VALUE" ]; then
  2752. Le_RealCertPath=""
  2753. fi
  2754. if [ "$Le_RealKeyPath" = "$NO_VALUE" ]; then
  2755. Le_RealKeyPath=""
  2756. fi
  2757. if [ "$Le_RealCACertPath" = "$NO_VALUE" ]; then
  2758. Le_RealCACertPath=""
  2759. fi
  2760. if [ "$Le_ReloadCmd" = "$NO_VALUE" ]; then
  2761. Le_ReloadCmd=""
  2762. fi
  2763. if [ "$Le_RealFullChainPath" = "$NO_VALUE" ]; then
  2764. Le_RealFullChainPath=""
  2765. fi
  2766. if [ "$Le_RealCertPath" ]; then
  2767. _info "Installing cert to:$Le_RealCertPath"
  2768. if [ -f "$Le_RealCertPath" ] && [ ! "$IS_RENEW" ]; then
  2769. cp "$Le_RealCertPath" "$Le_RealCertPath".bak
  2770. fi
  2771. cat "$CERT_PATH" >"$Le_RealCertPath"
  2772. fi
  2773. if [ "$Le_RealCACertPath" ]; then
  2774. _info "Installing CA to:$Le_RealCACertPath"
  2775. if [ "$Le_RealCACertPath" = "$Le_RealCertPath" ]; then
  2776. echo "" >>"$Le_RealCACertPath"
  2777. cat "$CA_CERT_PATH" >>"$Le_RealCACertPath"
  2778. else
  2779. if [ -f "$Le_RealCACertPath" ] && [ ! "$IS_RENEW" ]; then
  2780. cp "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  2781. fi
  2782. cat "$CA_CERT_PATH" >"$Le_RealCACertPath"
  2783. fi
  2784. fi
  2785. if [ "$Le_RealKeyPath" ]; then
  2786. _info "Installing key to:$Le_RealKeyPath"
  2787. if [ -f "$Le_RealKeyPath" ] && [ ! "$IS_RENEW" ]; then
  2788. cp "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  2789. fi
  2790. cat "$CERT_KEY_PATH" >"$Le_RealKeyPath"
  2791. fi
  2792. if [ "$Le_RealFullChainPath" ]; then
  2793. _info "Installing full chain to:$Le_RealFullChainPath"
  2794. if [ -f "$Le_RealFullChainPath" ] && [ ! "$IS_RENEW" ]; then
  2795. cp "$Le_RealFullChainPath" "$Le_RealFullChainPath".bak
  2796. fi
  2797. cat "$CERT_FULLCHAIN_PATH" >"$Le_RealFullChainPath"
  2798. fi
  2799. if [ "$Le_ReloadCmd" ]; then
  2800. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  2801. if (cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd"); then
  2802. _info "$(__green "Reload success")"
  2803. else
  2804. _err "Reload error for :$Le_Domain"
  2805. fi
  2806. fi
  2807. }
  2808. installcronjob() {
  2809. _initpath
  2810. if ! _exists "crontab"; then
  2811. _err "crontab doesn't exist, so, we can not install cron jobs."
  2812. _err "All your certs will not be renewed automatically."
  2813. _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
  2814. return 1
  2815. fi
  2816. _info "Installing cron job"
  2817. if ! crontab -l | grep "$PROJECT_ENTRY --cron"; then
  2818. if [ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ]; then
  2819. lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
  2820. else
  2821. _err "Can not install cronjob, $PROJECT_ENTRY not found."
  2822. return 1
  2823. fi
  2824. if _exists uname && uname -a | grep solaris >/dev/null; then
  2825. crontab -l | {
  2826. cat
  2827. echo "0 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  2828. } | crontab --
  2829. else
  2830. crontab -l | {
  2831. cat
  2832. echo "0 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  2833. } | crontab -
  2834. fi
  2835. fi
  2836. if [ "$?" != "0" ]; then
  2837. _err "Install cron job failed. You need to manually renew your certs."
  2838. _err "Or you can add cronjob by yourself:"
  2839. _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  2840. return 1
  2841. fi
  2842. }
  2843. uninstallcronjob() {
  2844. if ! _exists "crontab"; then
  2845. return
  2846. fi
  2847. _info "Removing cron job"
  2848. cr="$(crontab -l | grep "$PROJECT_ENTRY --cron")"
  2849. if [ "$cr" ]; then
  2850. if _exists uname && uname -a | grep solaris >/dev/null; then
  2851. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab --
  2852. else
  2853. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab -
  2854. fi
  2855. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
  2856. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  2857. fi
  2858. _initpath
  2859. }
  2860. revoke() {
  2861. Le_Domain="$1"
  2862. if [ -z "$Le_Domain" ]; then
  2863. _usage "Usage: $PROJECT_ENTRY --revoke -d domain.com"
  2864. return 1
  2865. fi
  2866. _isEcc="$2"
  2867. _initpath "$Le_Domain" "$_isEcc"
  2868. if [ ! -f "$DOMAIN_CONF" ]; then
  2869. _err "$Le_Domain is not a issued domain, skip."
  2870. return 1
  2871. fi
  2872. if [ ! -f "$CERT_PATH" ]; then
  2873. _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
  2874. return 1
  2875. fi
  2876. cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}" | tr -d "\r\n" | _urlencode)"
  2877. if [ -z "$cert" ]; then
  2878. _err "Cert for $Le_Domain is empty found, skip."
  2879. return 1
  2880. fi
  2881. data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
  2882. uri="$API/acme/revoke-cert"
  2883. if [ -f "$CERT_KEY_PATH" ]; then
  2884. _info "Try domain key first."
  2885. if _send_signed_request "$uri" "$data" "" "$CERT_KEY_PATH"; then
  2886. if [ -z "$response" ]; then
  2887. _info "Revoke success."
  2888. rm -f "$CERT_PATH"
  2889. return 0
  2890. else
  2891. _err "Revoke error by domain key."
  2892. _err "$response"
  2893. fi
  2894. fi
  2895. else
  2896. _info "Domain key file doesn't exists."
  2897. fi
  2898. _info "Try account key."
  2899. if _send_signed_request "$uri" "$data" "" "$ACCOUNT_KEY_PATH"; then
  2900. if [ -z "$response" ]; then
  2901. _info "Revoke success."
  2902. rm -f "$CERT_PATH"
  2903. return 0
  2904. else
  2905. _err "Revoke error."
  2906. _debug "$response"
  2907. fi
  2908. fi
  2909. return 1
  2910. }
  2911. #domain vtype
  2912. _deactivate() {
  2913. _d_domain="$1"
  2914. _d_type="$2"
  2915. _initpath
  2916. _d_i=0
  2917. _d_max_retry=9
  2918. while [ "$_d_i" -lt "$_d_max_retry" ]; do
  2919. _info "Deactivate: $_d_domain"
  2920. _d_i="$(_math $_d_i + 1)"
  2921. if ! __get_domain_new_authz "$_d_domain"; then
  2922. _err "Can not get domain new authz token."
  2923. return 1
  2924. fi
  2925. authzUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
  2926. _debug "authzUri" "$authzUri"
  2927. if [ ! -z "$code" ] && [ ! "$code" = '201' ]; then
  2928. _err "new-authz error: $response"
  2929. return 1
  2930. fi
  2931. entry="$(printf "%s\n" "$response" | _egrep_o '[^\{]*"status":"valid","uri"[^\}]*')"
  2932. _debug entry "$entry"
  2933. if [ -z "$entry" ]; then
  2934. _info "No more valid entry found."
  2935. break
  2936. fi
  2937. _vtype="$(printf "%s\n" "$entry" | _egrep_o '"type": *"[^"]*"' | cut -d : -f 2 | tr -d '"')"
  2938. _debug _vtype "$_vtype"
  2939. _info "Found $_vtype"
  2940. uri="$(printf "%s\n" "$entry" | _egrep_o '"uri":"[^"]*' | cut -d : -f 2,3 | tr -d '"')"
  2941. _debug uri "$uri"
  2942. if [ "$_d_type" ] && [ "$_d_type" != "$_vtype" ]; then
  2943. _info "Skip $_vtype"
  2944. continue
  2945. fi
  2946. _info "Deactivate: $_vtype"
  2947. if ! _send_signed_request "$authzUri" "{\"resource\": \"authz\", \"status\":\"deactivated\"}"; then
  2948. _err "Can not deactivate $_vtype."
  2949. return 1
  2950. fi
  2951. _info "Deactivate: $_vtype success."
  2952. done
  2953. _debug "$_d_i"
  2954. if [ "$_d_i" -lt "$_d_max_retry" ]; then
  2955. _info "Deactivated success!"
  2956. else
  2957. _err "Deactivate failed."
  2958. fi
  2959. }
  2960. deactivate() {
  2961. _d_domain_list="$1"
  2962. _d_type="$2"
  2963. _initpath
  2964. _debug _d_domain_list "$_d_domain_list"
  2965. if [ -z "$(echo $_d_domain_list | cut -d , -f 1)" ]; then
  2966. _usage "Usage: $PROJECT_ENTRY --deactivate -d domain.com [-d domain.com]"
  2967. return 1
  2968. fi
  2969. for _d_dm in $(echo "$_d_domain_list" | tr ',' ' '); do
  2970. if [ -z "$_d_dm" ] || [ "$_d_dm" = "$NO_VALUE" ]; then
  2971. continue
  2972. fi
  2973. if ! _deactivate "$_d_dm" "$_d_type"; then
  2974. return 1
  2975. fi
  2976. done
  2977. }
  2978. # Detect profile file if not specified as environment variable
  2979. _detect_profile() {
  2980. if [ -n "$PROFILE" -a -f "$PROFILE" ]; then
  2981. echo "$PROFILE"
  2982. return
  2983. fi
  2984. DETECTED_PROFILE=''
  2985. SHELLTYPE="$(basename "/$SHELL")"
  2986. if [ "$SHELLTYPE" = "bash" ]; then
  2987. if [ -f "$HOME/.bashrc" ]; then
  2988. DETECTED_PROFILE="$HOME/.bashrc"
  2989. elif [ -f "$HOME/.bash_profile" ]; then
  2990. DETECTED_PROFILE="$HOME/.bash_profile"
  2991. fi
  2992. elif [ "$SHELLTYPE" = "zsh" ]; then
  2993. DETECTED_PROFILE="$HOME/.zshrc"
  2994. fi
  2995. if [ -z "$DETECTED_PROFILE" ]; then
  2996. if [ -f "$HOME/.profile" ]; then
  2997. DETECTED_PROFILE="$HOME/.profile"
  2998. elif [ -f "$HOME/.bashrc" ]; then
  2999. DETECTED_PROFILE="$HOME/.bashrc"
  3000. elif [ -f "$HOME/.bash_profile" ]; then
  3001. DETECTED_PROFILE="$HOME/.bash_profile"
  3002. elif [ -f "$HOME/.zshrc" ]; then
  3003. DETECTED_PROFILE="$HOME/.zshrc"
  3004. fi
  3005. fi
  3006. if [ ! -z "$DETECTED_PROFILE" ]; then
  3007. echo "$DETECTED_PROFILE"
  3008. fi
  3009. }
  3010. _initconf() {
  3011. _initpath
  3012. if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
  3013. echo "#ACCOUNT_CONF_PATH=xxxx
  3014. #Account configurations:
  3015. #Here are the supported macros, uncomment them to make them take effect.
  3016. #ACCOUNT_EMAIL=aaa@example.com # the account email used to register account.
  3017. #ACCOUNT_KEY_PATH=\"/path/to/account.key\"
  3018. #CERT_HOME=\"/path/to/cert/home\"
  3019. #LOG_FILE=\"$DEFAULT_LOG_FILE\"
  3020. #LOG_LEVEL=1
  3021. #AUTO_UPGRADE=\"1\"
  3022. #STAGE=1 # Use the staging api
  3023. #FORCE=1 # Force to issue cert
  3024. #DEBUG=1 # Debug mode
  3025. #NO_TIMESTAMP=1
  3026. #OPENSSL_BIN=openssl
  3027. #USER_AGENT=\"$USER_AGENT\"
  3028. #USER_PATH=
  3029. #dns api
  3030. #######################
  3031. #Cloudflare:
  3032. #api key
  3033. #CF_Key=\"sdfsdfsdfljlbjkljlkjsdfoiwje\"
  3034. #account email
  3035. #CF_Email=\"xxxx@sss.com\"
  3036. #######################
  3037. #Dnspod.cn:
  3038. #api key id
  3039. #DP_Id=\"1234\"
  3040. #api key
  3041. #DP_Key=\"sADDsdasdgdsf\"
  3042. #######################
  3043. #Cloudxns.com:
  3044. #CX_Key=\"1234\"
  3045. #
  3046. #CX_Secret=\"sADDsdasdgdsf\"
  3047. #######################
  3048. #Godaddy.com:
  3049. #GD_Key=\"sdfdsgdgdfdasfds\"
  3050. #
  3051. #GD_Secret=\"sADDsdasdfsdfdssdgdsf\"
  3052. #######################
  3053. #nsupdate:
  3054. #NSUPDATE_KEY=\"/path/to/update.key\"
  3055. #NSUPDATE_SERVER=\"192.168.0.1\"
  3056. #######################
  3057. #PowerDNS:
  3058. #PDNS_Url=\"http://ns.example.com:8081\"
  3059. #PDNS_ServerId=\"localhost\"
  3060. #PDNS_Token=\"0123456789ABCDEF\"
  3061. #PDNS_Ttl=60
  3062. #######################
  3063. #Amazon Route53:
  3064. #AWS_ACCESS_KEY_ID=XXXXXXXXXX
  3065. #AWS_SECRET_ACCESS_KEY=XXXXXXXXXXXXXXX
  3066. " >"$ACCOUNT_CONF_PATH"
  3067. fi
  3068. }
  3069. # nocron
  3070. _precheck() {
  3071. _nocron="$1"
  3072. if ! _exists "curl" && ! _exists "wget"; then
  3073. _err "Please install curl or wget first, we need to access http resources."
  3074. return 1
  3075. fi
  3076. if [ -z "$_nocron" ]; then
  3077. if ! _exists "crontab"; then
  3078. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  3079. _err "We need to set cron job to renew the certs automatically."
  3080. _err "Otherwise, your certs will not be able to be renewed automatically."
  3081. if [ -z "$FORCE" ]; then
  3082. _err "Please add '--force' and try install again to go without crontab."
  3083. _err "./$PROJECT_ENTRY --install --force"
  3084. return 1
  3085. fi
  3086. fi
  3087. fi
  3088. if ! _exists "$OPENSSL_BIN"; then
  3089. _err "Please install openssl first."
  3090. _err "We need openssl to generate keys."
  3091. return 1
  3092. fi
  3093. if ! _exists "nc"; then
  3094. _err "It is recommended to install nc first, try to install 'nc' or 'netcat'."
  3095. _err "We use nc for standalone server if you use standalone mode."
  3096. _err "If you don't use standalone mode, just ignore this warning."
  3097. fi
  3098. return 0
  3099. }
  3100. _setShebang() {
  3101. _file="$1"
  3102. _shebang="$2"
  3103. if [ -z "$_shebang" ]; then
  3104. _usage "Usage: file shebang"
  3105. return 1
  3106. fi
  3107. cp "$_file" "$_file.tmp"
  3108. echo "$_shebang" >"$_file"
  3109. sed -n 2,99999p "$_file.tmp" >>"$_file"
  3110. rm -f "$_file.tmp"
  3111. }
  3112. _installalias() {
  3113. _initpath
  3114. _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  3115. if [ "$_upgrading" ] && [ "$_upgrading" = "1" ]; then
  3116. echo "$(cat "$_envfile")" | sed "s|^LE_WORKING_DIR.*$||" >"$_envfile"
  3117. echo "$(cat "$_envfile")" | sed "s|^alias le.*$||" >"$_envfile"
  3118. echo "$(cat "$_envfile")" | sed "s|^alias le.sh.*$||" >"$_envfile"
  3119. fi
  3120. _setopt "$_envfile" "export LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
  3121. _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  3122. _profile="$(_detect_profile)"
  3123. if [ "$_profile" ]; then
  3124. _debug "Found profile: $_profile"
  3125. _info "Installing alias to '$_profile'"
  3126. _setopt "$_profile" ". \"$_envfile\""
  3127. _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
  3128. else
  3129. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
  3130. fi
  3131. #for csh
  3132. _cshfile="$LE_WORKING_DIR/$PROJECT_ENTRY.csh"
  3133. _csh_profile="$HOME/.cshrc"
  3134. if [ -f "$_csh_profile" ]; then
  3135. _info "Installing alias to '$_csh_profile'"
  3136. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  3137. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  3138. _setopt "$_csh_profile" "source \"$_cshfile\""
  3139. fi
  3140. #for tcsh
  3141. _tcsh_profile="$HOME/.tcshrc"
  3142. if [ -f "$_tcsh_profile" ]; then
  3143. _info "Installing alias to '$_tcsh_profile'"
  3144. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  3145. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  3146. _setopt "$_tcsh_profile" "source \"$_cshfile\""
  3147. fi
  3148. }
  3149. # nocron
  3150. install() {
  3151. if [ -z "$LE_WORKING_DIR" ]; then
  3152. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  3153. fi
  3154. _nocron="$1"
  3155. if ! _initpath; then
  3156. _err "Install failed."
  3157. return 1
  3158. fi
  3159. if [ "$_nocron" ]; then
  3160. _debug "Skip install cron job"
  3161. fi
  3162. if ! _precheck "$_nocron"; then
  3163. _err "Pre-check failed, can not install."
  3164. return 1
  3165. fi
  3166. #convert from le
  3167. if [ -d "$HOME/.le" ]; then
  3168. for envfile in "le.env" "le.sh.env"; do
  3169. if [ -f "$HOME/.le/$envfile" ]; then
  3170. if grep "le.sh" "$HOME/.le/$envfile" >/dev/null; then
  3171. _upgrading="1"
  3172. _info "You are upgrading from le.sh"
  3173. _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
  3174. mv "$HOME/.le" "$LE_WORKING_DIR"
  3175. mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  3176. break
  3177. fi
  3178. fi
  3179. done
  3180. fi
  3181. _info "Installing to $LE_WORKING_DIR"
  3182. if ! mkdir -p "$LE_WORKING_DIR"; then
  3183. _err "Can not create working dir: $LE_WORKING_DIR"
  3184. return 1
  3185. fi
  3186. chmod 700 "$LE_WORKING_DIR"
  3187. cp "$PROJECT_ENTRY" "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
  3188. if [ "$?" != "0" ]; then
  3189. _err "Install failed, can not copy $PROJECT_ENTRY"
  3190. return 1
  3191. fi
  3192. _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
  3193. _installalias
  3194. for subf in $_SUB_FOLDERS; do
  3195. if [ -d "$subf" ]; then
  3196. mkdir -p "$LE_WORKING_DIR/$subf"
  3197. cp "$subf"/* "$LE_WORKING_DIR"/"$subf"/
  3198. fi
  3199. done
  3200. if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
  3201. _initconf
  3202. fi
  3203. if [ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ]; then
  3204. _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
  3205. fi
  3206. if [ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ]; then
  3207. _saveaccountconf "CERT_HOME" "$CERT_HOME"
  3208. fi
  3209. if [ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ]; then
  3210. _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
  3211. fi
  3212. if [ -z "$_nocron" ]; then
  3213. installcronjob
  3214. fi
  3215. if [ -z "$NO_DETECT_SH" ]; then
  3216. #Modify shebang
  3217. if _exists bash; then
  3218. _info "Good, bash is found, so change the shebang to use bash as prefered."
  3219. _shebang='#!/usr/bin/env bash'
  3220. _setShebang "$LE_WORKING_DIR/$PROJECT_ENTRY" "$_shebang"
  3221. for subf in $_SUB_FOLDERS; do
  3222. if [ -d "$LE_WORKING_DIR/$subf" ]; then
  3223. for _apifile in "$LE_WORKING_DIR/$subf/"*.sh; do
  3224. _setShebang "$_apifile" "$_shebang"
  3225. done
  3226. fi
  3227. done
  3228. fi
  3229. fi
  3230. _info OK
  3231. }
  3232. # nocron
  3233. uninstall() {
  3234. _nocron="$1"
  3235. if [ -z "$_nocron" ]; then
  3236. uninstallcronjob
  3237. fi
  3238. _initpath
  3239. _uninstallalias
  3240. rm -f "$LE_WORKING_DIR/$PROJECT_ENTRY"
  3241. _info "The keys and certs are in $LE_WORKING_DIR, you can remove them by yourself."
  3242. }
  3243. _uninstallalias() {
  3244. _initpath
  3245. _profile="$(_detect_profile)"
  3246. if [ "$_profile" ]; then
  3247. _info "Uninstalling alias from: '$_profile'"
  3248. text="$(cat "$_profile")"
  3249. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.env\"$||" >"$_profile"
  3250. fi
  3251. _csh_profile="$HOME/.cshrc"
  3252. if [ -f "$_csh_profile" ]; then
  3253. _info "Uninstalling alias from: '$_csh_profile'"
  3254. text="$(cat "$_csh_profile")"
  3255. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_csh_profile"
  3256. fi
  3257. _tcsh_profile="$HOME/.tcshrc"
  3258. if [ -f "$_tcsh_profile" ]; then
  3259. _info "Uninstalling alias from: '$_csh_profile'"
  3260. text="$(cat "$_tcsh_profile")"
  3261. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_tcsh_profile"
  3262. fi
  3263. }
  3264. cron() {
  3265. IN_CRON=1
  3266. _initpath
  3267. if [ "$AUTO_UPGRADE" = "1" ]; then
  3268. export LE_WORKING_DIR
  3269. (
  3270. if ! upgrade; then
  3271. _err "Cron:Upgrade failed!"
  3272. return 1
  3273. fi
  3274. )
  3275. . "$LE_WORKING_DIR/$PROJECT_ENTRY" >/dev/null
  3276. if [ -t 1 ]; then
  3277. __INTERACTIVE="1"
  3278. fi
  3279. _info "Auto upgraded to: $VER"
  3280. fi
  3281. renewAll
  3282. _ret="$?"
  3283. IN_CRON=""
  3284. exit $_ret
  3285. }
  3286. version() {
  3287. echo "$PROJECT"
  3288. echo "v$VER"
  3289. }
  3290. showhelp() {
  3291. _initpath
  3292. version
  3293. echo "Usage: $PROJECT_ENTRY command ...[parameters]....
  3294. Commands:
  3295. --help, -h Show this help message.
  3296. --version, -v Show version info.
  3297. --install Install $PROJECT_NAME to your system.
  3298. --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
  3299. --upgrade Upgrade $PROJECT_NAME to the latest code from $PROJECT .
  3300. --issue Issue a cert.
  3301. --signcsr Issue a cert from an existing csr.
  3302. --deploy Deploy the cert to your server.
  3303. --installcert Install the issued cert to apache/nginx or any other server.
  3304. --renew, -r Renew a cert.
  3305. --renewAll Renew all the certs.
  3306. --revoke Revoke a cert.
  3307. --list List all the certs.
  3308. --showcsr Show the content of a csr.
  3309. --installcronjob Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  3310. --uninstallcronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
  3311. --cron Run cron job to renew all the certs.
  3312. --toPkcs Export the certificate and key to a pfx file.
  3313. --updateaccount Update account info.
  3314. --registeraccount Register account key.
  3315. --createAccountKey, -cak Create an account private key, professional use.
  3316. --createDomainKey, -cdk Create an domain private key, professional use.
  3317. --createCSR, -ccsr Create CSR , professional use.
  3318. --deactivate Deactivate the domain authz, professional use.
  3319. Parameters:
  3320. --domain, -d domain.tld Specifies a domain, used to issue, renew or revoke etc.
  3321. --force, -f Used to force to install or force to renew a cert immediately.
  3322. --staging, --test Use staging server, just for test.
  3323. --debug Output debug info.
  3324. --webroot, -w /path/to/webroot Specifies the web root folder for web root mode.
  3325. --standalone Use standalone mode.
  3326. --tls Use standalone tls mode.
  3327. --apache Use apache mode.
  3328. --dns [dns_cf|dns_dp|dns_cx|/path/to/api/file] Use dns mode or dns api.
  3329. --dnssleep [$DEFAULT_DNS_SLEEP] The time in seconds to wait for all the txt records to take effect in dns api mode. Default $DEFAULT_DNS_SLEEP seconds.
  3330. --keylength, -k [2048] Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384.
  3331. --accountkeylength, -ak [2048] Specifies the account key length.
  3332. --log [/path/to/logfile] Specifies the log file. The default is: \"$DEFAULT_LOG_FILE\" if you don't give a file path here.
  3333. --log-level 1|2 Specifies the log level, default is 1.
  3334. These parameters are to install the cert to nginx/apache or anyother server after issue/renew a cert:
  3335. --certpath /path/to/real/cert/file After issue/renew, the cert will be copied to this path.
  3336. --keypath /path/to/real/key/file After issue/renew, the key will be copied to this path.
  3337. --capath /path/to/real/ca/file After issue/renew, the intermediate cert will be copied to this path.
  3338. --fullchainpath /path/to/fullchain/file After issue/renew, the fullchain cert will be copied to this path.
  3339. --reloadcmd \"service nginx reload\" After issue/renew, it's used to reload the server.
  3340. --accountconf Specifies a customized account config file.
  3341. --home Specifies the home dir for $PROJECT_NAME .
  3342. --certhome Specifies the home dir to save all the certs, only valid for '--install' command.
  3343. --useragent Specifies the user agent string. it will be saved for future use too.
  3344. --accountemail Specifies the account email for registering, Only valid for the '--install' command.
  3345. --accountkey Specifies the account key path, Only valid for the '--install' command.
  3346. --days Specifies the days to renew the cert when using '--issue' command. The max value is $MAX_RENEW days.
  3347. --httpport Specifies the standalone listening port. Only valid if the server is behind a reverse proxy or load balancer.
  3348. --tlsport Specifies the standalone tls listening port. Only valid if the server is behind a reverse proxy or load balancer.
  3349. --local-address Specifies the standalone/tls server listening address, in case you have multiple ip addresses.
  3350. --listraw Only used for '--list' command, list the certs in raw format.
  3351. --stopRenewOnError, -se Only valid for '--renewall' command. Stop if one cert has error in renewal.
  3352. --insecure Do not check the server certificate, in some devices, the api server's certificate may not be trusted.
  3353. --ca-bundle Specifices the path to the CA certificate bundle to verify api server's certificate.
  3354. --nocron Only valid for '--install' command, which means: do not install the default cron job. In this case, the certs will not be renewed automatically.
  3355. --ecc Specifies to use the ECC cert. Valid for '--installcert', '--renew', '--revoke', '--toPkcs' and '--createCSR'
  3356. --csr Specifies the input csr.
  3357. --pre-hook Command to be run before obtaining any certificates.
  3358. --post-hook Command to be run after attempting to obtain/renew certificates. No matter the obain/renew is success or failed.
  3359. --renew-hook Command to be run once for each successfully renewed certificate.
  3360. --deploy-hook The hook file to deploy cert
  3361. --ocsp-must-staple, --ocsp Generate ocsp must Staple extension.
  3362. --auto-upgrade [0|1] Valid for '--upgrade' command, indicating whether to upgrade automatically in future.
  3363. --listen-v4 Force standalone/tls server to listen at ipv4.
  3364. --listen-v6 Force standalone/tls server to listen at ipv6.
  3365. --openssl-bin Specifies a custom openssl bin location.
  3366. "
  3367. }
  3368. # nocron
  3369. _installOnline() {
  3370. _info "Installing from online archive."
  3371. _nocron="$1"
  3372. if [ ! "$BRANCH" ]; then
  3373. BRANCH="master"
  3374. fi
  3375. target="$PROJECT/archive/$BRANCH.tar.gz"
  3376. _info "Downloading $target"
  3377. localname="$BRANCH.tar.gz"
  3378. if ! _get "$target" >$localname; then
  3379. _err "Download error."
  3380. return 1
  3381. fi
  3382. (
  3383. _info "Extracting $localname"
  3384. tar xzf $localname
  3385. cd "$PROJECT_NAME-$BRANCH"
  3386. chmod +x $PROJECT_ENTRY
  3387. if ./$PROJECT_ENTRY install "$_nocron"; then
  3388. _info "Install success!"
  3389. fi
  3390. cd ..
  3391. rm -rf "$PROJECT_NAME-$BRANCH"
  3392. rm -f "$localname"
  3393. )
  3394. }
  3395. upgrade() {
  3396. if (
  3397. _initpath
  3398. export LE_WORKING_DIR
  3399. cd "$LE_WORKING_DIR"
  3400. _installOnline "nocron"
  3401. ); then
  3402. _info "Upgrade success!"
  3403. exit 0
  3404. else
  3405. _err "Upgrade failed!"
  3406. exit 1
  3407. fi
  3408. }
  3409. _processAccountConf() {
  3410. if [ "$_useragent" ]; then
  3411. _saveaccountconf "USER_AGENT" "$_useragent"
  3412. elif [ "$USER_AGENT" ] && [ "$USER_AGENT" != "$DEFAULT_USER_AGENT" ]; then
  3413. _saveaccountconf "USER_AGENT" "$USER_AGENT"
  3414. fi
  3415. if [ "$_accountemail" ]; then
  3416. _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
  3417. elif [ "$ACCOUNT_EMAIL" ] && [ "$ACCOUNT_EMAIL" != "$DEFAULT_ACCOUNT_EMAIL" ]; then
  3418. _saveaccountconf "ACCOUNT_EMAIL" "$ACCOUNT_EMAIL"
  3419. fi
  3420. if [ "$_openssl_bin" ]; then
  3421. _saveaccountconf "OPENSSL_BIN" "$_openssl_bin"
  3422. elif [ "$OPENSSL_BIN" ] && [ "$OPENSSL_BIN" != "$DEFAULT_OPENSSL_BIN" ]; then
  3423. _saveaccountconf "OPENSSL_BIN" "$OPENSSL_BIN"
  3424. fi
  3425. if [ "$_auto_upgrade" ]; then
  3426. _saveaccountconf "AUTO_UPGRADE" "$_auto_upgrade"
  3427. elif [ "$AUTO_UPGRADE" ]; then
  3428. _saveaccountconf "AUTO_UPGRADE" "$AUTO_UPGRADE"
  3429. fi
  3430. }
  3431. _process() {
  3432. _CMD=""
  3433. _domain=""
  3434. _altdomains="$NO_VALUE"
  3435. _webroot=""
  3436. _keylength=""
  3437. _accountkeylength=""
  3438. _certpath=""
  3439. _keypath=""
  3440. _capath=""
  3441. _fullchainpath=""
  3442. _reloadcmd=""
  3443. _password=""
  3444. _accountconf=""
  3445. _useragent=""
  3446. _accountemail=""
  3447. _accountkey=""
  3448. _certhome=""
  3449. _httpport=""
  3450. _tlsport=""
  3451. _dnssleep=""
  3452. _listraw=""
  3453. _stopRenewOnError=""
  3454. #_insecure=""
  3455. _ca_bundle=""
  3456. _nocron=""
  3457. _ecc=""
  3458. _csr=""
  3459. _pre_hook=""
  3460. _post_hook=""
  3461. _renew_hook=""
  3462. _deploy_hook=""
  3463. _logfile=""
  3464. _log=""
  3465. _local_address=""
  3466. _log_level=""
  3467. _auto_upgrade=""
  3468. _listen_v4=""
  3469. _listen_v6=""
  3470. _openssl_bin=""
  3471. while [ ${#} -gt 0 ]; do
  3472. case "${1}" in
  3473. --help | -h)
  3474. showhelp
  3475. return
  3476. ;;
  3477. --version | -v)
  3478. version
  3479. return
  3480. ;;
  3481. --install)
  3482. _CMD="install"
  3483. ;;
  3484. --uninstall)
  3485. _CMD="uninstall"
  3486. ;;
  3487. --upgrade)
  3488. _CMD="upgrade"
  3489. ;;
  3490. --issue)
  3491. _CMD="issue"
  3492. ;;
  3493. --deploy)
  3494. _CMD="deploy"
  3495. ;;
  3496. --signcsr)
  3497. _CMD="signcsr"
  3498. ;;
  3499. --showcsr)
  3500. _CMD="showcsr"
  3501. ;;
  3502. --installcert | -i)
  3503. _CMD="installcert"
  3504. ;;
  3505. --renew | -r)
  3506. _CMD="renew"
  3507. ;;
  3508. --renewAll | --renewall)
  3509. _CMD="renewAll"
  3510. ;;
  3511. --revoke)
  3512. _CMD="revoke"
  3513. ;;
  3514. --list)
  3515. _CMD="list"
  3516. ;;
  3517. --installcronjob)
  3518. _CMD="installcronjob"
  3519. ;;
  3520. --uninstallcronjob)
  3521. _CMD="uninstallcronjob"
  3522. ;;
  3523. --cron)
  3524. _CMD="cron"
  3525. ;;
  3526. --toPkcs)
  3527. _CMD="toPkcs"
  3528. ;;
  3529. --createAccountKey | --createaccountkey | -cak)
  3530. _CMD="createAccountKey"
  3531. ;;
  3532. --createDomainKey | --createdomainkey | -cdk)
  3533. _CMD="createDomainKey"
  3534. ;;
  3535. --createCSR | --createcsr | -ccr)
  3536. _CMD="createCSR"
  3537. ;;
  3538. --deactivate)
  3539. _CMD="deactivate"
  3540. ;;
  3541. --updateaccount)
  3542. _CMD="updateaccount"
  3543. ;;
  3544. --registeraccount)
  3545. _CMD="registeraccount"
  3546. ;;
  3547. --domain | -d)
  3548. _dvalue="$2"
  3549. if [ "$_dvalue" ]; then
  3550. if _startswith "$_dvalue" "-"; then
  3551. _err "'$_dvalue' is not a valid domain for parameter '$1'"
  3552. return 1
  3553. fi
  3554. if _is_idn "$_dvalue" && ! _exists idn; then
  3555. _err "It seems that $_dvalue is an IDN( Internationalized Domain Names), please install 'idn' command first."
  3556. return 1
  3557. fi
  3558. if [ -z "$_domain" ]; then
  3559. _domain="$_dvalue"
  3560. else
  3561. if [ "$_altdomains" = "$NO_VALUE" ]; then
  3562. _altdomains="$_dvalue"
  3563. else
  3564. _altdomains="$_altdomains,$_dvalue"
  3565. fi
  3566. fi
  3567. fi
  3568. shift
  3569. ;;
  3570. --force | -f)
  3571. FORCE="1"
  3572. ;;
  3573. --staging | --test)
  3574. STAGE="1"
  3575. ;;
  3576. --debug)
  3577. if [ -z "$2" ] || _startswith "$2" "-"; then
  3578. DEBUG="1"
  3579. else
  3580. DEBUG="$2"
  3581. shift
  3582. fi
  3583. ;;
  3584. --webroot | -w)
  3585. wvalue="$2"
  3586. if [ -z "$_webroot" ]; then
  3587. _webroot="$wvalue"
  3588. else
  3589. _webroot="$_webroot,$wvalue"
  3590. fi
  3591. shift
  3592. ;;
  3593. --standalone)
  3594. wvalue="$NO_VALUE"
  3595. if [ -z "$_webroot" ]; then
  3596. _webroot="$wvalue"
  3597. else
  3598. _webroot="$_webroot,$wvalue"
  3599. fi
  3600. ;;
  3601. --local-address)
  3602. lvalue="$2"
  3603. _local_address="$_local_address$lvalue,"
  3604. shift
  3605. ;;
  3606. --apache)
  3607. wvalue="apache"
  3608. if [ -z "$_webroot" ]; then
  3609. _webroot="$wvalue"
  3610. else
  3611. _webroot="$_webroot,$wvalue"
  3612. fi
  3613. ;;
  3614. --tls)
  3615. wvalue="$W_TLS"
  3616. if [ -z "$_webroot" ]; then
  3617. _webroot="$wvalue"
  3618. else
  3619. _webroot="$_webroot,$wvalue"
  3620. fi
  3621. ;;
  3622. --dns)
  3623. wvalue="dns"
  3624. if ! _startswith "$2" "-"; then
  3625. wvalue="$2"
  3626. shift
  3627. fi
  3628. if [ -z "$_webroot" ]; then
  3629. _webroot="$wvalue"
  3630. else
  3631. _webroot="$_webroot,$wvalue"
  3632. fi
  3633. ;;
  3634. --dnssleep)
  3635. _dnssleep="$2"
  3636. Le_DNSSleep="$_dnssleep"
  3637. shift
  3638. ;;
  3639. --keylength | -k)
  3640. _keylength="$2"
  3641. shift
  3642. ;;
  3643. --accountkeylength | -ak)
  3644. _accountkeylength="$2"
  3645. shift
  3646. ;;
  3647. --certpath)
  3648. _certpath="$2"
  3649. shift
  3650. ;;
  3651. --keypath)
  3652. _keypath="$2"
  3653. shift
  3654. ;;
  3655. --capath)
  3656. _capath="$2"
  3657. shift
  3658. ;;
  3659. --fullchainpath)
  3660. _fullchainpath="$2"
  3661. shift
  3662. ;;
  3663. --reloadcmd | --reloadCmd)
  3664. _reloadcmd="$2"
  3665. shift
  3666. ;;
  3667. --password)
  3668. _password="$2"
  3669. shift
  3670. ;;
  3671. --accountconf)
  3672. _accountconf="$2"
  3673. ACCOUNT_CONF_PATH="$_accountconf"
  3674. shift
  3675. ;;
  3676. --home)
  3677. LE_WORKING_DIR="$2"
  3678. shift
  3679. ;;
  3680. --certhome)
  3681. _certhome="$2"
  3682. CERT_HOME="$_certhome"
  3683. shift
  3684. ;;
  3685. --useragent)
  3686. _useragent="$2"
  3687. USER_AGENT="$_useragent"
  3688. shift
  3689. ;;
  3690. --accountemail)
  3691. _accountemail="$2"
  3692. ACCOUNT_EMAIL="$_accountemail"
  3693. shift
  3694. ;;
  3695. --accountkey)
  3696. _accountkey="$2"
  3697. ACCOUNT_KEY_PATH="$_accountkey"
  3698. shift
  3699. ;;
  3700. --days)
  3701. _days="$2"
  3702. Le_RenewalDays="$_days"
  3703. shift
  3704. ;;
  3705. --httpport)
  3706. _httpport="$2"
  3707. Le_HTTPPort="$_httpport"
  3708. shift
  3709. ;;
  3710. --tlsport)
  3711. _tlsport="$2"
  3712. Le_TLSPort="$_tlsport"
  3713. shift
  3714. ;;
  3715. --listraw)
  3716. _listraw="raw"
  3717. ;;
  3718. --stopRenewOnError | --stoprenewonerror | -se)
  3719. _stopRenewOnError="1"
  3720. ;;
  3721. --insecure)
  3722. #_insecure="1"
  3723. HTTPS_INSECURE="1"
  3724. ;;
  3725. --ca-bundle)
  3726. _ca_bundle="$(readlink -f "$2")"
  3727. CA_BUNDLE="$_ca_bundle"
  3728. shift
  3729. ;;
  3730. --nocron)
  3731. _nocron="1"
  3732. ;;
  3733. --ecc)
  3734. _ecc="isEcc"
  3735. ;;
  3736. --csr)
  3737. _csr="$2"
  3738. shift
  3739. ;;
  3740. --pre-hook)
  3741. _pre_hook="$2"
  3742. shift
  3743. ;;
  3744. --post-hook)
  3745. _post_hook="$2"
  3746. shift
  3747. ;;
  3748. --renew-hook)
  3749. _renew_hook="$2"
  3750. shift
  3751. ;;
  3752. --deploy-hook)
  3753. _deploy_hook="$2"
  3754. shift
  3755. ;;
  3756. --ocsp-must-staple | --ocsp)
  3757. Le_OCSP_Stable="1"
  3758. ;;
  3759. --log | --logfile)
  3760. _log="1"
  3761. _logfile="$2"
  3762. if _startswith "$_logfile" '-'; then
  3763. _logfile=""
  3764. else
  3765. shift
  3766. fi
  3767. LOG_FILE="$_logfile"
  3768. if [ -z "$LOG_LEVEL" ]; then
  3769. LOG_LEVEL="$DEFAULT_LOG_LEVEL"
  3770. fi
  3771. ;;
  3772. --log-level)
  3773. _log_level="$2"
  3774. LOG_LEVEL="$_log_level"
  3775. shift
  3776. ;;
  3777. --auto-upgrade)
  3778. _auto_upgrade="$2"
  3779. if [ -z "$_auto_upgrade" ] || _startswith "$_auto_upgrade" '-'; then
  3780. _auto_upgrade="1"
  3781. else
  3782. shift
  3783. fi
  3784. AUTO_UPGRADE="$_auto_upgrade"
  3785. ;;
  3786. --listen-v4)
  3787. _listen_v4="1"
  3788. Le_Listen_V4="$_listen_v4"
  3789. ;;
  3790. --listen-v6)
  3791. _listen_v6="1"
  3792. Le_Listen_V6="$_listen_v6"
  3793. ;;
  3794. --openssl-bin)
  3795. _openssl_bin="$2"
  3796. OPENSSL_BIN="$_openssl_bin"
  3797. ;;
  3798. *)
  3799. _err "Unknown parameter : $1"
  3800. return 1
  3801. ;;
  3802. esac
  3803. shift 1
  3804. done
  3805. if [ "${_CMD}" != "install" ]; then
  3806. __initHome
  3807. if [ "$_log" ]; then
  3808. if [ -z "$_logfile" ]; then
  3809. _logfile="$DEFAULT_LOG_FILE"
  3810. fi
  3811. fi
  3812. if [ "$_logfile" ]; then
  3813. _saveaccountconf "LOG_FILE" "$_logfile"
  3814. LOG_FILE="$_logfile"
  3815. fi
  3816. if [ "$_log_level" ]; then
  3817. _saveaccountconf "LOG_LEVEL" "$_log_level"
  3818. LOG_LEVEL="$_log_level"
  3819. fi
  3820. _processAccountConf
  3821. fi
  3822. _debug2 LE_WORKING_DIR "$LE_WORKING_DIR"
  3823. if [ "$DEBUG" ]; then
  3824. version
  3825. fi
  3826. case "${_CMD}" in
  3827. install) install "$_nocron" ;;
  3828. uninstall) uninstall "$_nocron" ;;
  3829. upgrade) upgrade ;;
  3830. issue)
  3831. issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address"
  3832. ;;
  3833. deploy)
  3834. deploy "$_domain" "$_deploy_hook" "$_ecc"
  3835. ;;
  3836. signcsr)
  3837. signcsr "$_csr" "$_webroot"
  3838. ;;
  3839. showcsr)
  3840. showcsr "$_csr" "$_domain"
  3841. ;;
  3842. installcert)
  3843. installcert "$_domain" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath" "$_ecc"
  3844. ;;
  3845. renew)
  3846. renew "$_domain" "$_ecc"
  3847. ;;
  3848. renewAll)
  3849. renewAll "$_stopRenewOnError"
  3850. ;;
  3851. revoke)
  3852. revoke "$_domain" "$_ecc"
  3853. ;;
  3854. deactivate)
  3855. deactivate "$_domain,$_altdomains"
  3856. ;;
  3857. registeraccount)
  3858. registeraccount "$_accountkeylength"
  3859. ;;
  3860. updateaccount)
  3861. updateaccount
  3862. ;;
  3863. list)
  3864. list "$_listraw"
  3865. ;;
  3866. installcronjob) installcronjob ;;
  3867. uninstallcronjob) uninstallcronjob ;;
  3868. cron) cron ;;
  3869. toPkcs)
  3870. toPkcs "$_domain" "$_password" "$_ecc"
  3871. ;;
  3872. createAccountKey)
  3873. createAccountKey "$_accountkeylength"
  3874. ;;
  3875. createDomainKey)
  3876. createDomainKey "$_domain" "$_keylength"
  3877. ;;
  3878. createCSR)
  3879. createCSR "$_domain" "$_altdomains" "$_ecc"
  3880. ;;
  3881. *)
  3882. _err "Invalid command: $_CMD"
  3883. showhelp
  3884. return 1
  3885. ;;
  3886. esac
  3887. _ret="$?"
  3888. if [ "$_ret" != "0" ]; then
  3889. return $_ret
  3890. fi
  3891. if [ "${_CMD}" = "install" ]; then
  3892. if [ "$_log" ]; then
  3893. if [ -z "$LOG_FILE" ]; then
  3894. LOG_FILE="$DEFAULT_LOG_FILE"
  3895. fi
  3896. _saveaccountconf "LOG_FILE" "$LOG_FILE"
  3897. fi
  3898. if [ "$_log_level" ]; then
  3899. _saveaccountconf "LOG_LEVEL" "$_log_level"
  3900. fi
  3901. _processAccountConf
  3902. fi
  3903. }
  3904. if [ "$INSTALLONLINE" ]; then
  3905. INSTALLONLINE=""
  3906. _installOnline $BRANCH
  3907. exit
  3908. fi
  3909. main() {
  3910. [ -z "$1" ] && showhelp && return
  3911. if _startswith "$1" '-'; then _process "$@"; else "$@"; fi
  3912. }
  3913. main "$@"