acme.sh 112 KB

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