acme.sh 112 KB

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